diff --git a/README.markdown b/README.markdown deleted file mode 100644 index 3a6b1f8f..00000000 --- a/README.markdown +++ /dev/null @@ -1,1135 +0,0 @@ -[![Build Status](https://travis-ci.org/josegonzalez/cakephp-upload.png?branch=master)](https://travis-ci.org/josegonzalez/cakephp-upload) [![Coverage Status](https://coveralls.io/repos/josegonzalez/cakephp-upload/badge.png?branch=master)](https://coveralls.io/r/josegonzalez/cakephp-upload?branch=master) [![Total Downloads](https://poser.pugx.org/josegonzalez/cakephp-upload/d/total.png)](https://packagist.org/packages/josegonzalez/cakephp-upload) [![Latest Stable Version](https://poser.pugx.org/josegonzalez/cakephp-upload/v/stable.png)](https://packagist.org/packages/josegonzalez/cakephp-upload) - -# Upload Plugin 2.0 - -The Upload Plugin is an attempt to sanely upload files using techniques garnered packages such as [MeioUpload](http://github.com/jrbasso/MeioUpload) , [UploadPack](http://github.com/szajbus/cakephp-uploadpack) and [PHP documentation](http://php.net/manual/en/features.file-upload.php). - -## Background - -Media Plugin is too complicated, and it was a PITA to merge the latest updates into MeioUpload, so here I am, building yet another upload plugin. I'll build another in a month and call it "YAUP". - -## Requirements - -* CakePHP 2.x -* Imagick/GD PHP Extension (for Thumbnail Creation) -* PHP5 -* Patience - -## Installation - -_[Using [Composer](http://getcomposer.org/)]_ - -[View on Packagist](https://packagist.org/packages/josegonzalez/cakephp-upload), and copy the json snippet for the latest version into your project's `composer.json` (See [http://book.cakephp.org/2.0/en/installation/advanced-installation.html](http://book.cakephp.org/2.0/en/installation/advanced-installation.html) about how to setup your `composer.json` file). Eg, v. 1.1.1 would look like this: - -```javascript -{ - "require": { - "josegonzalez/cakephp-upload": "1.1.1" - } -} -``` - -Because this plugin has the type `cakephp-plugin` set in it's own `composer.json`, composer knows to install it inside your `/Plugins` directory, rather than in the usual vendors file. It is recommended that you add `/Plugins/Upload` to your .gitignore file. (Why? [read this](http://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md).) - -_[Manual]_ - -* Download this: [http://github.com/josegonzalez/cakephp-upload/zipball/master](http://github.com/josegonzalez/cakephp-upload/zipball/master) -* Unzip that download. -* Copy the resulting folder to `app/Plugin` -* Rename the folder you just copied to `Upload` - -_[GIT Submodule]_ - -In your app directory type: - -```shell -git submodule add -b master git://github.com/josegonzalez/cakephp-upload.git Plugin/Upload -git submodule init -git submodule update -``` - -_[GIT Clone]_ - -In your `Plugin` directory type: - -```shell -git clone -b master git://github.com/josegonzalez/cakephp-upload.git Upload -``` - -### Imagick Support - -To enable Imagick support, you need to have imagick installed: - -```shell -# Debian systems -sudo apt-get install php-imagick - -# OS X Homebrew -brew tap homebrew/dupes -brew tap josegonzalez/homebrew-php -brew install php54-imagick - -# From pecl -pecl install imagick -``` - -If you cannot install imagick, please do not use imagick, and instead configure the plugin with `'thumbnailMethod' => 'php'` in your setup options, at your model (see below, **Thumbnail Creation**). - -### Enable plugin - -In 2.0 you need to enable the plugin your `app/Config/bootstrap.php` file: - -```php - -``` - -If you are already using `CakePlugin::loadAll();`, then this is not necessary. - -## Usage - -> Note: You may want to define the Upload behavior *before* the core Translate Behavior as they have been known to conflict with each other. - -```sql -CREATE table users ( - id int(10) unsigned NOT NULL auto_increment, - username varchar(20) NOT NULL, - photo varchar(255) -); -``` - -```php - array( - 'photo' - ) - ); -} -?> -``` - -```php -Form->create('User', array('type' => 'file')); ?> -Form->input('User.username'); ?> -Form->input('User.photo', array('type' => 'file')); ?> -Form->end(); ?> -``` - -Using the above setup, uploaded files cannot be deleted. To do so, a field must be added to store the directory of the file as follows: - -```sql -CREATE table users ( - `id` int(10) unsigned NOT NULL auto_increment, - `username` varchar(20) NOT NULL, - `photo` varchar(255) DEFAULT NULL, - `photo_dir` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`) -); -``` - -```php - array( - 'photo' => array( - 'fields' => array( - 'dir' => 'photo_dir' - ) - ) - ) - ); -} -?> -``` - -In the above example, photo can be a file upload via a file input within a form, a file grabber (from a url) via a text input, OR programatically used on the controller to file grab via a url. - -Files are stored in path `app/webroot/files///`. - -### File Upload Example - -```php -Form->create('User', array('type' => 'file')); ?> - Form->input('User.username'); ?> - Form->input('User.photo', array('type' => 'file')); ?> - Form->input('User.photo_dir', array('type' => 'hidden')); ?> -Form->end(); ?> -``` - -### File Grabbing via Form Example - -```php -Form->create('User', array('type' => 'file')); ?> - Form->input('User.username'); ?> - Form->input('User.photo', array('type' => 'file')); ?> - Form->input('User.photo_dir', array('type' => 'hidden')); ?> -Form->end(); ?> -``` - -### Programmatic File Retrieval without a Form - -```php -User->set(array('photo' => $image_url)); -$this->User->save(); -?> -``` - -### Thumbnail Creation - -Thumbnails are not automatically created. To do so, thumbnail sizes must be defined: - -```php - array( - 'photo' => array( - 'thumbnailSizes' => array( - 'xvga' => '1024x768', - 'vga' => '640x480', - 'thumb' => '80x80' - ) - ) - ) - ); -} -?> -``` - -Note: by default thumbnails will be generated by imagick, if you want to use GD you need to set the thumbnailMethod attribute. Example: `'thumbnailMethod' => 'php'`. - -```php - array( - 'photo' => array( - 'fields' => array( - 'dir' => 'photo_dir' - ) - ), - 'thumbnailSizes' => array( - 'xvga' => '1024x768', - 'vga' => '640x480', - 'thumb' => '80x80' - ) - ), - 'thumbnailMethod' => 'php' - ) - ); -} -?> -``` - -### Uploading Multiple files - -Multiple files can also be attached to a single record: - -```php - array( - 'resume', - 'photo' => array( - 'fields' => array( - 'dir' => 'photo_dir' - ) - ) - ) - ); -} -?> -``` - -Each key in the `Upload.Upload` array is a field name, and can contain it's own configuration. For example, you might want to set different fields for storing file paths: - -```php - array( - 'resume' => array( - 'fields' => array( - 'dir' => 'resume_dir', - 'type' => 'resume_type', - 'size' => 'resume_size', - ) - ), - 'photo' => array( - 'fields' => array( - 'dir' => 'photo_dir', - 'type' => 'photo_type', - 'size' => 'photo_size', - ) - ) - ) - ); -} -?> -``` - -Keep in mind that while this plugin does not have any limits in terms of number of files uploaded per request, you should keep this down in order to decrease the ability of your users to block other requests. - -### PDF Support - -It is now possible to generate a thumbnail for the first page of a PDF file. (Only works with the `imagick` `thumbnailMethod`.) - -Please read about the Behavior options for more details as to how to configure this plugin. - -### Using a Polymorphic Attachment Model for File Storage - -In some cases you will want to store multiple file uploads for multiple models, but will not want to use multiple tables for some reason. For example, we might have a `Post` model that can have many images for a gallery, and a `Message` model that has many videos. In this case, we would use an `Attachment` model: - -Post hasMany Attachment - -We could use the following database schema for the `Attachment` model: - -```sql -CREATE table attachments ( - `id` int(10) unsigned NOT NULL auto_increment, - `model` varchar(20) NOT NULL, - `foreign_key` int(11) NOT NULL, - `name` varchar(32) NOT NULL, - `attachment` varchar(255) NOT NULL, - `dir` varchar(255) DEFAULT NULL, - `type` varchar(255) DEFAULT NULL, - `size` int(11) DEFAULT 0, - `active` tinyint(1) DEFAULT 1, - PRIMARY KEY (`id`) -); -``` - -Our attachment records would thus be able to have a name and be activated/de-activated on the fly. The schema is simply an example, and such functionality would need to be implemented within your application. - -Once the `attachments` table has been created, we would create the following model: - -```php - array( - 'attachment' => array( - 'thumbnailSizes' => array( - 'xvga' => '1024x768', - 'vga' => '640x480', - 'thumb' => '80x80', - ), - ), - ), - ); - - public $belongsTo = array( - 'Post' => array( - 'className' => 'Post', - 'foreignKey' => 'foreign_key', - ), - 'Message' => array( - 'className' => 'Message', - 'foreignKey' => 'foreign_key', - ), - ); -} -?> -``` - -We would also need to present a valid counter-relationship in the `Post` model: - -```php - array( - 'className' => 'Attachment', - 'foreignKey' => 'foreign_key', - 'conditions' => array( - 'Image.model' => 'Post', - ), - ), - ); -} -?> -``` - -The key thing to note here is the `Post` model has some conditions on the relationship to the `Attachment` model, where the `Image.model` has to be `Post`. Remember to set the `model` field to `Post`, or whatever model it is you'd like to attach it to, otherwise you may get incorrect relationship results when performing find queries. - -We would also need a similar relationship in our `Message` model: - -```php - array( - 'className' => 'Attachment', - 'foreignKey' => 'foreign_key', - 'conditions' => array( - 'Video.model' => 'Message', - ), - ), - ); -} -?> -``` - -Now that we have our models setup, we should create the proper actions in our controllers. To keep this short, we shall only document the Post model: - -```php -request->is('post')) { - try { - $this->Post->createWithAttachments($this->request->data); - $this->Session->setFlash(__('The message has been saved')); - } catch (Exception $e) { - $this->Session->setFlash($e->getMessage()); - } - } - } -} -?> -``` - -In the above example, we are calling our custom `createWithAttachments` method on the `Post` model. This will allow us to unify the Post creation logic together in one place. That method is outlined below: - -```php - $image) { - if (is_array($data['Image'][$i])) { - // Force setting the `model` field to this model - $image['model'] = 'Post'; - - // Unset the foreign_key if the user tries to specify it - if (isset($image['foreign_key'])) { - unset($image['foreign_key']); - } - - $images[] = $image; - } - } - } - $data['Image'] = $images; - - // Try to save the data using Model::saveAll() - $this->create(); - if ($this->saveAll($data)) { - return true; - } - - // Throw an exception for the controller - throw new Exception(__("This post could not be saved. Please try again")); - } -} -?> -``` - -The above model method will: - -- Ensure we only try to save valid images -- Force the foreign_key to be unspecified. This will allow saveAll to properly associate it -- Force the model field to `Post` - -Now that this is set, we just need a view for our controller. A sample view for `View/Posts/add.ctp` is as follows (fields not necessary for the example are omitted): - -```php -Form->create('Post', array('type' => 'file')); - echo $this->Form->input('Image.0.attachment', array('type' => 'file', 'label' => 'Image')); - echo $this->Form->input('Image.0.model', array('type' => 'hidden', 'value' => 'Post')); - echo $this->Form->end(__('Add')); -?> -``` - -The one important thing you'll notice is that I am not referring to the `Attachment` model as `Attachment`, but rather as `Image`; when I initially specified the `$hasMany` relationship between an `Attachment` and a `Post`, I aliased `Attachment` to `Image`. This is necessary for cases where many of your Polymorphic models may be related to each other, as a type of *hint* to the CakePHP ORM to properly reference model data. - -I'm also using `Model.{n}.field` notation, which would allow you to add multiple attachment records to the Post. This is necessary for `$hasMany` relationships, which we are using for this example. - -Once you have all the above in place, you'll have a working Polymorphic upload! - -Please note that this is not the only way to represent file uploads, but it is documented here for reference. - -### Alternative Behaviors - -The Upload plugin also comes with a `FileImport` behavior and a `FileGrabber` behavior. - -#### FileImportBehavior - -`FileImportBehavior` may be used to import files directly from the disk. This is useful in importing from a directory already on the filesystem. - -## Behavior options: - -* `pathMethod`: The method to use for file paths. This is appended to the `path` option below - * Default: (string) `primaryKey` - * Options: - * `flat`: Does not create a path for each record. Files are moved to the value of the 'path' option. - * `primaryKey`: Path based upon the record's primaryKey is generated. Persists across a record update. - * `random`: Random path is generated for each file upload in the form `nn/nn/nn` where `nn` are random numbers. Does not persist across a record update. - * `randomCombined`: Random path - with model id - is generated for each file upload in the form `ID/nn/nn/nn` where `ID` is the current model's ID and `nn` are random numbers. Does not persist across a record update. -* `path`: A path relative to the `rootDir`. Should end in `{DS}` - * Default: (string) `'{ROOT}webroot{DS}files{DS}{model}{DS}{field}{DS}'` - * Tokens: - * {ROOT}: Replaced by a `rootDir` option - * {DS}: Replaced by a `DIRECTORY_SEPARATOR` - * {model}: Replaced by the Model Alias. - * {field}: Replaced by the field name. - * {primaryKey}: Replaced by the record primary key, when available. If used on a new record being created, will have undefined behavior. - * {size}: Replaced by a zero-length string (the empty string) when used for the regular file upload path. Only available for resized thumbnails. - * {geometry}: Replaced by a zero-length string (the empty string) when used for the regular file upload path. Only available for resized thumbnails. -* `fields`: An array of fields to use when uploading files - * Default: (array) `array('dir' => 'dir', 'type' => 'type', 'size' => 'size')` - * Options: - * dir: Field to use for storing the directory - * type: Field to use for storing the filetype - * size: Field to use for storing the filesize -* `rootDir`: Root directory for moving images. Auto-prepended to `path` and `thumbnailPath` where necessary - * Default (string) `ROOT . DS . APP_DIR . DS` -* `mimetypes`: Array of mimetypes to use for validation - * Default: (array) empty -* `extensions`: Array of extensions to use for validation - * Default: (array) empty -* `maxSize`: Max filesize in bytes for validation - * Default: (int) `2097152` -* `minSize`: Minimum filesize in bytes for validation - * Default: (int) `8` -* `maxHeight`: Maximum image height for validation - * Default: (int) `0` -* `minHeight`: Minimum image height for validation - * Default: (int) `0` -* `maxWidth`: Maximum image width for validation - * Default: (int) `0` -* `minWidth`: Minimum image width for validation - * Default: (int) `0` -* `deleteOnUpdate`: Whether to delete files when uploading new versions (potentially dangerous due to naming conflicts) - * Default: (boolean) `false` -* `thumbnails`: Whether to create thumbnails or not - * Default: (boolean) `true` -* `thumbnailMethod`: The method to use for resizing thumbnails - * Default: (string) `imagick` - * Options: - * imagick: Uses the PHP `imagick` extension to generate thumbnails - * php: Uses the built-in PHP methods (`GD` extension) to generate thumbnails. Does not support BMP images. -* `thumbnailName`: Naming style for a thumbnail - * Default: `NULL` - * Note: The tokens `{size}`, `{geometry}` and `{filename}` are valid for naming and will be auto-replaced with the actual terms. - * Note: As well, the extension of the file will be automatically added. - * Note: When left unspecified, will be set to `{size}_{filename}` or `{filename}_{size}` depending upon the value of `thumbnailPrefixStyle` -* `thumbnailPath`: A path relative to the `rootDir` where thumbnails will be saved. Should end in `{DS}`. If not set, thumbnails will be saved at `path`. - * Default: `NULL` - * Tokens: - * {ROOT}: Replaced by a `rootDir` option - * {DS}: Replaced by a `DIRECTORY_SEPARATOR` - * {model}: Replaced by the Model Alias - * {field}: Replaced by the field name - * {size}: Replaced by the size key specified by a given `thumbnailSize` - * {geometry}: Replaced by the geometry value specified by a given `thumbnailSize` -* `thumbnailPrefixStyle`: Whether to prefix or suffix the style onto thumbnails - * Default: (boolean) `true` prefix the thumbnail - * Note that this overrides `thumbnailName` when `thumbnailName` is not specified in your config -* `thumbnailQuality`: Quality of thumbnails that will be generated, on a scale of 0-100. Not supported gif images when using GD for image manipulation. - * Default: (int) `75` -* `thumbnailSizes`: Array of thumbnail sizes, with the size-name mapping to a geometry - * Default: (array) empty -* `thumbnailType`: Override the type of the generated thumbnail - * Default: (mixed) `false` or `png` when the upload is a Media file - * Options: - * Any valid image type -* `mediaThumbnailType`: Override the type of the generated thumbnail for a non-image media (`pdfs`). Overrides `thumbnailType` - * Default: (mixed) `png` - * Options: - * Any valid image type -* `saveDir`: Can be used to turn off saving the directory - * Default: (boolean) `true` - * Note: Because of the way in which the directory is saved, if you are using a `pathMethod` other than flat and you set `saveDir` to false, you may end up in situations where the file is in a location that you cannot predict. This is more of an issue for a `pathMethod` of `random` and `randomCombined` than `primaryKey`, but keep this in mind when fiddling with this option -* `deleteFolderOnDelete`: Delete folder related to current record on record delete - * Default: (boolean) `false` - * Note: Because of the way in which the directory is saved, if you are using a `pathMethod` of flat, turning this setting on will delete all your images. As such, setting this to true can be potentially dangerous. -* `keepFilesOnDelete`: Keep *all* files when uploading/deleting a record. - * Default: (boolean) `false` - * Note: This does not override `deleteFolderOnDelete`. If you set that setting to true, your images may still be deleted. This is so that existing uploads are not deleted - unless overwritten. -* `mode`: The UNIX permissions to set on the created upload directories. - * Default: (integer) `0777` -* `handleUploadedFileCallback`: If set to a method name available on your model, this model method will handle the movement of the original file on disk. Can be used in conjunction with `thumbnailMethod` to store your files in alternative locations, such as S3. - * Default: `NULL` - * Available arguments: - * `string $field`: Field being manipulated - * `string $filename`: The filename of the uploaded file - * `string $destination`: The configured destination of the moved file -* `nameCallback`: A callback that can be used to rename a file. Currently only handles original file naming. - * Default: `NULL` - * Available arguments: - * `string $field`: Field being manipulated - * `string $currentName` - * `array $data` - * `array options`: - * `isThumbnail` - a boolean field that is on when we are trying to infer a thumbnail path - * `rootDir` - root directory to replace `{ROOT}` - * `geometry` - * `size` - * `thumbnailType` - * `thumbnailName` - * `thumbnailMethod` - * `mediaThumbnailType` - * `dir` field name - * `saveType` - create, update, delete - -## Thumbnail Sizes and Styles - -Styles are the definition of thumbnails that will be generated for original image. You can define as many as you want. - -```php - array( - 'photo' => array( - 'thumbnailSizes' => array( - 'big' => '200x200', - 'small' => '120x120' - 'thumb' => '80x80' - ) - ) - ) - ); -} -?> -``` - -Styles only apply to images of the following types: - -* image/bmp -* image/gif -* image/jpeg -* image/pjpeg -* image/png -* image/vnd.microsoft.icon -* image/x-icon - -You can specify any of the following resize modes for your sizes: - -* `100x80` - resize for best fit into these dimensions, with overlapping edges trimmed if original aspect ratio differs -* `[100x80]` - resize to fit these dimensions, with white banding if original aspect ratio differs -* `100w` - maintain original aspect ratio, resize to 100 pixels wide -* `80h` - maintain original aspect ratio, resize to 80 pixels high -* `80l` - maintain original aspect ratio, resize so that longest side is 80 pixels -* `600mw` - maintain original aspect ratio, resize to max 600 pixels wide, or copy the original image if it is less than 600 pixels wide -* `800mh` - maintain original aspect ratio, resize to max 800 pixels high, or copy the original image if it is less than 800 pixels high -* `960ml` - maintain original aspect ratio, resize so that longest side is max 960 pixels, or copy the original image if the thumbnail would be bigger than the origina - -## Validation rules - -By default, no validation rules are attached to the model. One must explicitly attach each rule if needed. Rules not referring to PHP upload errors are configurable but fallback to the behavior configuration. - -#### isUnderPhpSizeLimit - -Check that the file does not exceed the max file size specified by PHP - -```php - array( - 'rule' => 'isUnderPhpSizeLimit', - 'message' => 'File exceeds upload filesize limit' - ) -); -?> -``` - -#### isUnderFormSizeLimit - -Check that the file does not exceed the max file size specified in the HTML Form - -```php - array( - 'rule' => 'isUnderFormSizeLimit', - 'message' => 'File exceeds form upload filesize limit' - ) -); -?> -``` - -#### isCompletedUpload - -Check that the file was completely uploaded - -```php - array( - 'rule' => 'isCompletedUpload', - 'message' => 'File was not successfully uploaded' - ) -); -?> -``` - -#### isFileUpload - -Check that a file was uploaded - -```php - array( - 'rule' => 'isFileUpload', - 'message' => 'File was missing from submission' - ) -); -?> -``` - -#### isFileUploadOrHasExistingValue - -Check that either a file was uploaded, or the existing value in the database is not blank - -```php - array( - 'rule' => 'isFileUploadOrHasExistingValue', - 'message' => 'File was missing from submission' - ) -); -?> -``` - -#### tempDirExists - -Check that the PHP temporary directory is missing - -```php - array( - 'rule' => 'tempDirExists', - 'message' => 'The system temporary directory is missing' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('tempDirExists', false), - 'message' => 'The system temporary directory is missing' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isSuccessfulWrite - -Check that the file was successfully written to the server - -```php - array( - 'rule' => 'isSuccessfulWrite', - 'message' => 'File was unsuccessfully written to the server' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isSuccessfulWrite', false), - 'message' => 'File was unsuccessfully written to the server' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### noPhpExtensionErrors - -Check that a PHP extension did not cause an error - -```php - array( - 'rule' => 'noPhpExtensionErrors', - 'message' => 'File was not uploaded because of a faulty PHP extension' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('noPhpExtensionErrors', false), - 'message' => 'File was not uploaded because of a faulty PHP extension' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isValidMimeType - -Check that the file is of a valid mimetype - -```php - array( - 'rule' => array('isValidMimeType', array('application/pdf', 'image/png')), - 'message' => 'File is not a pdf or png' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isValidMimeType', array('application/pdf', 'image/png'), false), - 'message' => 'File is not a pdf or png' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isWritable - -Check that the upload directory is writable - -```php - array( - 'rule' => array('isWritable'), - 'message' => 'File upload directory was not writable' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isWritable', false), - 'message' => 'File upload directory was not writable' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isValidDir - -Check that the upload directory exists - -```php - array( - 'rule' => array('isValidDir'), - 'message' => 'File upload directory does not exist' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isValidDir', false), - 'message' => 'File upload directory does not exist' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isBelowMaxSize - -Check that the file is below the maximum file upload size (checked in bytes) - -```php - array( - 'rule' => array('isBelowMaxSize', 1024), - 'message' => 'File is larger than the maximum filesize' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isBelowMaxSize', 1024, false), - 'message' => 'File is larger than the maximum filesize' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isAboveMinSize - -Check that the file is above the minimum file upload size (checked in bytes) - -```php - array( - 'rule' => array('isAboveMinSize', 1024), - 'message' => 'File is below the mimimum filesize' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isAboveMinSize', 1024, false), - 'message' => 'File is below the mimimum filesize' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isValidExtension - -Check that the file has a valid extension - -```php - array( - 'rule' => array('isValidExtension', array('pdf', 'png', 'txt')), - 'message' => 'File does not have a pdf, png, or txt extension' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isValidExtension', array('pdf', 'png', 'txt'), false), - 'message' => 'File does not have a pdf, png, or txt extension' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isAboveMinHeight - -Check that the file is above the minimum height requirement (checked in pixels) - -```php - array( - 'rule' => array('isAboveMinHeight', 150), - 'message' => 'File is below the minimum height' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isAboveMinHeight', 150, false), - 'message' => 'File is below the minimum height' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isBelowMaxHeight - -Check that the file is below the maximum height requirement (checked in pixels) - -```php - array( - 'rule' => array('isBelowMaxHeight', 150), - 'message' => 'File is above the maximum height' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isBelowMaxHeight', 150, false), - 'message' => 'File is above the maximum height' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isAboveMinWidth - -Check that the file is above the minimum width requirement (checked in pixels) - -```php - array( - 'rule' => array('isAboveMinWidth', 150), - 'message' => 'File is below the minimum width' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isAboveMinWidth', 150, false), - 'message' => 'File is below the minimum width' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -#### isBelowMaxWidth - -Check that the file is below the maximum width requirement (checked in pixels) - -```php - array( - 'rule' => array('isBelowMaxWidth', 150), - 'message' => 'File is above the maximum width' - ) -); -?> -``` - -If the argument `$requireUpload` is passed, we can skip this check when a file is not uploaded: - -```php - array( - 'rule' => array('isBelowMaxWidth', 150, false), - 'message' => 'File is above the maximum width' - ) -); -?> -``` - -In the above, the variable `$requireUpload` has a value of false. By default, `requireUpload` is set to true. - -## Remove a current file without deleting the entire record - -In some cases you might want to remove a photo or uploaded file without having to -remove the entire record from the Model. In this case you would use the following code: - -```php -Form->create('Model', array('type' => 'file')); -echo $this->Form->input('Model.file.remove', array('type' => 'checkbox', 'label' => 'Remove existing file')); -?> -``` - -## License - -The MIT License (MIT) - -Copyright (c) 2010 Jose Diaz-Gonzalez - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..a69bb44a --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +[![Build Status](https://travis-ci.org/josegonzalez/cakephp-upload.png?branch=master)](https://travis-ci.org/josegonzalez/cakephp-upload) [![Coverage Status](https://coveralls.io/repos/josegonzalez/cakephp-upload/badge.png?branch=master)](https://coveralls.io/r/josegonzalez/cakephp-upload?branch=master) [![Total Downloads](https://poser.pugx.org/josegonzalez/cakephp-upload/d/total.png)](https://packagist.org/packages/josegonzalez/cakephp-upload) [![Latest Stable Version](https://poser.pugx.org/josegonzalez/cakephp-upload/v/stable.png)](https://packagist.org/packages/josegonzalez/cakephp-upload) + +# Upload Plugin 2.0 + +The Upload Plugin is an attempt to sanely upload files using techniques garnered from packages such as [MeioUpload](http://github.com/jrbasso/MeioUpload) , [UploadPack](http://github.com/szajbus/cakephp-uploadpack) and [PHP documentation](http://php.net/manual/en/features.file-upload.php). + +## Background + +Media Plugin is too complicated, and it was a PITA to merge the latest updates into MeioUpload, so here I am, building yet another upload plugin. I'll build another in a month and call it "YAUP". + +## Requirements + +* CakePHP 2.x +* Imagick/GD PHP Extension (for thumbnail creation) +* PHP 5 +* Patience + +## Documentation +For documentation, please see the [/docs/index.md](docs folder). + +## License + +The MIT License (MIT) + +Copyright (c) 2010 Jose Diaz-Gonzalez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..e877a6e2 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/CakePHP-Upload.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/CakePHP-Upload.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/CakePHP-Upload" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/CakePHP-Upload" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..de713aef --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# +# CakePHP-Upload documentation build configuration file, created by +# sphinx-quickstart on Tue Aug 26 08:59:51 2014. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'CakePHP-Upload' +copyright = u'2014, Jose Diaz-Gonzalez' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '1.1.1' +# The full version, including alpha/beta/rc tags. +release = '1.1.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'CakePHP-Uploaddoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'CakePHP-Upload.tex', u'CakePHP-Upload Documentation', + u'Jose Diaz-Gonzalez', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'cakephp-upload', u'CakePHP-Upload Documentation', + [u'Jose Diaz-Gonzalez'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'CakePHP-Upload', u'CakePHP-Upload Documentation', + u'Jose Diaz-Gonzalez', 'CakePHP-Upload', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/configuration.rst b/docs/configuration.rst new file mode 100644 index 00000000..6949d1f8 --- /dev/null +++ b/docs/configuration.rst @@ -0,0 +1,244 @@ +Behavior configuration options +------------------------------ + +This is a list of all the available configuration options which can be +passed in under each field in your behavior configuration. + +- ``pathMethod``: The method to use for file paths. This is appended to + the ``path`` option below + + - Default: (string) ``primaryKey`` + - Options: + + - ``flat``: Does not create a path for each record. Files are + moved to the value of the 'path' option. + - ``primaryKey``: Path based upon the record's primaryKey is + generated. Persists across a record update. + - ``random``: Random path is generated for each file upload in + the form ``nn/nn/nn`` where ``nn`` are random numbers. Does not + persist across a record update. + - ``randomCombined``: Random path - with model id - is generated + for each file upload in the form ``ID/nn/nn/nn`` where ``ID`` + is the current model's ID and ``nn`` are random numbers. Does + not persist across a record update. + +- ``path``: A path relative to the ``rootDir``. Should end in ``{DS}`` + + - Default: (string) + ``'{ROOT}webroot{DS}files{DS}{model}{DS}{field}{DS}'`` + - Tokens: + + - {ROOT}: Replaced by a ``rootDir`` option + - {DS}: Replaced by a ``DIRECTORY_SEPARATOR`` + - {model}: Replaced by the Model Alias. + - {field}: Replaced by the field name. + - {primaryKey}: Replaced by the record primary key, when + available. If used on a new record being created, will have + undefined behavior. + - {size}: Replaced by a zero-length string (the empty string) + when used for the regular file upload path. Only available for + resized thumbnails. + - {geometry}: Replaced by a zero-length string (the empty string) + when used for the regular file upload path. Only available for + resized thumbnails. + +- ``fields``: An array of fields to use when uploading files + + - Default: (array) + ``array('dir' => 'dir', 'type' => 'type', 'size' => 'size')`` + - Options: + + - dir: Field to use for storing the directory + - type: Field to use for storing the filetype + - size: Field to use for storing the filesize + +- ``rootDir``: Root directory for moving images. Auto-prepended to + ``path`` and ``thumbnailPath`` where necessary + + - Default (string) ``ROOT . DS . APP_DIR . DS`` + +- ``mimetypes``: Array of mimetypes to use for validation + + - Default: (array) empty + +- ``extensions``: Array of extensions to use for validation + + - Default: (array) empty + +- ``maxSize``: Max filesize in bytes for validation + + - Default: (int) ``2097152`` + +- ``minSize``: Minimum filesize in bytes for validation + + - Default: (int) ``8`` + +- ``maxHeight``: Maximum image height for validation + + - Default: (int) ``0`` + +- ``minHeight``: Minimum image height for validation + + - Default: (int) ``0`` + +- ``maxWidth``: Maximum image width for validation + + - Default: (int) ``0`` + +- ``minWidth``: Minimum image width for validation + + - Default: (int) ``0`` + +- ``deleteOnUpdate``: Whether to delete files when uploading new + versions (potentially dangerous due to naming conflicts) + + - Default: (boolean) ``false`` + +- ``thumbnails``: Whether to create thumbnails or not + + - Default: (boolean) ``true`` + +- ``thumbnailMethod``: The method to use for resizing thumbnails + + - Default: (string) ``imagick`` + - Options: + + - imagick: Uses the PHP ``imagick`` extension to generate + thumbnails + - php: Uses the built-in PHP methods (``GD`` extension) to + generate thumbnails. Does not support BMP images. + +- ``thumbnailName``: Naming style for a thumbnail + + - Default: ``NULL`` + - Note: The tokens ``{size}``, ``{geometry}`` and ``{filename}`` are + valid for naming and will be auto-replaced with the actual terms. + - Note: As well, the extension of the file will be automatically + added. + - Note: When left unspecified, will be set to ``{size}_{filename}`` + or ``{filename}_{size}`` depending upon the value of + ``thumbnailPrefixStyle`` + +- ``thumbnailPath``: A path relative to the ``rootDir`` where + thumbnails will be saved. Should end in ``{DS}``. If not set, + thumbnails will be saved at ``path``. + + - Default: ``NULL`` + - Tokens: + + - {ROOT}: Replaced by a ``rootDir`` option + - {DS}: Replaced by a ``DIRECTORY_SEPARATOR`` + - {model}: Replaced by the Model Alias + - {field}: Replaced by the field name + - {size}: Replaced by the size key specified by a given + ``thumbnailSize`` + - {geometry}: Replaced by the geometry value specified by a given + ``thumbnailSize`` + +- ``thumbnailPrefixStyle``: Whether to prefix or suffix the style onto + thumbnails + + - Default: (boolean) ``true`` prefix the thumbnail + - Note that this overrides ``thumbnailName`` when ``thumbnailName`` + is not specified in your config + +- ``thumbnailQuality``: Quality of thumbnails that will be generated, + on a scale of 0-100. Not supported gif images when using GD for image + manipulation. + + - Default: (int) ``75`` + +- ``thumbnailSizes``: Array of thumbnail sizes, with the size-name + mapping to a geometry + + - Default: (array) empty + +- ``thumbnailType``: Override the type of the generated thumbnail + + - Default: (mixed) ``false`` or ``png`` when the upload is a Media + file + - Options: + + - Any valid image type + +- ``mediaThumbnailType``: Override the type of the generated thumbnail + for a non-image media (``pdfs``). Overrides ``thumbnailType`` + + - Default: (mixed) ``png`` + - Options: + + - Any valid image type + +- ``saveDir``: Can be used to turn off saving the directory + + - Default: (boolean) ``true`` + - Note: Because of the way in which the directory is saved, if you + are using a ``pathMethod`` other than flat and you set ``saveDir`` + to false, you may end up in situations where the file is in a + location that you cannot predict. This is more of an issue for a + ``pathMethod`` of ``random`` and ``randomCombined`` than + ``primaryKey``, but keep this in mind when fiddling with this + option + +- ``deleteFolderOnDelete``: Delete folder related to current record on + record delete + + - Default: (boolean) ``false`` + - Note: Because of the way in which the directory is saved, if you + are using a ``pathMethod`` of flat, turning this setting on will + delete all your images. As such, setting this to true can be + potentially dangerous. + +- ``keepFilesOnDelete``: Keep *all* files when uploading/deleting a + record. + + - Default: (boolean) ``false`` + - Note: This does not override ``deleteFolderOnDelete``. If you set + that setting to true, your images may still be deleted. This is so + that existing uploads are not deleted - unless overwritten. + +- ``mode``: The UNIX permissions to set on the created upload + directories. + + - Default: (integer) ``0777`` + +- ``handleUploadedFileCallback``: If set to a method name available on + your model, this model method will handle the movement of the + original file on disk. Can be used in conjunction with + ``thumbnailMethod`` to store your files in alternative locations, + such as S3. + + - Default: ``NULL`` + - Available arguments: + + - ``string $field``: Field being manipulated + - ``string $filename``: The filename of the uploaded file + - ``string $destination``: The configured destination of the + moved file + +- ``nameCallback``: A callback that can be used to rename a file. + Currently only handles original file naming. + + - Default: ``NULL`` + - Available arguments: + + - ``string $field``: Field being manipulated + - ``string $currentName`` + - ``array $data`` + - ``array options``: + + - ``isThumbnail`` - a boolean field that is on when we are + trying to infer a thumbnail path + - ``rootDir`` - root directory to replace ``{ROOT}`` + - ``geometry`` + - ``size`` + - ``thumbnailType`` + - ``thumbnailName`` + - ``thumbnailMethod`` + - ``mediaThumbnailType`` + - ``dir`` field name + - ``saveType`` - create, update, delete + + - Return: String - returns the new name for the file + + diff --git a/docs/examples.rst b/docs/examples.rst new file mode 100644 index 00000000..33932fcf --- /dev/null +++ b/docs/examples.rst @@ -0,0 +1,236 @@ +Examples +-------- + +Basic example +~~~~~~~~~~~~~ + + Note: You may want to define the Upload behavior *before* the core + Translate Behavior as they have been known to conflict with each + other. + +.. code:: sql + + CREATE table users ( + id int(10) unsigned NOT NULL auto_increment, + username varchar(20) NOT NULL, + photo varchar(255) + ); + +.. code:: php + + array( + 'photo' + ) + ); + } + ?> + +.. code:: php + + Form->create('User', array('type' => 'file')); ?> + Form->input('User.username'); ?> + Form->input('User.photo', array('type' => 'file')); ?> + Form->end(); ?> + +Using the above setup, uploaded files cannot be deleted. To do so, a +field must be added to store the directory of the file as follows: + +.. code:: sql + + CREATE table users ( + `id` int(10) unsigned NOT NULL auto_increment, + `username` varchar(20) NOT NULL, + `photo` varchar(255) DEFAULT NULL, + `photo_dir` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`) + ); + +.. code:: php + + array( + 'photo' => array( + 'fields' => array( + 'dir' => 'photo_dir' + ) + ) + ) + ); + } + ?> + +In the above example, photo can be a file upload via a file input within +a form, a file grabber (from a url) via a text input, OR programatically +used on the controller to file grab via a url. + +File Upload Example +^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + Form->create('User', array('type' => 'file')); ?> + Form->input('User.username'); ?> + Form->input('User.photo', array('type' => 'file')); ?> + Form->input('User.photo_dir', array('type' => 'hidden')); ?> + Form->end(); ?> + +File Grabbing via Form Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + Form->create('User', array('type' => 'file')); ?> + Form->input('User.username'); ?> + Form->input('User.photo', array('type' => 'file')); ?> + Form->input('User.photo_dir', array('type' => 'hidden')); ?> + Form->end(); ?> + +Programmatic File Retrieval without a Form +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + User->set(array('photo' => $image_url)); + $this->User->save(); + ?> + +Thumbnail Creation +^^^^^^^^^^^^^^^^^^ + +Thumbnails are not automatically created. To do so, thumbnail sizes must +be defined: Note: by default thumbnails will be generated by imagick, if +you want to use GD you need to set the thumbnailMethod attribute. +Example: ``'thumbnailMethod' => 'php'``. + +.. code:: php + + array( + 'photo' => array( + 'thumbnailSizes' => array( + 'xvga' => '1024x768', + 'vga' => '640x480', + 'thumb' => '80x80' + ) + ) + ) + ); + } + ?> + +Uploading Multiple files +~~~~~~~~~~~~~~~~~~~~~~~~ + +Multiple files can also be attached to a single record: + +.. code:: php + + array( + 'resume', + 'photo' => array( + 'fields' => array( + 'dir' => 'profile_dir' + ) + ) + ) + ); + } + ?> + +Each key in the ``Upload.Upload`` array is a field name, and can +**contain it's own configuration**. For example, you might want to set +different fields for storing file paths: + +.. code:: php + + array( + 'resume' => array( + 'fields' => array( + 'dir' => 'resume_dir', + 'type' => 'resume_type', + 'size' => 'resume_size', + ) + ), + 'photo' => array( + 'fields' => array( + 'dir' => 'photo_dir', + 'type' => 'photo_type', + 'size' => 'photo_size', + ) + ) + ) + ); + } + ?> + +Keep in mind that while this plugin does not have any limits in terms of +number of files uploaded per request, you should keep this down in order +to decrease the ability of your users to block other requests. + +If you are looking to add an unknown or high number of uploads to a +model it's worth considering using a `polymorphic +attachment `__. + +Remove a current file without deleting the entire record +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In some cases you might want to remove a photo or uploaded file without +having to remove the entire record from the Model. In this case you +would use the following code: + +.. code:: php + + Form->create('Model', array('type' => 'file')); + echo $this->Form->input('Model.file.remove', array('type' => 'checkbox', 'label' => 'Remove existing file')); + ?> + +Saving two uploads into different folders +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Sometimes you might want to upload more than one file, but upload each +file into a different folder. This is actually very simple. By simply +using the behavior configuration for *each file* you can change the +path. Don't forget to make sure `the plugin is installed +first `__. + +Let's assume for this example that we want to upload a picture of a +user, and say, a picture of their car. For the sake of simplicity we'll +also assume that these files are just stored in the ``User`` model. + + Note: It's important to notice that each field can have it's own + configuration. + +.. code:: php + + array( + 'avatar' => array( // The name of the field in our database, so this is `users.avatar` + 'rootDir' => ROOT, // Here we can define the rootDir, which is the root of the application, usually an absolute path to your project + 'path' => '{ROOT}{DS}webroot{DS}files{DS}{model}{DS}{field}{DS}', // The path pattern that we want to use to save our file where {DS} is the directory separator and the {ROOT}, {model} and {field} tokens are replaced with their matching values + 'fields' => array( + 'dir' => 'image_dir' // It's always helpful to save the directory our files are in, just in case + ) + ), + 'car' => array( + 'path' => '{ROOT}{DS}webroot{DS}files{DS}cars{DS}' // Here we have changed the path, so our images will now be in a different folder + ) + ) + ) + diff --git a/docs/file-import-behavior.rst b/docs/file-import-behavior.rst new file mode 100644 index 00000000..bc588ae8 --- /dev/null +++ b/docs/file-import-behavior.rst @@ -0,0 +1,6 @@ +FileImportBehavior +------------------ + +``FileImportBehavior`` may be used to import files directly from the +disk. This is useful in importing from a directory already on the +filesystem. diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..bbf4a0d6 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,29 @@ +.. CakePHP-Upload documentation master file, created by + sphinx-quickstart on Tue Aug 26 08:59:51 2014. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to CakePHP-Upload's documentation! +========================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + Installation + Examples + Configuration options + Associating many images to one item + Generating thumbnails + Validating uploads + File import behavior + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 00000000..330ad586 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,88 @@ +Installation +------------ + +Using `Composer `__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`View on +Packagist `__, +and copy the json snippet for the latest version into your project's +``composer.json``. Eg, v. 1.1.1 would look like this: + +.. code:: json + + { + "require": { + "josegonzalez/cakephp-upload": "1.1.1" + } + } + +This plugin has the type ``cakephp-plugin`` set in it's own +``composer.json``, composer knows to install it inside your ``/Plugins`` +directory, rather than in the usual vendors file. It is recommended that +you add ``/Plugins/Upload`` to your .gitignore file. (Why? `read +this `__.) + +Manual +~~~~~~ + +- Download this: + http://github.com/josegonzalez/cakephp-upload/zipball/master +- Unzip that download. +- Copy the resulting folder to ``app/Plugin`` +- Rename the folder you just copied to ``Upload`` + +GIT Submodule +~~~~~~~~~~~~~ + +In your *app directory* type: + +.. code:: bash + + git submodule add -b master git://github.com/josegonzalez/cakephp-upload.git Plugin/Upload + git submodule init + git submodule update + +GIT Clone +~~~~~~~~~ + +In your ``Plugin`` directory type: + +.. code:: bash + + git clone -b master git://github.com/josegonzalez/cakephp-upload.git Upload + +Imagick Support +--------------- + +To enable `Imagick `__ support, you need to +have Imagick installed: + +.. code:: bash + + # Debian systems + sudo apt-get install php-imagick + + # OS X Homebrew + brew tap homebrew/dupes + brew tap josegonzalez/homebrew-php + brew install php54-imagick + + # From pecl + pecl install imagick + +If you cannot install Imagick, instead configure the plugin with +``'thumbnailMethod' => 'php'`` in the files options. + +Enable plugin +------------- + +You need to enable the plugin your ``app/Config/bootstrap.php`` file: + +.. code:: php + + ` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\CakePHP-Upload.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\CakePHP-Upload.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/docs/polymorphic.rst b/docs/polymorphic.rst new file mode 100644 index 00000000..b8243ed7 --- /dev/null +++ b/docs/polymorphic.rst @@ -0,0 +1,210 @@ +Using a polymorphic attachment model for file storage +----------------------------------------------------- + +In some cases you will want to store multiple file uploads for multiple +models, but will not want to use multiple tables because your database +is normalized. For example, we might have a ``Post`` model that can have +many images for a gallery, and a ``Message`` model that has many videos. +In this case, we would use an ``Attachment`` model: + +Post hasMany Attachment + +We could use the following database schema for the ``Attachment`` model: + +.. code:: sql + + CREATE table attachments ( + `id` int(10) unsigned NOT NULL auto_increment, + `model` varchar(20) NOT NULL, + `foreign_key` int(11) NOT NULL, + `name` varchar(32) NOT NULL, + `attachment` varchar(255) NOT NULL, + `dir` varchar(255) DEFAULT NULL, + `type` varchar(255) DEFAULT NULL, + `size` int(11) DEFAULT 0, + `active` tinyint(1) DEFAULT 1, + PRIMARY KEY (`id`) + ); + +Our attachment records would thus be able to have a name and be +activated or deactivated on the fly. The schema is simply an example, +and such functionality would need to be implemented within your +application. + +Once the ``attachments`` table has been created, we would create the +following model: + +.. code:: php + + array( + 'attachment' => array( + 'thumbnailSizes' => array( + 'xvga' => '1024x768', + 'vga' => '640x480', + 'thumb' => '80x80', + ), + ), + ), + ); + + public $belongsTo = array( + 'Post' => array( + 'className' => 'Post', + 'foreignKey' => 'foreign_key', + ), + 'Message' => array( + 'className' => 'Message', + 'foreignKey' => 'foreign_key', + ), + ); + } + ?> + +We would also need to create a valid inverse relationship in the +``Post`` model: + +.. code:: php + + array( + 'className' => 'Attachment', + 'foreignKey' => 'foreign_key', + 'conditions' => array( + 'Image.model' => 'Post', + ), + ), + ); + } + ?> + +The key thing to note here is the ``Post`` model has some conditions on +the relationship to the ``Attachment`` model, where the ``Image.model`` +has to be ``Post``. Remember to set the ``model`` field to ``Post``, or +whatever model it is you'd like to attach it to, otherwise you may get +incorrect relationship results when performing find queries. + +We would also need a similar relationship in our ``Message`` model: + +.. code:: php + + array( + 'className' => 'Attachment', + 'foreignKey' => 'foreign_key', + 'conditions' => array( + 'Video.model' => 'Message', + ), + ), + ); + } + ?> + +Now that we have our models setup, we should create the proper actions +in our controllers. To keep this short, we shall only document the Post +model: + +.. code:: php + + request->is('post')) { + try { + $this->Post->createWithAttachments($this->request->data); + $this->Session->setFlash(__('The message has been saved')); + } catch (Exception $e) { + $this->Session->setFlash($e->getMessage()); + } + } + } + } + ?> + +In the above example, we are calling our custom +``createWithAttachments`` method on the ``Post`` model. This will allow +us to unify the Post creation logic together in one place. That method +is outlined below: + +.. code:: php + + $image) { + if (is_array($data['Image'][$i])) { + // Force setting the `model` field to this model + $image['model'] = 'Post'; + + // Unset the foreign_key if the user tries to specify it + if (isset($image['foreign_key'])) { + unset($image['foreign_key']); + } + + $images[] = $image; + } + } + } + $data['Image'] = $images; + + // Try to save the data using Model::saveAll() + $this->create(); + if ($this->saveAll($data)) { + return true; + } + + // Throw an exception for the controller + throw new Exception(__("This post could not be saved. Please try again")); + } + } + ?> + +The above model method will: + +- Ensure we only try to save valid images +- Force the foreign\_key to be unspecified. This will allow saveAll to + properly associate it +- Force the model field to ``Post`` + +Now that this is set, we just need a view for our controller. A sample +view for ``View/Posts/add.ctp`` is as follows (fields not necessary for +the example are omitted): + +.. code:: php + + Form->create('Post', array('type' => 'file')); + echo $this->Form->input('Image.0.attachment', array('type' => 'file', 'label' => 'Image')); + echo $this->Form->input('Image.0.model', array('type' => 'hidden', 'value' => 'Post')); + echo $this->Form->end(__('Add')); + ?> + +The one important thing you'll notice is that I am not referring to the +``Attachment`` model as ``Attachment``, but rather as ``Image``; when I +initially specified the ``$hasMany`` relationship between an +``Attachment`` and a ``Post``, I aliased ``Attachment`` to ``Image``. +This is necessary for cases where many of your Polymorphic models may be +related to each other, as a type of *hint* to the CakePHP ORM to +properly reference model data. + +I'm also using ``Model.{n}.field`` notation, which would allow you to +add multiple attachment records to the Post. This is necessary for +``$hasMany`` relationships, which we are using for this example. + +Once you have all the above in place, you'll have a working Polymorphic +upload! + +Please note that this is not the only way to represent file uploads, but +it is documented here for reference. diff --git a/docs/thumbnails.rst b/docs/thumbnails.rst new file mode 100644 index 00000000..48cd8f59 --- /dev/null +++ b/docs/thumbnails.rst @@ -0,0 +1,71 @@ +Thumbnail Sizes and Styles +-------------------------- + +The Upload plugin can automatically generate various thumbnails at +different sizes for you when uploading files. The thumbnails must be +configured in order for thumbnails to be generated. + +To generate thumbnails you will need to configure the ``thumbnailSizes`` +option under the field you are configuring. + +.. code:: php + + array( + 'photo' => array( // The field we are configuring for + 'thumbnailSizes' => array( // Various sizes of thumbnail to generate + 'big' => '200x200', // Resize for best fit to 200px by 200px, cropped from the center of the image. Prefix with big_ + 'small' => '120x120' + 'thumb' => '80x80' + ) + ) + ) + ); + } + ?> + +Once this configuration is set when uploading a file a thumbnail will +automatically be generated with the prefix defined in the options. For +example (using default configuration) +``app/webroot/files/Example/photo/1/big_example.jpg``. Where ``Example`` +is the model, ``photo`` is the field, ``1`` is the model primaryKey +value and finally ``big_`` is the thumbnail size prefix to the filename. + +Thumbnail sizes only apply to images of the following types: + +- image/bmp +- image/gif +- image/jpeg +- image/pjpeg +- image/png +- image/vnd.microsoft.icon +- image/x-icon + +You can specify any of the following resize modes for your sizes: + +- ``100x80`` - resize for best fit into these dimensions, with + overlapping edges trimmed if original aspect ratio differs +- ``[100x80]`` - resize to fit these dimensions, with white banding if + original aspect ratio differs +- ``100w`` - maintain original aspect ratio, resize to 100 pixels wide +- ``80h`` - maintain original aspect ratio, resize to 80 pixels high +- ``80l`` - maintain original aspect ratio, resize so that longest side + is 80 pixels +- ``600mw`` - maintain original aspect ratio, resize to max 600 pixels + wide, or copy the original image if it is less than 600 pixels wide +- ``800mh`` - maintain original aspect ratio, resize to max 800 pixels + high, or copy the original image if it is less than 800 pixels high +- ``960ml`` - maintain original aspect ratio, resize so that longest + side is max 960 pixels, or copy the original image if the thumbnail + would be bigger than the original. + +PDF Support +~~~~~~~~~~~ + +It is now possible to generate a thumbnail for the first page of a PDF +file. (Only works with the ``imagick`` ``thumbnailMethod``.) Please read +about the `Behavior options `__ for more details as to +how to `configure this plugin `__. diff --git a/docs/validation.rst b/docs/validation.rst new file mode 100644 index 00000000..3024d602 --- /dev/null +++ b/docs/validation.rst @@ -0,0 +1,523 @@ +Validation rules +---------------- + +By default, no validation rules are attached to the model. You must +explicitly attach each rule if needed. Rules not referring to PHP upload +errors are configurable but fallback to the behavior configuration. + +isUnderPhpSizeLimit +^^^^^^^^^^^^^^^^^^^ + +Check that the file does not exceed the max file size specified by PHP + +.. code:: php + + array( + 'rule' => 'isUnderPhpSizeLimit', + 'message' => 'File exceeds upload filesize limit' + ) + ); + ?> + +isUnderFormSizeLimit +^^^^^^^^^^^^^^^^^^^^ + +Check that the file does not exceed the max file size specified in the +HTML Form + +.. code:: php + + array( + 'rule' => 'isUnderFormSizeLimit', + 'message' => 'File exceeds form upload filesize limit' + ) + ); + ?> + +isCompletedUpload +^^^^^^^^^^^^^^^^^ + +Check that the file was completely uploaded + +.. code:: php + + array( + 'rule' => 'isCompletedUpload', + 'message' => 'File was not successfully uploaded' + ) + ); + ?> + +isFileUpload +^^^^^^^^^^^^ + +Check that a file was uploaded + +.. code:: php + + array( + 'rule' => 'isFileUpload', + 'message' => 'File was missing from submission' + ) + ); + ?> + +isFileUploadOrHasExistingValue +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Check that either a file was uploaded, or the existing value in the +database is not blank + +.. code:: php + + array( + 'rule' => 'isFileUploadOrHasExistingValue', + 'message' => 'File was missing from submission' + ) + ); + ?> + +tempDirExists +^^^^^^^^^^^^^ + +Check that the PHP temporary directory is missing + +.. code:: php + + array( + 'rule' => 'tempDirExists', + 'message' => 'The system temporary directory is missing' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('tempDirExists', false), + 'message' => 'The system temporary directory is missing' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isSuccessfulWrite +^^^^^^^^^^^^^^^^^ + +Check that the file was successfully written to the server + +.. code:: php + + array( + 'rule' => 'isSuccessfulWrite', + 'message' => 'File was unsuccessfully written to the server' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isSuccessfulWrite', false), + 'message' => 'File was unsuccessfully written to the server' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +noPhpExtensionErrors +^^^^^^^^^^^^^^^^^^^^ + +Check that a PHP extension did not cause an error + +.. code:: php + + array( + 'rule' => 'noPhpExtensionErrors', + 'message' => 'File was not uploaded because of a faulty PHP extension' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('noPhpExtensionErrors', false), + 'message' => 'File was not uploaded because of a faulty PHP extension' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isValidMimeType +^^^^^^^^^^^^^^^ + +Check that the file is of a valid mimetype + +.. code:: php + + array( + 'rule' => array('isValidMimeType', array('application/pdf', 'image/png')), + 'message' => 'File is not a pdf or png' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isValidMimeType', array('application/pdf', 'image/png'), false), + 'message' => 'File is not a pdf or png' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isWritable +^^^^^^^^^^ + +Check that the upload directory is writable + +.. code:: php + + array( + 'rule' => array('isWritable'), + 'message' => 'File upload directory was not writable' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isWritable', false), + 'message' => 'File upload directory was not writable' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isValidDir +^^^^^^^^^^ + +Check that the upload directory exists + +.. code:: php + + array( + 'rule' => array('isValidDir'), + 'message' => 'File upload directory does not exist' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isValidDir', false), + 'message' => 'File upload directory does not exist' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isBelowMaxSize +^^^^^^^^^^^^^^ + +Check that the file is below the maximum file upload size (checked in +bytes) + +.. code:: php + + array( + 'rule' => array('isBelowMaxSize', 1024), + 'message' => 'File is larger than the maximum filesize' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isBelowMaxSize', 1024, false), + 'message' => 'File is larger than the maximum filesize' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isAboveMinSize +^^^^^^^^^^^^^^ + +Check that the file is above the minimum file upload size (checked in +bytes) + +.. code:: php + + array( + 'rule' => array('isAboveMinSize', 1024), + 'message' => 'File is below the mimimum filesize' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isAboveMinSize', 1024, false), + 'message' => 'File is below the mimimum filesize' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isValidExtension +^^^^^^^^^^^^^^^^ + +Check that the file has a valid extension + +.. code:: php + + array( + 'rule' => array('isValidExtension', array('pdf', 'png', 'txt')), + 'message' => 'File does not have a pdf, png, or txt extension' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isValidExtension', array('pdf', 'png', 'txt'), false), + 'message' => 'File does not have a pdf, png, or txt extension' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isAboveMinHeight +^^^^^^^^^^^^^^^^ + +Check that the file is above the minimum height requirement (checked in +pixels) + +.. code:: php + + array( + 'rule' => array('isAboveMinHeight', 150), + 'message' => 'File is below the minimum height' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isAboveMinHeight', 150, false), + 'message' => 'File is below the minimum height' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isBelowMaxHeight +^^^^^^^^^^^^^^^^ + +Check that the file is below the maximum height requirement (checked in +pixels) + +.. code:: php + + array( + 'rule' => array('isBelowMaxHeight', 150), + 'message' => 'File is above the maximum height' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isBelowMaxHeight', 150, false), + 'message' => 'File is above the maximum height' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isAboveMinWidth +^^^^^^^^^^^^^^^ + +Check that the file is above the minimum width requirement (checked in +pixels) + +.. code:: php + + array( + 'rule' => array('isAboveMinWidth', 150), + 'message' => 'File is below the minimum width' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isAboveMinWidth', 150, false), + 'message' => 'File is below the minimum width' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true. + +isBelowMaxWidth +^^^^^^^^^^^^^^^ + +Check that the file is below the maximum width requirement (checked in +pixels) + +.. code:: php + + array( + 'rule' => array('isBelowMaxWidth', 150), + 'message' => 'File is above the maximum width' + ) + ); + ?> + +If the argument ``$requireUpload`` is passed, we can skip this check +when a file is not uploaded: + +.. code:: php + + array( + 'rule' => array('isBelowMaxWidth', 150, false), + 'message' => 'File is above the maximum width' + ) + ); + ?> + +In the above, the variable ``$requireUpload`` has a value of false. By +default, ``requireUpload`` is set to true.