Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
73
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 14 WORKING WITH FILES

This generic solution probably isn’t robust enough for most people, so let’s see some specific examples in the following section.

Video and Audio

Numerous modules that help to manage media such as video files, Flash content, slideshows, and so on can be found at www.drupal.org/project/modules.

File API

The file API lives in includes/file.inc. We’ll cover some of the commonly used functions in this section. For more, the interested reader is directed to the API documentation to study the API in its current format: http://api.drupal.org/api/group/file/7.

Database Schema

Although Drupal stores files on disk, it still uses the database to store a fair amount of metadata about the files. In addition to authorship, MIME type, and location, it maintains revision information for uploaded files. The schema for the file_managed table is shown in Table 14-1.

Table 14-1. The file_managed Table

Field*

Type

Default

Description

 

 

 

 

fid

serial

 

Primary key

uid

int

0

User ID of the user associated with the file

filename

varchar(255)

''

Name of the file

uri

varchar(255)

''

The URI to access the file (either local or remote)

filemime

varchar(255)

''

The MIME type of the file

filesize

int

0

Size of the file in bytes

status

int

0

Flag indicating whether file is temporary (1) or

 

 

 

permanent (0)

timestamp

int

0

Unix timestamp indicating when file was added

* Bold indicates a primary key; italics indicate an indexed field.

328

CHAPTER 14 WORKING WITH FILES

The mechanism for associating uploaded files with the content that they are associated with is handled through a field_data_field_file_xxxxxx table, where xxxxx represents the unique name assigned to that form field when it was added to the content type. The schema for all of those tables is identical, as shown in Table 14-2.

Table 14-2. The Upload Table Used by the Upload Module

Field*

Type

Default

Description

 

 

 

 

etid

int

0

The entity type id this data is attached to

bundle

varchar

 

The field instance bundle to which this row belongs

deleted

tinyint

0

A Boolean indicating whether this data item has been

 

 

 

deleted

entity_id

int

 

The entity id this data is attached to (e.g., the node

 

 

 

id)

revision_id

int

NULL

The entity revision id this data is attached to

language

varchar

 

The language for this data item

delta

int

 

The sequence number for this data item

field_xxxxxx

int

NULL

The file_managed.id being referenced in this field,

_fid

 

 

where xxxxx is replaced with the name of the field from

 

 

 

the content type

field_xxxxxx

tinyint

1

Flag to control whether this file should be displayed

_display

 

 

when viewing content

Field_xxxxxx

Text

NULL

A description of the file

_description

 

 

 

* Bold indicates a primary key; italics indicate an indexed field.

Common Tasks and Functions

If you want to do something with a file, chances are that the File API already has a convenient function for you to use. Let’s look at some of these.

Finding the Default Files URI

The file_default_scheme() function returns the default scheme (e.g., public or private) and can be used to define the URI where those files exist. For example, file_default_scheme().”:/” represents the default location where files are written to on file upload.

329

Download from Wow! eBook <www.wowebook.com>

CHAPTER 14 WORKING WITH FILES

Saving Data to a File

Sometimes you just want to save data in a file. That’s what the following function does.

file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)

The $data parameter will become the contents of the file. The $dest parameter is the URI of the destination. The $replace parameter determines Drupal’s behavior if a file of the same name already exists at the destination. Possible values are shown in Table 14-3.

Table 14-3. Constants That Determine Drupal’s Behavior When a File of the Same Name Exists at the Destination

Name

Meaning

FILE_EXISTS_REPLACE Replace the existing file with the current file.

FILE_EXISTS_RENAME Append an underscore and integer to make the new file name unique.

FILE_EXISTS_ERROR

Abort and return FALSE.

Here’s a quick example that puts a short string into a file in Drupal’s file system directory:

<?php

$filename = 'testfile.txt';

$dest = file_build_uri($filename);

file_save_data('My data', $dest, FILE_EXISTS_REPLACE);

The $dest variable must contain a valid stream wrapper URI. The foregoing example utilizes the file_build_uri function to create a valid stream wrapper URI that points to the destination directory, which in this case is the default public files directory.

Copying and Moving Files

The following functions help you work with files that are already on the file system. See also file_unmanaged_copy() and file_unmanaged_move().

file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME)

The file_copy() function copies files into Drupal’s file system path (typically sites/default/ files). The $source parameter is a file object, $destination is a string containing the destination of where the file should be copied to—as a valid stream wrapper URI—and $replace is the action that Drupal should take if the file already exists in the destination directory.

330

CHAPTER 14 WORKING WITH FILES

file_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME)

The file_move() function works just like the file_copy() function (in fact, it calls file_unmanaged_copy()), but also removes the original file by calling file_delete().

Checking Directories

The file_prepare_directory(&$directory, $options=FILE_MODIFY_PERMISSIONS) function checks to see whether a directory exists and is writeable, which is a good thing to do before you attempt to write to that directory. The following example checks to see if the sites/default/files directory exists and is writeable.

<?php

$directory = 'sites/default/files';

if (file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS)) { echo "The directory exists and is writeable";

} else {

echo "The file does not exist or it is not writeable";

}

Uploading Files

Although field API and its file field offer a full-fledged implementation of file uploading for nodes, sometimes you just want to be able to upload a file that is not associated with a node. The following functions can help in that situation.

file_save_upload($source, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME)

The $source parameter is a string that specifies the filepath or URI of the uploaded file to save. The $validators parameter is an optional associative array of callback functions used to validate the file. If you don’t specify a validator, then Drupal performs basic validation that the file extension is one of “jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp”. The $destination parameter is a string that contains the URI of where the source should be copied to, and the $replace parameter allows you to specify whether the uploaded file should replace an existing file, rename the file by appending an incrementing number to the end of the file name, or error out. Here is the validation function from the user module that uploads the user’s picture using the file_save_upload function. The function sets three validators: test whether the file is an image, test whether the image resolution is 85 X 85, and validate the size of the file. The image itself comes from the file upload field on the user form named “picture_upload” (see figure 14-4) with the resulting object showing in figure 14-5.

function user_validate_picture(&$form, &$form_state) { // If required, validate the uploaded picture. $validators = array(

'file_validate_is_image' => array(),

'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),

331

CHAPTER 14 WORKING WITH FILES

'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),

);

// Save the file as a temporary file.

$file = file_save_upload('picture_upload', $validators); if ($file === FALSE) {

form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));

}

elseif ($file !== NULL) { $form_state['values']['picture_upload'] = $file;

}

}

Figure 14-4. File field for user_picture form element as it appears on the “My account” page

Figure 14-5. Resulting file object after HTTP POST

332

CHAPTER 14 WORKING WITH FILES

The $dest parameter in the file_save_upload() function is optional and may contain the directory to which the file will be copied. For example, when processing files attached to a node, the upload module uses file_directory_path() (which defaults to sites/default/files) as the value for $dest (see Figure 14-6). If $dest is not provided, the temporary directory will be used.

The $replace parameter defines what Drupal should do if a file with the same name already exists. Possible values are listed in Table 14-3.

Figure 14-6. The file object as it exists when passed to file_save_upload() validators

The return value for file_save_upload() is a fully populated file object (as shown in Figure 14-6), or 0 if something went wrong.

After calling file_save_upload(), a new file exists in Drupal’s temporary directory and a new record is written to the files table. The record contains the same values as the file object shown in Figure 14-6.

Notice that the status field is set to 0. That means that as far as Drupal is concerned, this is still a temporary file. It is the caller’s responsibility to make the file permanent. Continuing with our example of uploading a user picture, we see that the user module takes the approach of copying this file to the directory defined in Drupal’s user_picture_path variable and renaming it using the user’s ID:

// Process picture uploads.

if (!empty($edit['picture']->fid)) { $picture = $edit['picture'];

//If the picture is a temporary file move it to its final location and

//make it permanent.

if (($picture->status & FILE_STATUS_PERMANENT) == 0) { $info = image_get_info($picture->uri);

$picture_directory = variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');

// Prepare the pictures directory. file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);

$destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-'

. $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);

333

CHAPTER 14 WORKING WITH FILES

if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) { $picture->status |= FILE_STATUS_PERMANENT;

$edit['picture'] = file_save($picture);

}

}

}.

This moves the uploaded image to sites/default/files/pictures/directory and makes the file permanent.

If the $dest parameter was provided and the file was moved to its final destination instead of the temporary directory, the caller can change the status of the record in the files table to permanent by calling file_save($file), with $file set to the full file object (as shown in Figure 14-7) and the status set to FILE_STATUS_PERMANENT. According to includes/file.inc, if you plan to use additional status constants in your own modules, you must start with 256, as 0, 1, 2, 4, 8, 16, 32, 64, and 128 are reserved for core.

Validation functions that may be used with file_save_upload() follow.

file_validate_extensions($file, $extensions)

The $file parameter is a file object. The $extensions parameter is a string of space-delimited file extensions. The function will return an empty array if the file extension is allowed, and an array of error messages like Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp if the file extension is disallowed. This function is a possible validator for file_save_upload().

file_validate_is_image($file)

This function takes a file object and attempts to pass $file->filepath to image_get_info(). The function will return an empty array if image_get_info() was able to extract information from the file, or an array containing the error message Only JPEG, PNG and GIF images are allowed if the process failed. This function is a possible validator for file_save_upload().

file_validate_image_resolution($file, $maximum_dimensions = 0, $minimum_ dimensions = 0)

This function takes a file object and uses $file->file path in several operations. If the file is an image, the function will check if the image exceeds $maximum_dimensions and attempt to resize it if possible. If everything goes well, an empty array will be returned and the $file object, which was passed by reference, will have $file->filesize set to the new size if the image was resized. Otherwise, the array will contain an error message, such as The image is too small; the minimum dimensions are 320x240 pixels. The $maximum_dimensions and $minimum_dimensions parameters are strings made up of width and height in pixels with a lowercase x separating them (e.g., 640x480 or 85x85). The default value of 0 indicates no restriction on size. This function is a possible validator for file_save_upload().

334

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]