New module 'ImageCache'

This commit is contained in:
Manuel Cillero 2017-07-26 13:29:42 +02:00
parent 6be6a844b3
commit 0811f2c02b
17 changed files with 3602 additions and 0 deletions

View file

@ -0,0 +1,25 @@
For ImageCache to work properly it needs to be able to make use fou clean URLs.
This requires some webserver specific setup.
Apache2 + mod_rewrite
Works out of the box.
LightHTTPD pre-1.4.24:
http://nordisch.org/2007/2/6/drupal-on-lighttpd-with-clean-urls
LightHTTPD 1.4.24 and later:
https://veracium.com/content/imagecache-lighttpd-witho
IIS 6:
add an error404.asp that passed everything to drupal.
<%
Response.Expires=0
strQString=Request.ServerVariables("QUERY_STRING")
If (InStr(strQString,"/d5/")) Then
pos=Instr(strQString,"/d5/")+3
Id=Right(strQString,Len(strQString)-pos)
Response.Redirect("/d5/index.php?q=" & Id)
End If
Response.Redirect("index.htm")
%>

View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1,69 @@
ImageCache is a dynamic image manipulation and cache tool. It allows you to
create a namespace that corresponds to a set of image manipulation actions. It
generates a derivative image the first time it is requested from a namespace
until the namespace or the entire imagecache is flushed.
Getting Started:
1. Upload and enable both the ImageCache and ImageCache UI modules.
2. Go to Administer -> Site Building -> ImageCache. Click on the local task tab
labeled "Add New Preset" to build a new set of image manipulation actions.
3. Enter a descriptive name of your choice (e.g. 'product_thumbnail') into the
"Preset Namespace" box and click "Create New Preset".
4. Add actions to your preset that tell ImageCache how to manipulate the
original image when it is rendered for display. Available actions include
crop, scale, desaturate (grey scale), resize, and rotate. Multiple actions
may be added to a preset.
5. Each action is configured in its own form, and the actions may be reordered
from the preset's configuration form. If you need to make any changes to the
order of actions in a preset, remember to click "Update Preset" when you're
finished.
Viewing Manipulated Images:
Your modified image can be viewed by visiting a URL in this format:
http://example.com/files/imagecache/preset-name/files/image-name.jpg
For example, if your preset is named 'product_thumbnail' and your image is
named 'green-widget.jpg', you could view your modified image at:
http://example.com/files/imagecache/product_thumbnail/files/green-widget...
NOTE: Each role that wishes to view the images generated by a
particular preset must be given permission on the admin/user/permissions
page.
ImageCache also defines a theme function that you can use in your modules and
themes to automatically display a manipulated image. For example, to use the
theme function in a .tpl.php file, add the following line where you would like
the image to appear:
<?php
print theme('imagecache', 'preset_namespace', $image_filepath, $alt, $title, $attributes);
?>
Change 'preset_namespace' to the name of your imagecache preset and make sure
that $image_filepath or some other variable contains the actual filepath to
the image you would like to display.
$alt, $title and $attributes are optional parameters that specify ALT/TITLE
text for the image element in the HTML or other attributes as specified in the
$attributes array.
Using ImageCache with Contributed Modules:
ImageCache presets can be put to use in various other modules. For example, when
using CCK with the Imagefield module, you can use the "Display fields" local
task tab to choose a preset to apply to images in that field. Similarly, you
can specify a preset when displaying images attached to nodes using Imagefield
in a View through the Views UI.
For more information, refer to http://drupal.org/node/163561.
(Images, page names, and form field names may refer to previous versions of
ImageCache, but the concepts are the same.)

View file

@ -0,0 +1,7 @@
Upgrading From imagecache version 1.x to 2.0
-- Install ImageAPI before attempting to upgrade to imagecache 2.x. Your site will 'Blow UP' otherwise.
-- The old ImageScale actions should be turned into Deprecated Scale actions. You
should update your presets to use the new scale or 'scale and crop' actions.

View file

@ -0,0 +1,102 @@
<?php
/**
* @file
* Hooks provided by the ImageCache module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Inform ImageCache about actions that can be performed on an image.
*
* @return array
* An array of information on the actions implemented by a module. The array
* contains a sub-array for each action node type, with the machine-readable
* action name as the key. Each sub-array has up to 3 attributes. Possible
* attributes:
* "name": the human-readable name of the action. Required.
* "description": a brief description of the action. Required.
* "file": the name of the include file the action can be found
* in relative to the implementing module's path.
*/
function hook_imagecache_actions() {
$actions = array(
'imagecache_resize' => array(
'name' => 'Resize',
'description' => 'Resize an image to an exact set of dimensions, ignoring aspect ratio.',
),
);
}
/**
* Provides default ImageCache presets that can be overridden by site
* administrators.
*
* @return array
* An array of imagecache preset definitions. Each definition can be
* generated by exporting a preset from the database. Each preset
* definition should be keyed on its presetname (for easier interaction
* with drupal_alter) and have the following attributes:
* "presetname": the imagecache preset name. Required.
* "actions": an array of action defintions for this preset. Required.
*/
function hook_imagecache_default_presets() {
$presets = array();
$presets['thumbnail'] = array (
'presetname' => 'thumbnail',
'actions' => array (
0 => array (
'weight' => '0',
'module' => 'imagecache',
'action' => 'imagecache_scale_and_crop',
'data' => array (
'width' => '60',
'height' => '60',
),
),
),
);
return $presets;
}
/**
* Allows other modules to perform actions on an image before it is flushed.
*
* This hook can be used to send purge requests to a reverse proxy or delete
* a file from a remote file server or CDN when the imagecached version is
* flushed.
*
* Implementations of hook_imagecache_image_flush should not delete the image
* at $filepath, as ImageCache will perform this action.
*
* @param $derivative_path
* The path to the file about to be flushed.
* @param $preset
* An ImageCache preset array.
* @param $original_path
* The Drupal file path to the original image.
*/
function hook_imagecache_image_flush($derivative_path, $preset, $original_path) {
}
/**
* Allows other modules to perform actions when a preset is about to be flushed.
*
* This hook can be used to send purge requests to a reverse proxy or delete
* files from a remote file server or CDN when the imagecached versions are
* flushed.
*
* Implementations of hook_imagecache_preset_flush should not delete the
* images in $presetdir, as ImageCache will perform this action.
*
* @param $presetdir
* The directory containing the images about to be flushed.
* @param $preset
* An ImageCache preset array.
*/
function hook_imagecache_preset_flush($presetdir, $preset) {
}

View file

@ -0,0 +1,169 @@
<?php
/**
* Implementation of hook_drush_command().
*/
function imagecache_drush_command() {
$items = array();
$items['imagecache-flush'] = array(
'callback' => 'imagecache_drush_preset_flush',
'description' => dt('Flush an imagecache preset.'),
'examples' => array(
'drush imagecache-flush foobar' => dt('Flush the ImageCache preset "foobar".'),
),
'aliases' => array('icf'),
);
$items['imagecache-build'] = array(
'callback' => 'imagecache_drush_preset_build',
'description' => dt('Build imagecache derivates for all images for a given preset.'),
'examples' => array(
'drush imagecache-build foobar' => dt('Build all images for preset "foobar".'),
),
'aliases' => array('icb'),
);
return $items;
}
/**
* Implementation of hook_drush_help().
*/
function imagecache_drush_help($section) {
switch ($section) {
case 'drush:imagecache-flush':
return dt('Flush a given preset.');
case 'drush:imagecache-build':
return dt('Build derivative images for a given preset.');
}
}
/**
* Drush callback to perform actual imagecache preset flush.
*/
function imagecache_drush_preset_flush() {
$args = func_get_args();
// Rebuild imagecache presets.
foreach (imagecache_presets(TRUE) as $preset) {
$preset_names[] = $preset['presetname'];
}
if (empty($args)) {
$choice = drush_choice($preset_names, 'Enter a number to choose which preset to flush.');
if ($choice !== FALSE) {
$args[] = $preset_names[$choice];
}
}
else {
// Implement 'all'
if (count($args) == 1 && $args[0] == 'all') {
$args = $preset_names;
}
}
// Remove any invalid preset names and report them as errors.
$not_found = array_diff($args, $preset_names);
$args = array_intersect($args, $preset_names);
if ($not_found) {
drush_log(dt('Preset(s) not found: @presets', array('@presets' => implode($not_found, ' '))), 'error');
}
if (empty($args)) {
return FALSE;
}
$path = drush_get_context('DRUSH_DRUPAL_ROOT') .'/'. file_directory_path() .'/imagecache/';
foreach ($args as $arg) {
// Load preset.
if ($preset = imagecache_preset_by_name($arg)) {
// This mimics the logic inside of the function
// imagecache_preset_flush(), but without the access check.
$presetdir = $path . $preset['presetname'];
if (is_dir($presetdir)) {
_imagecache_recursive_delete($presetdir);
drush_log(dt('Flushed "@preset" preset.', array('@preset' => $arg)), 'ok');
}
else {
drush_log(dt('Cache for preset "@preset" was already empty.', array('@preset' => $arg)), 'ok');
}
}
}
return TRUE;
}
/**
* Drush callback to perform actual imagecache preset build.
*/
function imagecache_drush_preset_build() {
$args = func_get_args();
// Rebuild imagecache presets.
foreach (imagecache_presets(TRUE) as $preset) {
$preset_names[] = $preset['presetname'];
}
if (empty($args)) {
$choice = drush_choice($preset_names, 'Enter a number to choose which preset to flush.');
if ($choice !== FALSE) {
$args[] = $preset_names[$choice];
}
}
elseif ($args[0] == 'all') {
// Implement 'all'
$args = $preset_names;
}
// Remove any invalid preset names and report them as errors.
$not_found = array_diff($args, $preset_names);
$args = array_intersect($args, $preset_names);
if ($not_found) {
drush_log(dt('Preset(s) not found: @presets', array('@presets' => implode($not_found, ' '))), 'error');
}
if (empty($args)) {
return FALSE;
}
// Get a list of files to processes.
$file_query = db_query("SELECT filepath FROM {files} where filemime LIKE 'image%' ORDER BY fid DESC");
$files = array();
drush_log(dt('Generating file list...', array()), 'ok');
while ($filepath = db_result($file_query)) {
if (file_exists($filepath)) {
$files[] = $filepath;
}
}
if (empty($files)) {
drush_log(dt('No images found in the files table.', array()), 'error');
return FALSE;
}
$count = count($files);
drush_log(dt('Done. @count files to process using these presets: @presets', array('@count' => $count, '@presets' => implode(' ', $args))), 'ok');
// Generate the images.
$counter = 0;
$mod = round($count / 200);
foreach ($files as $filepath) {
foreach ($args as $arg) {
$path = imagecache_create_path($arg, $filepath);
if (!file_exists($path)) {
imagecache_generate_image($arg, $filepath);
if (file_exists($path)) {
drush_log(dt('File "@file" created.', array('@file' => $path)), 'ok');
}
else {
drush_log(dt('File "@file" not created.', array('@file' => $path)), 'error');
}
}
}
// Output progress.
$counter++;
if ($counter % $mod == 0) {
drush_log(dt('@percent% done.', array('@percent' => round($counter / $count * 100, 2))), 'ok');
}
}
return TRUE;
}

View file

@ -0,0 +1,12 @@
name = ImageCache
description = Dynamic image manipulator and cache.
package = ImageCache
dependencies[] = imageapi
core = 6.x
; Information added by drupal.org packaging script on 2012-05-23
version = "6.x-2.0-rc1"
core = "6.x"
project = "imagecache"
datestamp = "1337742655"

View file

@ -0,0 +1,322 @@
<?php
function imagecache_requirements($phase) {
$requirements = array();
// Ensure translations don't break at install time.
$t = get_t();
if ($phase == 'runtime') {
$imagecache_directory = file_create_path() .'/imagecache';
if (!file_check_directory($imagecache_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
if (!is_dir($imagecache_directory)) {
$requirements['imagecache_directory'] = array(
'title' => $t('ImageCache Directory'),
'value' => $t('%p is not a directory or is not readable by the webserver.', array('%p' => $imagecache_directory)),
'severity' => REQUIREMENT_ERROR,
);
}
elseif (!is_writable($imagecache_directory)) {
$requirements['imagecache_directory'] = array(
'title' => $t('ImageCache Directory'),
'value' => $t('%p is not writeable by the webserver.', array('%p' => $imagecache_directory)),
'severity' => REQUIREMENT_ERROR,
);
}
else {
$requirements['imagecache_directory'] = array(
'title' => $t('ImageCache Directory'),
'value' => $t('An unknown error occured.'),
'description' => $t('An unknown error occured trying to verify %p is a directory and is writable.', array('%p' => $imagecache_directory)),
'severity' => REQUIREMENT_ERROR,
);
}
}
if (!is_writable(file_directory_temp())) {
$requirements['imagecache_directory'] = array(
'title' => $t('ImageCache Temp Directory'),
'value' => $t('%p is not writeable by the webserver.', array('%p' => file_directory_temp())),
'severity' => REQUIREMENT_ERROR,
);
}
}
return $requirements;
}
function imagecache_schema() {
$schema['imagecache_preset'] = array(
'fields' => array(
'presetid' => array(
'description' => t('The primary identifier for an imagecache_preset.'),
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'presetname' => array(
'description' => t('The primary identifier for a node.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
),
),
'primary key' => array('presetid'),
);
$schema['imagecache_action'] = array(
'fields' => array(
'actionid' => array(
'description' => t('The primary identifier for an imagecache_action.'),
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'presetid' => array(
'description' => t('The primary identifier for an imagecache_preset.'),
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'weight' => array(
'description' => t('The weight of the action in the preset.'),
'type' => 'int',
'not null' => TRUE,
'default' => 0,
),
'module' => array(
'description' => t('The module that defined the action.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
),
'action' => array(
'description' => t('The unique ID of the action to be executed.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
),
'data' => array(
'description' => t('The configuration data for the action.'),
'type' => 'text',
'not null' => TRUE,
'size' => 'big',
'serialize' => TRUE,
),
),
'primary key' => array('actionid'),
'indexes' => array(
'presetid' => array('presetid'),
),
);
return $schema;
}
/**
* Implementation of hook_install().
*/
function imagecache_install() {
drupal_install_schema('imagecache');
}
/**
* Implementation of hook_uninstall().
*/
function imagecache_uninstall() {
// Remove any cached images.
$path = file_directory_path() .'/imagecache/';
if (is_dir($path)) {
_imagecache_recursive_delete($path);
}
drupal_uninstall_schema('imagecache');
}
// Add action id to actions table.
function imagecache_update_1() {
$ret = array();
$ret[] = update_sql('ALTER TABLE {imagecache_actions} ADD COLUMN actionid INT UNSIGNED NOT NULL primary key auto_increment');
return $ret;
}
// Rename rulesets to presets; Make all table names singular;
function imagecache_update_2() {
$ret = array();
$ret[] = update_sql('ALTER TABLE {imagecache_rulesets} RENAME TO {imagecache_preset}');
$ret[] = update_sql('ALTER TABLE {imagecache_actions} RENAME TO {imagecache_action}');
switch ($GLOBALS['db_type']) {
case 'mysql':
case 'mysqli':
$ret[] = update_sql('ALTER TABLE {imagecache_preset} CHANGE rulesetid presetid INT UNSIGNED NOT NULL AUTO_INCREMENT');
$ret[] = update_sql('ALTER TABLE {imagecache_preset} CHANGE rulesetname presetname VARCHAR(255) NOT NULL DEFAULT \'\'');
$ret[] = update_sql('ALTER TABLE {imagecache_action} CHANGE rulesetid presetid INTEGER NOT NULL DEFAULT 0');
break;
case 'pgsql':
$ret[] = update_sql('ALTER TABLE {imagecache_preset} RENAME COLUMN rulesetid TO presetid');
$ret[] = update_sql('ALTER TABLE {imagecache_preset} RENAME COLUMN rulesetname TO presetname');
$ret[] = update_sql('ALTER TABLE {imagecache_action} RENAME COLUMN rulesetid TO presetid');
break;
}
return $ret;
}
/**
* Remove auto-increment from tables, instead depending on the sequences table and db_next_id()
*/
function imagecache_update_3() {
$ret = array();
$count_action = db_result(db_query('SELECT max(actionid) FROM {imagecache_action}')) + 1;
$count_preset = db_result(db_query('SELECT max(presetid) FROM {imagecache_preset}')) + 1;
switch ($GLOBALS['db_type']) {
case 'mysql':
case 'mysqli':
$ret[] = update_sql("ALTER TABLE {imagecache_action} CHANGE actionid actionid INT UNSIGNED NOT NULL");
$ret[] = update_sql("ALTER TABLE {imagecache_preset} CHANGE presetid presetid INT UNSIGNED NOT NULL");
// Add the sequences
$ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{imagecache_action}_actionid', $count_action)");
$ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{imagecache_preset}_presetid', $count_preset)");
break;
case 'pgsql':
db_change_column($ret, 'imagecache_action', 'actionid', 'actionid', 'INT', $attributes = array('not null' => TRUE, 'default' => '0'));
db_change_column($ret, 'imagecache_preset', 'presetid', 'presetid', 'INT', $attributes = array('not null' => TRUE, 'default' => '0'));
// Re-add our indexes
$ret[] = update_sql("ALTER TABLE {imagecache_action} ADD PRIMARY KEY (actionid)");
$ret[] = update_sql("ALTER TABLE {imagecache_preset} ADD PRIMARY KEY (rulesetid)");
// Add the sequences
$ret[] = update_sql("CREATE SEQUENCE {imagecache_action}_actionid_seq INCREMENT 1 START $count_action;");
$ret[] = update_sql("CREATE SEQUENCE {imagecache_preset}_presetid_seq INCREMENT 1 START $count_preset;");
}
return $ret;
}
function imagecache_update_4() {
$ret = array();
// add action column to the imagecache_action table just becuase serialization bugs me.
switch ($GLOBALS['db_type']) {
case 'mysql':
case 'mysqli':
$ret[] = update_sql("ALTER TABLE {imagecache_action} ADD COLUMN action varchar(255) not null default '' after weight");
break;
case 'pgsql':
$ret[] = update_sql("ALTER TABLE {imagecache_action} ADD COLUMN action varchar(255) NOT NULL DEFAULT ''");
break;
}
// unserialize what we can.
$result = db_query("SELECT * FROM {imagecache_action}");
while ($row = db_fetch_array($result)) {
$data = unserialize($row['data']);
// remove function from data if present;
$function = $data['function'];
unset($data['function']);
$data = serialize($data);
// Rename scale and crop for any people who upgraded early...
if ($function == 'scale and crop') {
$function = 'scale_and_crop';
}
// Keep scale and crop and the old scale function seperate... I don't really want to break BC with
// the 2.x update. We'll deprecate this version.
if ($function == 'scale') {
$function = 'deprecated_scale';
}
// prefix with module name as per new status quo.
// since other modules couldn't implement actions before this update
// we assume imagecache...
$function = 'imagecache_'. $function;
db_query("UPDATE {imagecache_action} SET action='%s', data='%s' WHERE actionid = %d", $function, $data, $row['actionid']);
}
cache_clear_all('*', 'cache', TRUE);
return $ret;
}
function imagecache_update_5() {
// enable image API.
module_rebuild_cache(); // make sure new modules are in the system table.
module_enable(array('imageapi', 'imageapi_gd', 'imageapi_imagemagick')); // enable our new module.
// @todo: update formatter names: http://cvs.drupal.org/viewvc.py/drupal/contributions/modules/imagecache/imagecache.module?r1=1.68&r2=1.68.2.8&pathrev=DRUPAL-5--2
// ln: 516 diff 511.
return array();
}
/**
* Upgrade from Drupal 5 => Drupal 6.
*
* Use serial data type for primary keys. Add module field and presetid index.
*/
function imagecache_update_6000() {
$ret = array();
// Our additions to the schema.
$schema['imagecache_preset'] = array(
'fields' => array(
'presetid' => array(
'description' => t('The primary identifier for an imagecache_preset.'),
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary key' => array('presetid'),
);
$schema['imagecache_action'] = array(
'fields' => array(
'actionid' => array(
'description' => t('The primary identifier for an imagecache_action.'),
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'module' => array(
'description' => t('The module that defined the action.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'initial' => 'imagecache',
),
),
'primary key' => array('actionid'),
);
// Update primary keys to serial type for Drupal 6
foreach ($schema as $table => $info) {
$field = $info['primary key'][0];
if (db_table_exists('sequences')) {
$ret[] = update_sql("DELETE FROM {sequences} WHERE name = '{{$table}}_{$field}'");
}
db_change_field($ret, $table, $field, $field, $info['fields'][$field]);
}
// Going to assume that if the table doesn't have a module column that
// it needs the index as well.
if (!db_column_exists('imagecache_action', 'module')) {
// Add 'module' column to action table.
db_add_field($ret, 'imagecache_action', 'module', $schema['imagecache_action']['fields']['module']);
// Add 'presetid' index to action table
db_add_index($ret, 'imagecache_action', 'presetid', array('presetid'));
}
return $ret;
}
/**
* Make sure the schemas match, the weight should be signed.
*/
function imagecache_update_6001() {
$ret = array();
db_change_field($ret, 'imagecache_action', 'weight', 'weight', array('type' => 'int', 'not null' => TRUE, 'default' => 0));
return $ret;
}

View file

@ -0,0 +1,50 @@
/*global Drupal,jQuery */
(function($) {
"use strict";
Drupal.imagecache = {
/**
* Remove the files directory prefix from a path.
*/
stripFileDirectory: function(path) {
var filePath = Drupal.settings.imagecache.filesDirectory;
if (path.substr(0, filePath.length + 1) === filePath + '/') {
path = path.substr(filePath.length + 1);
}
return path;
},
createUrl: function(preset, path) {
var stripped = this.stripFileDirectory(path);
// If the preset is invalid, return the path to the original image.
if ($.inArray(preset, Drupal.settings.imagecache.presets) !== -1) {
return Drupal.settings.imagecache.filesUrl + '/imagecache/' + preset + '/' + stripped;
}
return Drupal.settings.imagecache.filesUrl + '/' + stripped;
}
};
Drupal.theme.prototype.imagecache = function(preset, path, alt, title, attributes) {
var image;
image = new Image();
image.onload = function() {
$(this).attr({
width: $(image).width(),
height: $(image).height()
});
};
image.src = Drupal.imagecache.createUrl(preset, path);
image = $.extend(image, {
title: title,
alt: alt
}, attributes);
return image;
};
})(jQuery);
/*jslint browser: true, onevar: true, undef: true */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,340 @@
<?php
function imagecache_resize_form($action) {
$form['width'] = array(
'#type' => 'textfield',
'#title' => t('Width'),
'#default_value' => isset($action['width']) ? $action['width'] : '100%',
'#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'),
);
$form['height'] = array(
'#type' => 'textfield',
'#title' => t('Height'),
'#default_value' => isset($action['height']) ? $action['height'] : '100%',
'#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'),
);
return $form;
}
function imagecache_resize_image(&$image, $data) {
if (!imageapi_image_resize($image, $data['width'], $data['height'])) {
watchdog('imagecache', 'imagecache_resize_image failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
function theme_imagecache_resize($element) {
$data = $element['#value'];
if ($data['width'] && $data['height']) {
return check_plain($data['width']) . 'x' . check_plain($data['height']);
}
return ($data['width']) ? t('width @width', array('@width' => $data['width'])) : t('height @height', array('@height' => $data['height']));
}
/**
* ImageCache Scale
*/
function imagecache_scale_form($data = array()) {
$form = imagecache_resize_form($data);
$form['upscale'] = array(
'#type' => 'checkbox',
'#default_value' => (isset($data['upscale'])) ? $data['upscale'] : 0,
'#title' => t('Allow Upscaling'),
'#description' => t('Let scale make images larger than their original size'),
);
return $form;
}
function theme_imagecache_scale($element) {
return theme_imagecache_resize($element) . ' ' . ($element['#value']['upscale'] ? '(' . t('upscaling allowed') . ')' : '');
}
function imagecache_scale_image(&$image, $data) {
// Set impossibly large values if the width and height aren't set.
$data['width'] = $data['width'] ? $data['width'] : 9999999;
$data['height'] = $data['height'] ? $data['height'] : 9999999;
if (!imageapi_image_scale($image, $data['width'], $data['height'], $data['upscale'])) {
watchdog('imagecache', 'imagecache_scale_image failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Scale and Crop
*/
function imagecache_scale_and_crop_form($data = array()) {
return imagecache_resize_form($data);
}
function theme_imagecache_scale_and_crop($element) {
return theme_imagecache_resize($element);
}
function imagecache_scale_and_crop_image(&$image, $data) {
if (!imageapi_image_scale_and_crop($image, $data['width'], $data['height'])) {
watchdog('imagecache', 'imagecache_scale_and_crop failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Deprecated Scale.
* This will be removed in imagecache 2.1
*/
function imagecache_deprecated_scale_form($data = array()) {
$helptext = array();
$helptext['inside'] = t('<strong>Inside dimensions</strong>: Final dimensions will be less than or equal to the entered width and height. Useful for ensuring a maximum height and/or width.');
$helptext['outside'] = t('<strong>Outside dimensions</strong>: Final dimensions will be greater than or equal to the entered width and height. Ideal for cropping the result to a square.');
$description = '<ul><li>'. implode('</li><li>', $helptext) .'</li><ul>';
$form['fit'] = array(
'#type' => 'select',
'#title' => t('Scale to fit'),
'#options' => array('inside' => t('Inside dimensions'), 'outside' => t('Outside dimensions')),
'#default_value' => isset($data['fit']) ? $data['fit'] : NULL,
'#weight' => 1,
'#description' => $description,
);
$form['width'] = array(
'#type' => 'textfield',
'#title' => t('Width'),
'#default_value' => isset($data['width']) ? $data['width'] : '',
'#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'),
);
$form['height'] = array(
'#type' => 'textfield',
'#title' => t('Height'),
'#default_value' => isset($data['height']) ? $data['height'] : '',
'#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'),
);
return $form;
}
function theme_imagecache_deprecated_scale($element) {
$data = $element['#value'];
$fits = array('inside' => t('Inside dimensions'), 'outside' => t('Outside dimensions'));
return t('width: @width, height: @height, fit: @fit', array('@width' => $data['width'], '@height' => $data['height'], '@fit' => $fits[$data['fit']]));
}
function imagecache_deprecated_scale_image(&$image, $data) {
if ($data['fit'] == 'outside' && $data['width'] && $data['height']) {
$ratio = $image->info['width'] / $image->info['height'];
$new_ratio = $data['width']/$data['height'];
$data['width'] = $ratio > $new_ratio ? 0 : $data['width'];
$data['height'] = $ratio < $new_ratio ? 0 : $data['height'];
}
// Set impossibly large values if the width and height aren't set.
$data['width'] = $data['width'] ? $data['width'] : 9999999;
$data['height'] = $data['height'] ? $data['height'] : 9999999;
if (!imageapi_image_scale($image, $data['width'], $data['height'])) {
watchdog('imagecache', 'imagecache_deprecated_scale failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Crop
*/
function imagecache_crop_form($data = array()) {
$data += array(
'width' => '',
'height' => '',
'xoffset' => '',
'yoffset' => '',
);
$form['width'] = array(
'#type' => 'textfield',
'#title' => t('Width'),
'#default_value' => $data['width'],
'#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'),
);
$form['height'] = array(
'#type' => 'textfield',
'#title' => t('Height'),
'#default_value' => $data['height'],
'#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'),
);
$form['xoffset'] = array(
'#type' => 'textfield',
'#title' => t('X offset'),
'#default_value' => $data['xoffset'],
'#description' => t('Enter an offset in pixels or use a keyword: <em>left</em>, <em>center</em>, or <em>right</em>.'),
);
$form['yoffset'] = array(
'#type' => 'textfield',
'#title' => t('Y offset'),
'#default_value' => $data['yoffset'],
'#description' => t('Enter an offset in pixels or use a keyword: <em>top</em>, <em>center</em>, or <em>bottom</em>.'),
);
return $form;
}
function theme_imagecache_crop($element) {
$data = $element['#value'];
return t('width: @width, height: @height, xoffset: @xoffset, yoffset: @yoffset', array(
'@width' => $data['width'],
'@height' => $data['height'],
'@xoffset' => $data['xoffset'],
'@yoffset' => $data['yoffset'],
));
}
function imagecache_crop_image(&$image, $data) {
if (!imageapi_image_crop($image, $data['xoffset'], $data['yoffset'], $data['width'], $data['height'])) {
watchdog('imagecache', 'imagecache_crop failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Desaturate
*/
function imagecache_desaturate_form($data = array()) {
return array();
}
function theme_imagecache_desaturate($element) {
return '';
}
function imagecache_desaturate_image(&$image, $data = array()) {
if (!imageapi_image_desaturate($image)) {
watchdog('imagecache', 'imagecache_desaturate failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Rotate
*/
function imagecache_rotate_form($data = array()) {
$form['degrees'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['degrees'])) ? $data['degrees'] : 0,
'#title' => t('Rotation angle'),
'#description' => t('The number of degrees the image should be rotated. Positive numbers are clockwise, negative are counter-clockwise.'),
);
$form['random'] = array(
'#type' => 'checkbox',
'#default_value' => (isset($data['random'])) ? $data['random'] : 0,
'#title' => t('Randomize'),
'#description' => t('Randomize the rotation angle for each image. The angle specified above is used as a maximum.'),
);
$form['bgcolor'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['bgcolor'])) ? $data['bgcolor'] : '',
'#title' => t('Background color'),
'#description' => t('The background color to use for exposed areas of the image. Use web-style hex colors (#FFFFFF for white, #000000 for black). An empty value will cause images that support transparency to have transparent backgrounds, otherwise it will be white.'),
);
return $form;
}
function theme_imagecache_rotate($element) {
$data = $element['#value'];
if ($data['random']) {
return t('random between -@degrees&deg and @degrees&deg', array('@degrees' => $data['degrees']));
}
return t('@degrees&deg', array('@degrees' => $data['degrees']));
}
function imagecache_rotate_image(&$image, $data) {
// Merge in default values.
$data += array(
'degrees' => '0',
'random' => FALSE,
'bgcolor' => '',
);
// Set sane default values.
if (strlen(trim($data['bgcolor']))) {
$data['bgcolor'] = hexdec(str_replace('#', '', $data['bgcolor']));
}
else {
$data['bgcolor'] = NULL;
}
if ($data['random']) {
$degrees = abs((float)$data['degrees']);
$data['degrees'] = rand(-1 * $degrees, $degrees);
}
if (!imageapi_image_rotate($image, $data['degrees'], $data['bgcolor'])) {
watchdog('imagecache', 'imagecache_rotate_image failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* ImageCache Sharpen
*/
function imagecache_sharpen_form($data) {
$form['info'] = array(
'#value' => t('<strong>NOTE:</strong> The sigma parameter below is currently <em>only</em> used when the Imagemagick toolkit is active.'),
);
$form['radius'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['radius'])) ? $data['radius'] : '0.5' ,
'#title' => t('Radius'),
'#description' => t('The radius of the gaussian, in pixels, not counting the center pixel. If you\'re using Imagemagick, you can set this to 0 to let Imagemagick select a suitable radius. Typically 0.5 to 1 for screen resolutions. (default 0.5)'),
);
$form['sigma'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['sigma'])) ? $data['sigma'] : '0.5' ,
'#title' => t('Sigma'),
'#description' => t('The standard deviation of the gaussian, in pixels. General rule of thumb: if radius < 1 then sigma = radius, else sigma = sqrt(radius). (default 0.5)'),
);
$form['amount'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['amount'])) ? $data['amount'] : '100' ,
'#title' => t('Amount'),
'#description' => t('The percentage of the difference between the original and the blur image that is added back into the original. Typically 50 to 200. (default 100).'),
);
$form['threshold'] = array(
'#type' => 'textfield',
'#default_value' => (isset($data['threshold'])) ? $data['threshold'] : '0.05' ,
'#title' => t('Threshold'),
'#description' => t('The threshold, as a fraction of max RGB levels, needed to apply the difference amount. Typically 0 to 0.2. (default 0.05).'),
);
return $form;
}
function theme_imagecache_sharpen($element) {
$data = $element['#value'];
return t('radius: @radius, sigma: @sigma, amount: @amount, threshold: @threshold', array(
'@radius' => $data['radius'],
'@sigma' => $data['sigma'],
'@amount' => $data['amount'],
'@threshold' => $data['threshold'],
));
}
function imagecache_sharpen_image(&$image, $data) {
// Set sane default values.
$data['radius'] = $data['radius'] ? $data['radius'] : "0.5";
$data['sigma'] = $data['sigma'] ? $data['sigma'] : "0.5";
$data['amount'] = $data['amount'] ? $data['amount'] : "100";
$data['threshold'] = $data['threshold'] ? $data['threshold'] : "0.05";
if (!imageapi_image_sharpen($image, $data['radius'], $data['sigma'], $data['amount'], $data['threshold'])) {
watchdog('imagecache', 'imagecache_sharpen_image failed. image: %image, data: %data.', array('%image' => $image->source, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}

View file

@ -0,0 +1,13 @@
name = ImageCache UI
description = ImageCache User Interface.
dependencies[] = imagecache
dependencies[] = imageapi
package = ImageCache
core = 6.x
; Information added by drupal.org packaging script on 2012-05-23
version = "6.x-2.0-rc1"
core = "6.x"
project = "imagecache"
datestamp = "1337742655"

View file

@ -0,0 +1,4 @@
<?php
function imagecache_ui_install() {
}

View file

@ -0,0 +1,160 @@
<?php
/**
* Administrative interface to imagecache.
*
*/
/**
* Implementation of hook_help().
*/
function imagecache_ui_help($path, $arg) {
switch($path) {
case 'admin/build/imagecache':
return t('Manage ImageCache presets.');
case 'admin/build/imagecache/%/export':
return t('Place the following snippet in your module as part of <code>hook_imagecache_default_presets()</code>.');
}
}
/**
* Implementation of hook_menu().
*/
function imagecache_ui_menu() {
$items = array();
$items['admin/build/imagecache'] = array(
'title' => 'ImageCache',
'file' => 'imagecache_ui.pages.inc',
'description' => 'Administer imagecache presets and actions.',
'page callback' => 'imagecache_ui_preset_overview',
'access arguments' => array('administer imagecache'),
);
$items['admin/build/imagecache/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/build/imagecache/add'] = array(
'title' => 'Add new preset',
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_form'),
'access arguments' => array('administer imagecache'),
'type' => MENU_LOCAL_TASK,
);
$items['admin/build/imagecache/%imagecache_ui_preset'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Edit preset: !presetname', 3),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_form', 3),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/delete'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Delete preset: !presetname', 3),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_delete_form', 3),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/flush'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Flush preset: !presetname', 3),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_flush_form', 3),
'access arguments' => array('flush imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/export'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Export preset: !presetname', 3),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_export_form', 3),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/override'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Override preset: !presetname', 3),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_preset_form', 3, TRUE),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/add/%'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Add !actionname to !presetname', 3, 5),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'imagecache_ui_action_add_page',
'page arguments' => array(3, 5),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/%imagecache_action'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('!action for preset !presetname', 3, 4),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_action_form', 3, 4),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
$items['admin/build/imagecache/%imagecache_ui_preset/%imagecache_action/delete'] = array(
'title callback' => 'imagecache_preset_title_callback',
'title arguments' => array('Delete !action for preset !presetname', 3, 4),
'file' => 'imagecache_ui.pages.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('imagecache_ui_action_delete_form', 3, 4),
'access arguments' => array('administer imagecache'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Menu wildcard loader.
*/
function imagecache_ui_preset_load($preset_id) {
return imagecache_preset($preset_id, TRUE);
}
function imagecache_preset_title_callback($title, $preset = array(), $action = array()) {
$replacements = array();
if (!empty($preset)) {
$replacements['!presetname'] = $preset['presetname'];
$replacements['!presetid'] = $preset['presetid'];
}
if (!empty($action) && !is_array($action)) {
$replacements['!actionname'] = $action;
}
elseif (!empty($action)) {
$replacements['!action'] = $action['action'];
}
return t($title, $replacements);
}
/**
* Implementation of hook_theme().
*/
function imagecache_ui_theme() {
return array(
'imagecache_ui_preset_actions' => array(
'arguments' => array(
'form' => NULL,
),
'file' => 'imagecache_ui.pages.inc',
),
);
}

View file

@ -0,0 +1,454 @@
<?php
/**
* Preset Admin callbacks and required functions.
*/
function imagecache_ui_preset_overview() {
$header = array(t('Preset Name'), t('Storage'), t('Actions'));
$rows = array();
// Always clear the preset cache on this display.
foreach (imagecache_presets(TRUE) as $preset) {
$row = array();
$row[] = l($preset['presetname'], 'admin/build/imagecache/'. $preset['presetid']);
$links = array();
switch ($preset['storage']) {
case IMAGECACHE_STORAGE_DEFAULT:
$row[] = t('Default');
$links[] = l(t('View'), 'admin/build/imagecache/'. $preset['presetid']);
$links[] = l(t('Flush'), 'admin/build/imagecache/'. $preset['presetid'] .'/flush' );
break;
case IMAGECACHE_STORAGE_OVERRIDE:
$row[] = t('Override');
$links[] = l(t('Edit'), 'admin/build/imagecache/'. $preset['presetid']);
$links[] = l(t('Revert'), 'admin/build/imagecache/'. $preset['presetid'] .'/delete');
$links[] = l(t('Flush'), 'admin/build/imagecache/'. $preset['presetid'] .'/flush' );
$links[] = l(t('Export'), 'admin/build/imagecache/'. $preset['presetid'] .'/export' );
break;
case IMAGECACHE_STORAGE_NORMAL:
$row[] = t('Normal');
$links[] = l(t('Edit'), 'admin/build/imagecache/'. $preset['presetid']);
$links[] = l(t('Delete'), 'admin/build/imagecache/'. $preset['presetid'] .'/delete');
$links[] = l(t('Flush'), 'admin/build/imagecache/'. $preset['presetid'] .'/flush' );
$links[] = l(t('Export'), 'admin/build/imagecache/'. $preset['presetid'] .'/export' );
break;
}
$row[] = implode('&nbsp;&nbsp;&nbsp;&nbsp;', $links);
$rows[] = $row;
}
$output = theme('table', $header, $rows);
return $output;
}
function imagecache_ui_preset_delete_form($form_state, $preset = array()) {
if (empty($preset)) {
drupal_set_message(t('The specified preset was not found'), 'error');
drupal_goto('admin/build/imagecache');
}
$form = array();
$form['presetid'] = array('#type' => 'value', '#value' => $preset['presetid']);
return confirm_form(
$form,
t('Are you sure you want to delete the preset %preset?',
array('%preset' => $preset['presetname'])
),
'admin/build/imagecache',
t('This action cannot be undone.'),
t('Delete'), t('Cancel')
);
}
function imagecache_ui_preset_delete_form_submit($form, &$form_state) {
$preset = imagecache_preset($form_state['values']['presetid']);
imagecache_preset_delete($preset);
drupal_set_message(t('Preset %name (ID: @id) was deleted.', array('%name' => $preset['presetname'], '@id' => $preset['presetid'])));
$form_state['redirect'] = 'admin/build/imagecache';
}
function imagecache_ui_preset_flush_form(&$form_state, $preset = array()) {
if (empty($preset)) {
drupal_set_message(t('The specified preset was not found'), 'error');
$form_state['redirect'] = 'admin/build/imagecache';
}
$form = array();
$form['presetid'] = array('#type' => 'value', '#value' => $preset['presetid']);
return confirm_form(
$form,
t('Are you sure you want to flush the preset %preset?',
array('%preset' => $preset['presetname'])
),
'admin/build/imagecache',
t('This action cannot be undone.'),
t('Flush'), t('Cancel')
);
}
function imagecache_ui_preset_flush_form_submit($form, &$form_state) {
$preset = imagecache_preset($form_state['values']['presetid']);
imagecache_preset_flush($preset);
drupal_set_message(t('Preset %name (ID: @id) was flushed.', array('%name' => $preset['presetname'], '@id' => $preset['presetid'])));
$form_state['redirect'] = 'admin/build/imagecache';
}
/**
* Imagecache preset export form.
*/
function imagecache_ui_preset_export_form(&$form_state, $preset = array()) {
if (empty($preset)) {
drupal_set_message(t('The specified preset was not found'), 'error');
$form_state['redirect'] = 'admin/build/imagecache';
}
if (isset($preset['presetid'])) {
unset($preset['presetid']);
}
if (isset($preset['storage'])) {
unset($preset['storage']);
}
foreach ($preset['actions'] as $id => $action) {
unset($preset['actions'][$id]['actionid']);
unset($preset['actions'][$id]['presetid']);
}
$exported = '$presets = array();';
$exported .= "\n";
$exported .= '$presets[\''. $preset['presetname'] .'\'] = ';
$exported .= var_export($preset, TRUE) .';';
$rows = substr_count($exported, "\n") + 1;
$form = array();
$form['export'] = array(
'#type' => 'textarea',
'#default_value' => $exported,
'#rows' => $rows,
'#resizable' => FALSE,
);
return $form;
}
function imagecache_ui_preset_form($form_state, $preset = array()) {
$form = array();
$form['presetid'] = array(
'#type' => 'value',
'#value' => isset($preset['presetid']) ? $preset['presetid'] : '',
);
// Browsers don't submit disabled form values so we've got to put two copies
// of the name on the form: one for the submit handler and one for the user.
if (isset($preset['storage']) && $preset['storage'] === IMAGECACHE_STORAGE_DEFAULT) {
$form['presetname'] = array(
'#type' => 'value',
'#value' => $preset['presetname'],
);
$form['presetname_display'] = array(
'#type' => 'textfield',
'#size' => '64',
'#title' => t('Preset Namespace'),
'#default_value' => $preset['presetname'],
'#disabled' => TRUE,
);
}
else {
$form['presetname'] = array(
'#type' => 'textfield',
'#size' => '64',
'#title' => t('Preset Namespace'),
'#default_value' => isset($preset['presetname']) ? $preset['presetname'] : '',
'#description' => t('The namespace is used in URL\'s for images to tell imagecache how to process an image. Please only use alphanumeric characters, underscores (_), and hyphens (-) for preset names.'),
'#validate' => array('imagecache_element_presetname_validate' => array()),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => isset($preset['storage']) && $preset['storage'] === IMAGECACHE_STORAGE_DEFAULT ? t('Override Defaults') : t('Save Preset'),
'#weight' => 9,
);
// For new presets don't show the preview or all actions to be added.
if (empty($preset['presetid'])) {
return $form;
}
$form['actions'] = array(
'#type' => 'fieldset',
'#title' => t('Actions'),
'#tree' => TRUE,
'#theme' => 'imagecache_ui_preset_actions',
);
foreach ($preset['actions'] as $i => $action) {
// skip unknown actions...
if (!$definition = imagecache_action_definition($action['action'])) {
continue;
}
$action_form['name'] = array(
'#value' => t($definition['name']),
);
$action_form['action'] = array(
'#type' => 'value',
'#value' => $action['action'],
);
$action_form['actionid'] = array(
'#type' => 'value',
'#value' => $action['actionid'],
);
$action_form['presetid'] = array(
'#type' => 'value',
'#value' => $action['presetid'],
);
$action_form['settings'] = array(
'#theme' => $action['action'],
'#value' => $action['data'],
);
$action_form['data'] = array(
'#type' => 'value',
'#value' => $action['data'],
);
$action_form['weight'] = array(
'#type' => 'weight',
'#default_value' => $action['weight'],
'#access' => $preset['storage'] !== IMAGECACHE_STORAGE_DEFAULT,
);
$action_form['configure'] = array(
'#value' => l(t('Configure'), 'admin/build/imagecache/'. $action['presetid'] .'/'. $action['actionid'] ),
'#access' => $preset['storage'] !== IMAGECACHE_STORAGE_DEFAULT,
);
$action_form['remove'] = array(
'#value' => l(t('Delete'), 'admin/build/imagecache/'. $action['presetid'] .'/'. $action['actionid'] .'/delete'),
'#access' => $preset['storage'] !== IMAGECACHE_STORAGE_DEFAULT,
);
$form['actions'][$i] = $action_form;
}
$form['actions']['new'] = array(
'#tree' => FALSE,
'#type' => 'fieldset',
'#title' => t('New Actions'),
'#collapsible' => TRUE,
'#collapsed' => count($preset['actions']) > 0,
'#access' => $preset['storage'] !== IMAGECACHE_STORAGE_DEFAULT,
);
foreach (imagecache_action_definitions() as $action => $definition) {
$form['actions']['new'][] = array(
'#type' => 'markup',
'#prefix' => '<div>',
'#suffix' => '</div>',
'#value' => l(t('Add !action', array('!action' => $definition['name'])),
'admin/build/imagecache/'. $preset['presetid'] .'/add/'. $action) .
' - '. $definition['description'],
);
}
// Display a preview image for this action. Put it below the submit button so
// users don't have to do a bunch of scrolling.
$preview_path = file_create_path('imagecache_sample.png');
if (!file_exists($preview_path)) {
// Copy of the image into the files directory so rather than generating it
// from the original so we don't end up creating subdirectories mirroring
// the path to the this module.
$preview_path = drupal_get_path('module', 'imagecache_ui') .'/sample.png';
file_copy($preview_path, 'imagecache_sample.png');
}
imagecache_image_flush($preview_path);
$imagecache_path = imagecache_create_url($preset['presetname'], $preview_path, TRUE);
$form['preview'] = array(
'#type' => 'item',
'#title' => t('Preview'),
'#value' => l($imagecache_path, $imagecache_path) .'<br />'. l("<img src='$imagecache_path' />", $imagecache_path, array('html' => TRUE)),
'#weight' => 10,
);
return $form;
}
function imagecache_ui_preset_form_validate($form, &$form_state) {
$values = $form_state['values'];
// Check for duplicates
foreach (imagecache_presets() as $preset) {
if ($values['presetname'] == $preset['presetname'] && $values['presetid'] != $preset['presetid']) {
form_set_error('presetname', t('The preset name you have chosen is already in use.'));
break;
}
}
// Check for illegal characters in preset names
if (preg_match('/[^0-9a-zA-Z_\-]/', $values['presetname'])) {
form_set_error('presetname', t('Please only use alphanumeric characters, underscores (_), and hyphens (-) for preset names.'));
}
}
function imagecache_ui_preset_form_submit($form, &$form_state) {
// Save the preset first to retrieve the presetid when overriding
$preset = imagecache_preset_save($form_state['values']);
// Populate the presetid as needed for overrides
if (isset($form_state['values']['actions'])) {
foreach($form_state['values']['actions'] as $action) {
if (empty($action['presetid'])) {
$action['presetid'] = $preset['presetid'];
}
imagecache_action_save($action);
}
}
// Push back to the preset form
$form_state['redirect'] = 'admin/build/imagecache/'. $preset['presetid'];
}
function theme_imagecache_ui_preset_actions($form) {
$header = array(t('Action'), t('Settings'));
// $header = array(, t('Weight'), '','');
$rows = array();
foreach(element_children($form) as $key) {
if (!is_numeric($key)) {
continue;
}
$row = array();
$row[] = drupal_render($form[$key]['name']);
$row[] = drupal_render($form[$key]['settings']);
// Check for form access before rendering these portions of the table / header
if (!empty($form[$key]['weight']['#access'])) {
if (empty($header['weight'])) {
$header['weight'] = t('Weight');
}
$form[$key]['weight']['#attributes']['class'] = 'imagecache-action-order-weight';
$row[] = drupal_render($form[$key]['weight']);
}
if (!empty($form[$key]['configure']['#access'])) {
if (empty($header['configure'])) {
$header['configure'] = '';
}
$row[] = drupal_render($form[$key]['configure']);
}
if (!empty($form[$key]['remove']['#access'])) {
if (empty($header['remove'])) {
$header['remove'] = '';
}
$row[] = drupal_render($form[$key]['remove']);
}
$rows[] = array(
'data' => $row,
'class' => 'draggable',
);
}
$output = '';
if ($rows) {
drupal_add_tabledrag('imagecache-preset-actions', 'order', 'sibling', 'imagecache-action-order-weight');
$output = theme('table', $header, $rows, array('id' => 'imagecache-preset-actions'));
}
$output .= drupal_render($form);
return $output;
}
/**
* Page with form for adding a new action to add to a preset.
*/
function imagecache_ui_action_add_page($preset, $actionname) {
// Make sure the name is valid.
if (!$definition = imagecache_action_definition($actionname)) {
drupal_set_message(t('Unknown action.'), 'error');
drupal_goto('admin/build/imagecache/'. $preset['presetid']);
}
$action = array(
'presetid' => $preset['presetid'],
'action' => $actionname,
'data' => array(),
);
return drupal_get_form('imagecache_ui_action_form', $preset, $action);
}
function imagecache_ui_action_form($form_state, $preset, $action) {
// Do some error checking.
if (empty($preset['presetid'])) {
drupal_set_message(t('Unknown preset.'), 'error');
drupal_goto('admin/build/imagecache');
}
if (empty($action['action']) || !$definition = imagecache_action_definition($action['action'])) {
drupal_set_message(t('Unknown action.'), 'error');
drupal_goto('admin/build/imagecache/'. $preset['presetid']);
}
if ($action['presetid'] != $preset['presetid']) {
drupal_set_message(t('This %action action is not associated %preset preset.', array('%action' => $action['action'], '%preset' => $preset['presetname'])), 'error');
drupal_goto('admin/build/imagecache/'. $preset['presetid']);
}
$form['#tree'] = TRUE;
$form['presetid'] = array(
'#type' => 'value',
'#value' => $action['presetid'],
);
$form['actionid'] = array(
'#type' => 'value',
'#value' => isset($action['actionid']) ? $action['actionid']: '',
);
$form['action'] = array(
'#type' => 'value',
'#value' => $action['action'],
);
if (!empty($definition['file'])) {
require_once($definition['file']);
}
if (function_exists($action['action'] .'_form')) {
$form['data'] = call_user_func($action['action'] .'_form', $action['data']);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => empty($action['actionid']) ? t('Create Action') : t('Update Action'),
);
return $form;
}
function imagecache_ui_action_form_submit($form, &$form_state) {
imagecache_action_save($form_state['values']);
if (empty($form_state['values']['presetid'])) {
drupal_set_message(t('The action was succesfully created.'));
}
else {
drupal_set_message(t('The action was succesfully updated.'));
}
$form_state['redirect'] = 'admin/build/imagecache/'. $form_state['values']['presetid'];
}
function imagecache_ui_action_delete_form($form_state, $preset = array(), $action = array()) {
if (empty($action)) {
drupal_set_message(t('Unknown Action.'), 'error');
drupal_goto('admin/build/imagecache');
}
if (empty($preset)) {
drupal_set_message(t('Unknown Preset.'), 'error');
drupal_goto('admin/build/imagecache');
}
$form = array();
$form['actionid'] = array('#type' => 'value', '#value' => $action['actionid']);
return confirm_form(
$form,
t('Are you sure you want to delete the !action action from preset !preset?',
array('!preset' => $preset['presetname'], '!action' => $action['name'])
),
'admin/build/imagecache',
t('This action cannot be undone.'),
t('Delete'), t('Cancel')
);
}
function imagecache_ui_action_delete_form_submit($form, &$form_state) {
$action = imagecache_action($form_state['values']['actionid']);
imagecache_action_delete($action);
drupal_set_message(t('The action has been deleted.'));
$form_state['redirect'] = 'admin/build/imagecache/'. $action['presetid'];
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

View file

@ -0,0 +1,169 @@
<?php // $Id$
/**
* Test class for testing imagecache_create_url() in several use cases with
* the different combinations of clean URLs and private/public download method.
*/
class ImageCacheUrlTests extends DrupalTestCase {
/**
* General admin user.
*/
var $admin_user;
/**
* The id of the php input format.
*/
var $input_format_id;
/**
* Drupal SimpleTest method: return metadata about the test.
*/
function get_info() {
return array(
'name' => 'ImageCache Create URL Tests',
'desc' => 'Assure that URLs are properly generated by imagecache_create_url(), as discussed at http://drupal.org/node/241541',
'group' => 'ImageCache',
);
}
/**
* SimpleTest core method: code run before each and every test method.
*/
function setUp() {
// Always call the setUp() function from the parent class.
parent::setUp();
// Make sure that the ImageCache module is enabled.
$this->drupalModuleEnable('imagecache');
// Create admin user
$permissions = array(
'administer filters',
);
$this->admin_user = $this->drupalCreateUserRolePerm($permissions);
// Log in with admin user.
$this->drupalLoginUser($this->admin_user);
// Add an input format with PHP evaluator.
$edit = array(
'name' => $this->randomName(10, 'inputformat_'),
'filters[filter/1]' => TRUE,
'roles[2]' => TRUE,
);
$this->drupalPostRequest('admin/settings/filters/add', $edit, t('Save configuration'));
// Store the format id of the created input format.
$this->input_format_id = db_result(db_query("SELECT format FROM {filter_formats} WHERE name = '%s'", $edit['name']));
$this->assertTrue($this->input_format_id, t('Input format id (%s)'));
}
/**
* SimpleTest core method: code run after each and every test method.
*/
function tearDown() {
// Remove input format.
$this->drupalPostRequest('admin/settings/filters/delete/'. $this->input_format_id, array(), t('Delete'));
// Log out admin user.
$this->drupalGet('logout');
// Always call the tearDown() function from the parent class.
parent::tearDown();
}
/**
* Test function that tests imagecache_create_url() under
* the different combinations of clean URLs and file download method
*/
function testImageCacheCreateUrl() {
// No Clean URLs + public downloads : http://example.com/?q=path/to/files/imagecache/preset/foo.jpg
$this->_ImagecacheCreateUrlTest(
false, FILE_DOWNLOADS_PUBLIC,
'path/to/files', 'preset', 'foo.jpg',
'http://example.com/?q=path/to/files/imagecache/preset/foo.jpg'
);
// Clean URLs + public downloads : http://example.com/path/to/files/imagecache/preset/foo.jpg
$this->_ImagecacheCreateUrlTest(
true, FILE_DOWNLOADS_PUBLIC,
'path/to/files', 'preset', 'foo.jpg',
'http://example.com/path/to/files/imagecache/preset/foo.jpg'
);
// No Clean URLs + private downloads : http://example.com/?q=system/files/imagecache/preset/foo.jpg
$this->_ImagecacheCreateUrlTest(
false, FILE_DOWNLOADS_PRIVATE,
'path/to/files', 'preset', 'foo.jpg',
'http://example.com/?q=system/files/imagecache/preset/foo.jpg'
);
// Clean URLs + private downloads : http://example.com/system/files/imagecache/preset/foo.jpg
$this->_ImagecacheCreateUrlTest(
true, FILE_DOWNLOADS_PRIVATE,
'path/to/files', 'preset', 'foo.jpg',
'http://example.com/system/files/imagecache/preset/foo.jpg'
);
}
/**
* Function to actually perform URL tests.
* @param $clean_url
* 'clean_url' setting for test.
* @param $file_downloads
* 'file_downloads' setting for test.
* @param $file_directory_path
* 'file_directory_path' setting for tests.
* @param $preset
* imagecache preset name to be used for test.
* @param $path
* file path to be used for generating output.
* @param $expected
* the url expected as output from imagecache_create_url
*
* Note about the implementation:
* At first sight one might think this can be easily implemented with just
* setting the Drupal settings, calling imagecache_create_url() and checking
* the result. This does not work however because the url() function, which is
* used by imagecache_create_url(), caches the clean_url setting with an
* internal static variable. This means that only one setting of clean_url
* can be evaluated per page view.
* To make testing possible, this function creates a node with the PHP
* evaluator as input filter and puts a proper call to imagecache_create_url()
* in the node body. The node view, which is a page view on its own can then
* be checked for the correctly generated URL.
*/
private function _ImagecacheCreateUrlTest($clean_url, $file_downloads, $file_directory_path, $preset, $path, $expected) {
// Drupal settings
$this->drupalVariableSet('clean_url', $clean_url);
$this->drupalVariableSet('file_downloads', $file_downloads);
$this->drupalVariableSet('file_directory_path', $file_directory_path);
// Build node body (php code).
$body = "<?php
// Change base_url
\$GLOBALS['base_url'] = 'http://example.com';
// Generate URL and check it.
echo imagecache_create_url('$preset', '$path');
?>";
// Create node.
$node = $this->drupalCreateNode(array(
'body' => $body,
'format' => $this->input_format_id,
));
// Show node.
$this->drupalGet(url('node/' . $node->nid, NULL, NULL, TRUE));
// Check if expected url shows up
$this->assertWantedRaw($expected,
t('[ImageCacheUrlTests] @clean_url + @file_downloads should return "@expected"', array(
'@clean_url' => ($clean_url ? 'Clean URLs' : 'No clean URLs'),
'@file_downloads' => ($file_downloads == FILE_DOWNLOADS_PRIVATE ? 'private downloads' : 'public downloads'),
'@expected' => $expected)
)
);
}
}