first import

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-08 11:40:19 +02:00
commit 1bc61b12ad
8435 changed files with 1582817 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
This document explains how to provide "Pathauto integration" in a
module. You need this if you would like to provide additional tokens
or if your module has paths and you wish to have them automatically
aliased. The simplest integration is just to provide tokens so we
cover that first. More advanced integration requires an
implementation of hook_pathauto to provide a settings form.
It may be helpful to review some examples of integration from the
pathauto_node.inc, pathauto_taxonomy.inc, and pathauto_user.inc files.
==================
1 - Providing additional tokens
==================
If all you want is to enable tokens for your module you will simply
need to implement two functions:
hook_token_values
hook_token_list
See the token.module and it's API.txt for more information about this
process.
If the token is intended to generate a path expected to contain slashes,
the token name must end in 'path', 'path-raw' or 'alias'. This indicates to
Pathauto that the slashes should not be removed from the replacement value.
When an object is created (whether it is a node or a user or a
taxonomy term) the data that Pathauto hands to the token_values in the
$object is in a specific format. This is the format that most people
write code to handle. However, during edits and bulk updates the data
may be in a totally different format. So, if you are writing a
hook_token_values implementation to add special tokens, be sure to
test creation, edit, and bulk update cases to make sure your code will
handle it.
==================
2 - Settings hook - To create aliases for your module
==================
You must implement hook_pathauto($op), where $op is always (at this
time) 'settings'. Return an object (NOT an array) containing the
following members, which will be used by pathauto to build a group
of settings for your module and define the variables for saving your
settings:
module - The name of your module (e.g., 'node')
groupheader - The translated label for the settings group (e.g.,
t('Content path settings')
patterndescr - The translated label for the default pattern (e.g.,
t('Default path pattern (applies to all content types with blank patterns below)')
patterndefault - A translated default pattern (e.g., t('[cat]/[title].html'))
token_type - The token type (e.g. 'node', 'user') that can be used.
patternitems - For modules which need to express multiple patterns
(for example, the node module supports a separate pattern for each
content type), an array whose keys consist of identifiers for each
pattern (e.g., the content type name) and values consist of the
translated label for the pattern
bulkname - For modules which support a bulk update operation, the
translated label for the action (e.g., t('Bulk update content paths'))
bulkdescr - For modules which support a bulk update operation, a
translated, more thorough description of what the operation will do
(e.g., t('Generate aliases for all existing content items which do not already have aliases.'))
==================
2 - $alias = pathauto_create_alias($module, $op, $placeholders, $src, $type=NULL)
==================
At the appropriate time (usually when a new item is being created for
which a generated alias is desired), call pathauto_create_alias() to
generate and create the alias. See the user, taxonomy, and nodeapi hook
implementations in pathauto.module for examples.
$module - The name of your module (e.g., 'node')
$op - Operation being performed on the item ('insert', 'update', or
'bulkupdate')
$placeholders - An array whose keys consist of the translated placeholders
which appear in patterns and values are the "clean" values to be
substituted into the pattern. Call pathauto_cleanstring() on any
values which you do not know to be purely alphanumeric, to substitute
any non-alphanumerics with the user's designated separator. Note that
if the pattern has multiple slash-separated components (e.g., [term:path]),
pathauto_cleanstring() should be called for each component, not the
complete string.
Example: $placeholders[t('[title]')] = pathauto_cleanstring($node->title);
$src - The "real" URI of the content to be aliased (e.g., "node/$node->nid")
$type - For modules which provided patternitems in hook_autopath(),
the relevant identifier for the specific item to be aliased (e.g.,
$node->type)
pathauto_create_alias() returns the alias that was created.
==================
3 - Bulk update function
==================
If a module supports bulk updating of aliases, it must provide a
function of this form, to be called by pathauto when the corresponding
checkbox is selected and the settings page submitted:
function <module>_pathauto_bulkupdate()
The function should iterate over the content items controlled by the
module, calling pathauto_create_alias() for each one. It is
recommended that the function report on its success (e.g., with a
count of created aliases) via drupal_set_message().
==================
4 - Bulk delete hook_path_alias_types()
==================
For modules that create new types of pages that can be aliased with pathauto, a
hook implementation is needed to allow the user to delete them all at once.
function hook_path_alias_types()
This hook returns an array whose keys match the beginning of the source paths
(e.g.: "node/", "user/", etc.) and whose values describe the type of page (e.g.:
"content", "users"). Like all displayed strings, these descriptionsshould be
localized with t(). Use % to match interior pieces of a path; "user/%/track". This
is a database wildcard, so be careful.
==================
Modules that extend node and/or taxonomy
==================
NOTE: this is basically not true any more. If you feel you need this file an issue.
Many contributed Drupal modules extend the core node and taxonomy
modules. To extend pathauto patterns to support their extensions, they
may implement the pathauto_node and pathauto_taxonomy hooks.
To do so, implement the function <modulename>_pathauto_node (or _taxonomy),
accepting the arguments $op and $node (or $term). Two operations are
supported:
$op = 'placeholders' - return an array keyed on placeholder strings
(e.g., t('[eventyyyy]')) valued with descriptions (e.g. t('The year the
event starts.')).
$op = 'values' - return an array keyed on placeholder strings, valued
with the "clean" actual value for the passed node or category (e.g.,
pathauto_cleanstring(date('M', $eventstart)));
See contrib/pathauto_node_event.inc for an example of extending node
patterns.

View File

@@ -0,0 +1,48 @@
**Installation:
Pathauto is an extension to the path module, which must be enabled.
Pathauto also relies on the Token module, which must be downloaded and
enabled separately.
1. Unpack the Pathauto folder and contents in the appropriate modules
directory of your Drupal installation. This is probably
sites/all/modules/
2. Enable the Pathauto module in the administration tools.
3. If you're not using Drupal's default administrative account, make
sure "administer pathauto" is enabled through access control administration.
4. Visit the Pathauto settings page and make appropriate configurations
For 5.x: Administer > Site configuration > Pathauto
For 6.x: Administer > Site building > URL alias > Automated alias settings
**Transliteration support:
If you desire transliteration support in the creation of URLs (e.g. the
replacement of Á with A) then you will need to install the Transliteration
module, which can be found at http://drupal.org/project/transliteration
Once you've installed and enabled the module, simply go to
admin/config/search/path/settings and check the "Transliterate prior to
creating alias" box and path aliases should now be transliterated automagically.
**Upgrading from previous versions:
If you are upgrading from Pathauto 5.x-1.x to 5.x-2.x (or 6.x-2.x) then you
will probably need to change your patterns.
For content patterns:
[user] is now [author-name]
[cat] is now [term]
There may be other changes as well. Please review the pattern examples on
Administration > Site Configuration > Pathauto
If you upgraded from Pathauto 5.x-1.x directly without enabling Token
first then you will need to
1) download/install the Token module
2) disable the Pathauto module
3) re-enable the Pathauto module
Upgrade to 6.x:
Note that the settings page has moved so that it is more logically grouped with
other URL alias related items under
Administer > Site building > URL alias > Automated alias settings

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,94 @@
Please read this file and also the INSTALL.txt.
They contain answers to many common questions.
If you are developing for this module, the API.txt may be interesting.
If you are upgrading, check the CHANGELOG.txt for major changes.
**Description:
The Pathauto module provides support functions for other modules to
automatically generate aliases based on appropriate criteria, with a
central settings path for site administrators.
Implementations are provided for core entity types: content, taxonomy terms,
and users (including blogs and tracker pages).
Pathauto also provides a way to delete large numbers of aliases. This feature
is available at Administer > Site building > URL aliases > Delete aliases
**Benefits:
Besides making the page address more reflective of its content than
"node/138", it's important to know that modern search engines give
heavy weight to search terms which appear in a page's URL. By
automatically using keywords based directly on the page content in the URL,
relevant search engine hits for your page can be significantly
enhanced.
**Installation AND Upgrades:
See the INSTALL.txt file.
**Notices:
Pathauto just adds URL aliases to content, users, and taxonomy terms.
Because it's an alias, the standard Drupal URL (for example node/123 or
taxonomy/term/1) will still function as normal. If you have external links
to your site pointing to standard Drupal URLs, or hardcoded links in a module,
template, content or menu which point to standard Drupal URLs it will bypass
the alias set by Pathauto.
There are reasons you might not want two URLs for the same content on your
site. If this applies to you, please note that you will need to update any
hard coded links in your content or blocks.
If you use the "system path" (i.e. node/10) for menu items and settings like
that, Drupal will replace it with the url_alias.
For external links, you might want to consider the Path Redirect or
Global Redirect modules, which allow you to set forwarding either per item or
across the site to your aliased URLs.
URLs (not) Getting Replaced With Aliases:
Please bear in mind that only URLs passed through Drupal's l() or url()
functions will be replaced with their aliases during page output. If a module
or your template contains hardcoded links, such as 'href="node/$node->nid"'
those won't get replaced with their corresponding aliases. Use the
Drupal API instead:
* 'href="'. url("node/$node->nid") .'"' or
* l("Your link title", "node/$node->nid")
See http://api.drupal.org/api/HEAD/function/url and
http://api.drupal.org/api/HEAD/function/l for more information.
** Disabling Pathauto for a specific content type (or taxonomy)
When the pattern for a content type is left blank, the default pattern will be
used. But if the default pattern is also blank, Pathauto will be disabled
for that content type.
** Bulk Updates Must be Run Multiple Times:
As of 5.x-2.x Pathauto now performs bulk updates in a manner which is more
likely to succeed on large sites. The drawback is that it needs to be run
multiple times. If you want to reduce the number of times that you need to
run Pathauto you can increase the "Maximum number of objects to alias in a
bulk update:" setting under General Settings.
**WYSIWYG Conflicts - FCKEditor, TinyMCE, etc.
If you use a WYSIWYG editor, please disable it for the Pathauto admin page.
Failure to do so may cause errors about "preg_replace" problems due to the <p>
tag being added to the "strings to replace". See http://drupal.org/node/175772
**Credits:
The original module combined the functionality of Mike Ryan's autopath with
Tommy Sundstrom's path_automatic.
Significant enhancements were contributed by jdmquin @ www.bcdems.net.
Matt England added the tracker support.
Other suggestions and patches contributed by the Drupal community.
Current maintainers:
Greg Knaddison - http://growingventuresolutions.com
Mike Ryan - http://mikeryan.name
Frederik 'Freso' S. Olesen - http://freso.dk
**Changes:
See the CHANGELOG.txt file.

View File

@@ -0,0 +1,437 @@
<?php
/**
* @file
* Admin page callbacks for the Pathauto module.
*
* @ingroup pathauto
*/
/**
* Form builder; Configure the URL alias patterns.
*
* @ingroup forms
* @see system_settings_form()
*/
function pathauto_patterns_form($form, $form_state) {
// Call the hook on all modules - an array of 'settings' objects is returned
$all_settings = module_invoke_all('pathauto', 'settings');
foreach ($all_settings as $settings) {
$module = $settings->module;
$patterndescr = $settings->patterndescr;
$patterndefault = $settings->patterndefault;
$groupheader = $settings->groupheader;
$form[$module] = array(
'#type' => 'fieldset',
'#title' => $groupheader,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
// Prompt for the default pattern for this module
$variable = 'pathauto_' . $module . '_pattern';
$form[$module][$variable] = array(
'#type' => 'textfield',
'#title' => $patterndescr,
'#default_value' => variable_get($variable, $patterndefault),
'#size' => 65,
'#maxlength' => 1280,
'#element_validate' => array('token_element_validate'),
'#after_build' => array('token_element_validate'),
'#token_types' => array($settings->token_type),
'#min_tokens' => 1,
'#parents' => array($variable),
);
// If the module supports a set of specialized patterns, set
// them up here
if (isset($settings->patternitems)) {
foreach ($settings->patternitems as $itemname => $itemlabel) {
$variable = 'pathauto_' . $module . '_' . $itemname . '_pattern';
$form[$module][$variable] = array(
'#type' => 'textfield',
'#title' => $itemlabel,
'#default_value' => variable_get($variable, ''),
'#size' => 65,
'#maxlength' => 1280,
'#element_validate' => array('token_element_validate'),
'#after_build' => array('token_element_validate'),
'#token_types' => array($settings->token_type),
'#min_tokens' => 1,
'#parents' => array($variable),
);
}
}
// Display the user documentation of placeholders supported by
// this module, as a description on the last pattern
$form[$module]['token_help'] = array(
'#title' => t('Replacement patterns'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form[$module]['token_help']['help'] = array(
'#theme' => 'token_tree',
'#token_types' => array($settings->token_type),
);
}
return system_settings_form($form);
}
/**
* Form builder; Configure the Pathauto settings.
*
* @ingroup forms
* @see system_settings_form()
*/
function pathauto_settings_form($form) {
module_load_include('inc', 'pathauto');
$form['pathauto_verbose'] = array(
'#type' => 'checkbox',
'#title' => t('Verbose'),
'#default_value' => variable_get('pathauto_verbose', FALSE),
'#description' => t('Display alias changes (except during bulk updates).'),
);
$form['pathauto_separator'] = array(
'#type' => 'textfield',
'#title' => t('Separator'),
'#size' => 1,
'#maxlength' => 1,
'#default_value' => variable_get('pathauto_separator', '-'),
'#description' => t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.'),
);
$form['pathauto_case'] = array(
'#type' => 'radios',
'#title' => t('Character case'),
'#default_value' => variable_get('pathauto_case', PATHAUTO_CASE_LOWER),
'#options' => array(
PATHAUTO_CASE_LEAVE_ASIS => t('Leave case the same as source token values.'),
PATHAUTO_CASE_LOWER => t('Change to lower case'),
),
);
$max_length = _pathauto_get_schema_alias_maxlength();
$form['pathauto_max_length'] = array(
'#type' => 'textfield',
'#title' => t('Maximum alias length'),
'#size' => 3,
'#maxlength' => 3,
'#default_value' => variable_get('pathauto_max_length', 100),
'#min_value' => 1,
'#max_value' => $max_length,
'#description' => t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => url('admin/help/pathauto'), '@max' => $max_length)),
'#element_validate' => array('_pathauto_validate_numeric_element'),
);
$form['pathauto_max_component_length'] = array(
'#type' => 'textfield',
'#title' => t('Maximum component length'),
'#size' => 3,
'#maxlength' => 3,
'#default_value' => variable_get('pathauto_max_component_length', 100),
'#min_value' => 1,
'#max_value' => $max_length,
'#description' => t('Maximum text length of any component in the alias (e.g., [title]). 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => url('admin/help/pathauto'), '@max' => $max_length)),
'#element_validate' => array('_pathauto_validate_numeric_element'),
);
$description = t('What should Pathauto do when updating an existing content item which already has an alias?');
if (module_exists('redirect')) {
$description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => url('admin/config/search/redirect')));
}
else {
$description .= ' ' . t('Considering installing the <a href="!url">Redirect module</a> to get redirects when your aliases change.', array('!url' => 'http://drupal.org/project/redirect'));
}
$form['pathauto_update_action'] = array(
'#type' => 'radios',
'#title' => t('Update action'),
'#default_value' => variable_get('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE),
'#options' => array(
PATHAUTO_UPDATE_ACTION_NO_NEW => t('Do nothing. Leave the old alias intact.'),
PATHAUTO_UPDATE_ACTION_LEAVE => t('Create a new alias. Leave the existing alias functioning.'),
PATHAUTO_UPDATE_ACTION_DELETE => t('Create a new alias. Delete the old alias.'),
),
'#description' => $description,
);
$form['pathauto_transliterate'] = array(
'#type' => 'checkbox',
'#title' => t('Transliterate prior to creating alias'),
'#default_value' => variable_get('pathauto_transliterate', FALSE) && module_exists('transliteration'),
'#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the ASCII-96 alphabet? Transliteration is handled by the Transliteration module.'),
'#access' => module_exists('transliteration'),
);
$form['pathauto_reduce_ascii'] = array(
'#type' => 'checkbox',
'#title' => t('Reduce strings to letters and numbers'),
'#default_value' => variable_get('pathauto_reduce_ascii', FALSE),
'#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.'),
);
$form['pathauto_ignore_words'] = array(
'#type' => 'textarea',
'#title' => t('Strings to Remove'),
'#default_value' => variable_get('pathauto_ignore_words', PATHAUTO_IGNORE_WORDS),
'#description' => t('Words to strip out of the URL alias, separated by commas. Do not use this to remove punctuation.'),
'#wysiwyg' => FALSE,
);
$form['punctuation'] = array(
'#type' => 'fieldset',
'#title' => t('Punctuation'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$punctuation = pathauto_punctuation_chars();
foreach ($punctuation as $name => $details) {
$details['default'] = PATHAUTO_PUNCTUATION_REMOVE;
if ($details['value'] == variable_get('pathauto_separator', '-')) {
$details['default'] = PATHAUTO_PUNCTUATION_REPLACE;
}
$form['punctuation']['pathauto_punctuation_' . $name] = array(
'#type' => 'select',
'#title' => $details['name'] . ' (<code>' . check_plain($details['value']) . '</code>)',
'#default_value' => variable_get('pathauto_punctuation_' . $name, $details['default']),
'#options' => array(
PATHAUTO_PUNCTUATION_REMOVE => t('Remove'),
PATHAUTO_PUNCTUATION_REPLACE => t('Replace by separator'),
PATHAUTO_PUNCTUATION_DO_NOTHING => t('No action (do not replace)'),
),
);
}
return system_settings_form($form);
}
/**
* Validate a form element that should have an numeric value.
*/
function _pathauto_validate_numeric_element($element, &$form_state) {
$value = $element['#value'];
if (!is_numeric($value)) {
form_error($element, t('The field %name is not a valid number.', array('%name' => $element['#title'])));
}
elseif (isset($element['#max_value']) && $value > $element['#max_value']) {
form_error($element, t('The field %name cannot be greater than @max.', array('%name' => $element['#title'], '@max' => $element['#max_value'])));
}
elseif (isset($element['#min_value']) && $value < $element['#min_value']) {
form_error($element, t('The field %name cannot be less than @min.', array('%name' => $element['#title'], '@min' => $element['#min_value'])));
}
}
/**
* Validate pathauto_settings_form form submissions.
*/
function pathauto_settings_form_validate($form, &$form_state) {
module_load_include('inc', 'pathauto');
// Perform a basic check for HTML characters in the strings to remove field.
if (strip_tags($form_state['values']['pathauto_ignore_words']) != $form_state['values']['pathauto_ignore_words']) {
form_set_error('pathauto_ignore_words', t('The <em>Strings to remove</em> field must not contain HTML. Make sure to disable any WYSIWYG editors for this field.'));
}
// Validate that the separator is not set to be removed per http://drupal.org/node/184119
// This isn't really all that bad so warn, but still allow them to save the value.
$separator = $form_state['values']['pathauto_separator'];
$punctuation = pathauto_punctuation_chars();
foreach ($punctuation as $name => $details) {
if ($details['value'] == $separator) {
$action = $form_state['values']['pathauto_punctuation_' . $name];
if ($action == PATHAUTO_PUNCTUATION_REMOVE) {
drupal_set_message(t('You have configured the @name to be the separator and to be removed when encountered in strings. This can cause problems with your patterns and especially with the term:path token. You should probably set the action for @name to be "replace by separator".', array('@name' => $details['name'])), 'error');
}
}
}
}
/**
* Form contructor for path alias bulk update form.
*
* @see pathauto_bulk_update_form_submit()
* @ingroup forms
*/
function pathauto_bulk_update_form() {
$form['#update_callbacks'] = array();
$form['update'] = array(
'#type' => 'checkboxes',
'#title' => t('Select the types of un-aliased paths for which to generate URL aliases'),
'#options' => array(),
'#default_value' => array(),
);
$pathauto_settings = module_invoke_all('pathauto', 'settings');
foreach ($pathauto_settings as $settings) {
if (!empty($settings->batch_update_callback)) {
$form['#update_callbacks'][$settings->batch_update_callback] = $settings;
$form['update']['#options'][$settings->batch_update_callback] = $settings->groupheader;
}
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
return $form;
}
/**
* Form submit handler for path alias bulk update form.
*
* @see pathauto_batch_update_form()
* @see pathauto_bulk_update_batch_finished()
*/
function pathauto_bulk_update_form_submit($form, &$form_state) {
$batch = array(
'title' => t('Bulk updating URL aliases'),
'operations' => array(
array('pathauto_bulk_update_batch_start', array()),
),
'finished' => 'pathauto_bulk_update_batch_finished',
'file' => drupal_get_path('module', 'pathauto') . '/pathauto.admin.inc',
);
foreach ($form_state['values']['update'] as $callback) {
if (!empty($callback)) {
$settings = $form['#update_callbacks'][$callback];
if (!empty($settings->batch_file)) {
$batch['operations'][] = array('pathauto_bulk_update_batch_process', array($callback, $settings));
}
else {
$batch['operations'][] = array($callback, array());
}
}
}
batch_set($batch);
}
/**
* Batch callback; count the current number of URL aliases for comparison later.
*/
function pathauto_bulk_update_batch_start(&$context) {
$context['results']['count_before'] = db_select('url_alias')->countQuery()->execute()->fetchField();
}
/**
* Common batch processing callback for all operations.
*
* Required to load our include the proper batch file.
*/
function pathauto_bulk_update_batch_process($callback, $settings, &$context) {
if (!empty($settings->batch_file)) {
require_once DRUPAL_ROOT . '/' . $settings->batch_file;
}
return $callback($context);
}
/**
* Batch finished callback.
*/
function pathauto_bulk_update_batch_finished($success, $results, $operations) {
if ($success) {
// Count the current number of URL aliases after the batch is completed
// and compare to the count before the batch started.
$results['count_after'] = db_select('url_alias')->countQuery()->execute()->fetchField();
$results['count_changed'] = max($results['count_after'] - $results['count_before'], 0);
if ($results['count_changed']) {
drupal_set_message(format_plural($results['count_changed'], 'Generated 1 URL alias.', 'Generated @count URL aliases.'));
}
else {
drupal_set_message(t('No new URL aliases to generate.'));
}
}
else {
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
}
}
/**
* Menu callback; select certain alias types to delete.
*/
function pathauto_admin_delete() {
/* TODO:
1) all - DONE
2) all node aliases - DONE
4) all user aliases - DONE
5) all taxonomy aliases - DONE
6) by node type
7) by taxonomy vocabulary
8) no longer existing aliases (see http://drupal.org/node/128366 )
9) where src like 'pattern' - DON'T DO
10) where dst like 'pattern' - DON'T DO
*/
$form['delete'] = array(
'#type' => 'fieldset',
'#title' => t('Choose aliases to delete'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
// First we do the "all" case
$total_count = db_query('SELECT count(1) FROM {url_alias}')->fetchField();
$form['delete']['all_aliases'] = array(
'#type' => 'checkbox',
'#title' => t('All aliases'),
'#default_value' => FALSE,
'#description' => t('Delete all aliases. Number of aliases which will be deleted: %count.', array('%count' => $total_count)),
);
// Next, iterate over an array of objects/alias types which can be deleted and provide checkboxes
$objects = module_invoke_all('path_alias_types');
foreach ($objects as $internal_name => $label) {
$count = db_query("SELECT count(1) FROM {url_alias} WHERE source LIKE :src", array(':src' => "$internal_name%"))->fetchField();
$form['delete'][$internal_name] = array(
'#type' => 'checkbox',
'#title' => $label, // This label is sent through t() in the hard coded function where it is defined
'#default_value' => FALSE,
'#description' => t('Delete aliases for all @label. Number of aliases which will be deleted: %count.', array('@label' => $label, '%count' => $count)),
);
}
// Warn them and give a button that shows we mean business
$form['warning'] = array('#value' => '<p>' . t('<strong>Note:</strong> there is no confirmation. Be sure of your action before clicking the "Delete aliases now!" button.<br />You may want to make a backup of the database and/or the url_alias table prior to using this feature.') . '</p>');
$form['buttons']['submit'] = array(
'#type' => 'submit',
'#value' => t('Delete aliases now!'),
);
return $form;
}
/**
* Process pathauto_admin_delete form submissions.
*/
function pathauto_admin_delete_submit($form, &$form_state) {
foreach ($form_state['values'] as $key => $value) {
if ($value) {
if ($key === 'all_aliases') {
db_delete('url_alias')
->execute();
drupal_set_message(t('All of your path aliases have been deleted.'));
}
$objects = module_invoke_all('path_alias_types');
if (array_key_exists($key, $objects)) {
db_delete('url_alias')
->condition('source', db_like($key) . '%', 'LIKE')
->execute();
drupal_set_message(t('All of your %type path aliases have been deleted.', array('%type' => $objects[$key])));
}
}
}
$form_state['redirect'] = 'admin/config/search/path/delete_bulk';
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* @file
* Documentation for pathauto API.
*
* @see hook_token_info
* @see hook_tokens
*/
function hook_path_alias_types() {
}
function hook_pathauto($op) {
}
/**
* Alter Pathauto-generated aliases before saving.
*
* @param string $alias
* The automatic alias after token replacement and strings cleaned.
* @param array $context
* An associative array of additional options, with the following elements:
* - 'module': The module or entity type being aliased.
* - 'op': A string with the operation being performed on the object being
* aliased. Can be either 'insert', 'update', 'return', or 'bulkupdate'.
* - 'source': A string of the source path for the alias (e.g. 'node/1').
* This can be altered by reference.
* - 'data': An array of keyed objects to pass to token_replace().
* - 'type': The sub-type or bundle of the object being aliased.
* - 'language': A string of the language code for the alias (e.g. 'en').
* This can be altered by reference.
* - 'pattern': A string of the pattern used for aliasing the object.
*/
function hook_pathauto_alias_alter(&$alias, array &$context) {
// Add a suffix so that all aliases get saved as 'content/my-title.html'
$alias .= '.html';
// Force all aliases to be saved as language neutral.
$context['language'] = LANGUAGE_NONE;
}
/**
* Alter the list of punctuation characters for Pathauto control.
*
* @param $punctuation
* An array of punctuation to be controlled by Pathauto during replacement
* keyed by punctuation name. Each punctuation record should be an array
* with the following key/value pairs:
* - value: The raw value of the punctuation mark.
* - name: The human-readable name of the punctuation mark. This must be
* translated using t() already.
*/
function hook_pathauto_punctuation_chars_alter(array &$punctuation) {
// Add the trademark symbol.
$punctuation['trademark'] = array('value' => '™', 'name' => t('Trademark symbol'));
// Remove the dollar sign.
unset($punctuation['dollar']);
}

View File

@@ -0,0 +1,689 @@
<?php
/**
* @file
* Miscellaneous functions for Pathauto.
*
* This also contains some constants giving human readable names to some numeric
* settings; they're included here as they're only rarely used outside this file
* anyway. Use module_load_include('inc', 'pathauto') if the constants need to
* be available.
*
* @ingroup pathauto
*/
/**
* Case should be left as is in the generated path.
*/
define('PATHAUTO_CASE_LEAVE_ASIS', 0);
/**
* Case should be lowercased in the generated path.
*/
define('PATHAUTO_CASE_LOWER', 1);
/**
* "Do nothing. Leave the old alias intact."
*/
define('PATHAUTO_UPDATE_ACTION_NO_NEW', 0);
/**
* "Create a new alias. Leave the existing alias functioning."
*/
define('PATHAUTO_UPDATE_ACTION_LEAVE', 1);
/**
* "Create a new alias. Delete the old alias."
*/
define('PATHAUTO_UPDATE_ACTION_DELETE', 2);
/**
* Remove the punctuation from the alias.
*/
define('PATHAUTO_PUNCTUATION_REMOVE', 0);
/**
* Replace the punctuation with the separator in the alias.
*/
define('PATHAUTO_PUNCTUATION_REPLACE', 1);
/**
* Leave the punctuation as it is in the alias.
*/
define('PATHAUTO_PUNCTUATION_DO_NOTHING', 2);
/**
* Check to see if there is already an alias pointing to a different item.
*
* @param $alias
* A string alias.
* @param $source
* A string that is the internal path.
* @param $language
* A string indicating the path's language.
* @return
* TRUE if an alias exists, FALSE if not.
*/
function _pathauto_alias_exists($alias, $source, $language = LANGUAGE_NONE) {
$pid = db_query_range("SELECT pid FROM {url_alias} WHERE source <> :source AND alias = :alias AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", 0, 1, array(
':source' => $source,
':alias' => $alias,
':language' => $language,
':language_none' => LANGUAGE_NONE,
))->fetchField();
return !empty($pid);
}
/**
* Fetches an existing URL alias given a path and optional language.
*
* @param $source
* An internal Drupal path.
* @param $language
* An optional language code to look up the path in.
* @return
* FALSE if no alias was found or an associative array containing the
* following keys:
* - pid: Unique path alias identifier.
* - alias: The URL alias.
*/
function _pathauto_existing_alias_data($source, $language = LANGUAGE_NONE) {
$pid = db_query_range("SELECT pid FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", 0, 1, array(':source' => $source, ':language' => $language, ':language_none' => LANGUAGE_NONE))->fetchField();
return path_load(array('pid' => $pid));
}
/**
* Clean up a string segment to be used in an URL alias.
*
* Performs the following possible alterations:
* - Remove all HTML tags.
* - Process the string through the transliteration module.
* - Replace or remove punctuation with the separator character.
* - Remove back-slashes.
* - Replace non-ascii and non-numeric characters with the separator.
* - Remove common words.
* - Replace whitespace with the separator character.
* - Trim duplicate, leading, and trailing separators.
* - Convert to lower-case.
* - Shorten to a desired length and logical position based on word boundaries.
*
* This function should *not* be called on URL alias or path strings because it
* is assumed that they are already clean.
*
* @param $string
* A string to clean.
* @return
* The cleaned string.
*/
function pathauto_cleanstring($string) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
}
$cache = &$drupal_static_fast['cache'];
// Generate and cache variables used in this function so that on the second
// call to pathauto_cleanstring() we focus on processing.
if (!isset($cache)) {
$cache = array(
'separator' => variable_get('pathauto_separator', '-'),
'strings' => array(),
'transliterate' => variable_get('pathauto_transliterate', FALSE) && module_exists('transliteration'),
'punctuation' => array(),
'reduce_ascii' => (bool) variable_get('pathauto_reduce_ascii', FALSE),
'ignore_words_regex' => FALSE,
'lowercase' => (bool) variable_get('pathauto_case', PATHAUTO_CASE_LOWER),
'maxlength' => min(variable_get('pathauto_max_component_length', 100), _pathauto_get_schema_alias_maxlength()),
);
// Generate and cache the punctuation replacements for strtr().
$punctuation = pathauto_punctuation_chars();
foreach ($punctuation as $name => $details) {
$action = variable_get('pathauto_punctuation_' . $name, PATHAUTO_PUNCTUATION_REMOVE);
switch ($action) {
case PATHAUTO_PUNCTUATION_REMOVE:
$cache['punctuation'][$details['value']] = '';
break;
case PATHAUTO_PUNCTUATION_REPLACE:
$cache['punctuation'][$details['value']] = $cache['separator'];
break;
case PATHAUTO_PUNCTUATION_DO_NOTHING:
// Literally do nothing.
break;
}
}
// Generate and cache the ignored words regular expression.
$ignore_words = variable_get('pathauto_ignore_words', PATHAUTO_IGNORE_WORDS);
$ignore_words_regex = preg_replace(array('/^[,\s]+|[,\s]+$/', '/[,\s]+/'), array('', '\b|\b'), $ignore_words);
if ($ignore_words_regex) {
$cache['ignore_words_regex'] = '\b' . $ignore_words_regex . '\b';
if (function_exists('mb_eregi_replace')) {
$cache['ignore_words_callback'] = 'mb_eregi_replace';
}
else {
$cache['ignore_words_callback'] = 'preg_replace';
$cache['ignore_words_regex'] = '/' . $cache['ignore_words_regex'] . '/i';
}
}
}
// Empty strings do not need any proccessing.
if ($string === '' || $string === NULL) {
return '';
}
// Check if the string has already been processed, and if so return the
// cached result.
if (isset($cache['strings'][$string])) {
return $cache['strings'][$string];
}
// Remove all HTML tags from the string.
$output = strip_tags(decode_entities($string));
// Optionally transliterate (by running through the Transliteration module)
if ($cache['transliterate']) {
$output = transliteration_get($output);
}
// Replace or drop punctuation based on user settings
$output = strtr($output, $cache['punctuation']);
// Reduce strings to letters and numbers
if ($cache['reduce_ascii']) {
$output = preg_replace('/[^a-zA-Z0-9\/]+/', $cache['separator'], $output);
}
// Get rid of words that are on the ignore list
if ($cache['ignore_words_regex']) {
$words_removed = $cache['ignore_words_callback']($cache['ignore_words_regex'], '', $output);
if (drupal_strlen(trim($words_removed)) > 0) {
$output = $words_removed;
}
}
// Always replace whitespace with the separator.
$output = preg_replace('/\s+/', $cache['separator'], $output);
// Trim duplicates and remove trailing and leading separators.
$output = _pathauto_clean_separators($output, $cache['separator']);
// Optionally convert to lower case.
if ($cache['lowercase']) {
$output = drupal_strtolower($output);
}
// Shorten to a logical place based on word boundaries.
$output = truncate_utf8($output, $cache['maxlength'], TRUE);
// Cache this result in the static array.
$cache['strings'][$string] = $output;
return $output;
}
/**
* Trims duplicate, leading, and trailing separators from a string.
*
* @param $string
* The string to clean path separators from.
* @param $separator
* The path separator to use when cleaning.
* @return
* The cleaned version of the string.
*
* @see pathauto_cleanstring()
* @see pathauto_clean_alias()
*/
function _pathauto_clean_separators($string, $separator = NULL) {
static $default_separator;
if (!isset($separator)) {
if (!isset($default_separator)) {
$default_separator = variable_get('pathauto_separator', '-');
}
$separator = $default_separator;
}
$output = $string;
// Clean duplicate or trailing separators.
if (strlen($separator)) {
// Escape the separator.
$seppattern = preg_quote($separator, '/');
// Trim any leading or trailing separators.
$output = preg_replace("/^$seppattern+|$seppattern+$/", '', $output);
// Replace trailing separators around slashes.
if ($separator !== '/') {
$output = preg_replace("/$seppattern+\/|\/$seppattern+/", "/", $output);
}
// Replace multiple separators with a single one.
$output = preg_replace("/$seppattern+/", $separator, $output);
}
return $output;
}
/**
* Clean up an URL alias.
*
* Performs the following alterations:
* - Trim duplicate, leading, and trailing back-slashes.
* - Trim duplicate, leading, and trailing separators.
* - Shorten to a desired length and logical position based on word boundaries.
*
* @param $alias
* A string with the URL alias to clean up.
* @return
* The cleaned URL alias.
*/
function pathauto_clean_alias($alias) {
$cache = &drupal_static(__FUNCTION__);
if (!isset($cache)) {
$cache = array(
'maxlength' => min(variable_get('pathauto_max_length', 100), _pathauto_get_schema_alias_maxlength()),
);
}
$output = $alias;
// Trim duplicate, leading, and trailing back-slashes.
$output = _pathauto_clean_separators($output, '/');
// Trim duplicate, leading, and trailing separators.
$output = _pathauto_clean_separators($output);
// Shorten to a logical place based on word boundaries.
$output = truncate_utf8($output, $cache['maxlength'], TRUE);
return $output;
}
/**
* Apply patterns to create an alias.
*
* @param $module
* The name of your module (e.g., 'node').
* @param $op
* Operation being performed on the content being aliased
* ('insert', 'update', 'return', or 'bulkupdate').
* @param $source
* An internal Drupal path to be aliased.
* @param $data
* An array of keyed objects to pass to token_replace(). For simple
* replacement scenarios 'node', 'user', and others are common keys, with an
* accompanying node or user object being the value. Some token types, like
* 'site', do not require any explicit information from $data and can be
* replaced even if it is empty.
* @param $type
* For modules which provided pattern items in hook_pathauto(),
* the relevant identifier for the specific item to be aliased
* (e.g., $node->type).
* @param $language
* A string specify the path's language.
* @return
* The alias that was created.
*
* @see _pathauto_set_alias()
* @see token_replace()
*/
function pathauto_create_alias($module, $op, $source, $data, $type = NULL, $language = LANGUAGE_NONE) {
// Retrieve and apply the pattern for this content type.
$pattern = pathauto_pattern_load_by_entity($module, $type, $language);
if (empty($pattern)) {
// No pattern? Do nothing (otherwise we may blow away existing aliases...)
return '';
}
// Special handling when updating an item which is already aliased.
$existing_alias = NULL;
if ($op == 'update' || $op == 'bulkupdate') {
if ($existing_alias = _pathauto_existing_alias_data($source, $language)) {
switch (variable_get('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE)) {
case PATHAUTO_UPDATE_ACTION_NO_NEW:
// If an alias already exists, and the update action is set to do nothing,
// then gosh-darn it, do nothing.
return '';
}
}
}
// Replace any tokens in the pattern. Uses callback option to clean replacements. No sanitization.
$alias = token_replace($pattern, $data, array(
'sanitize' => FALSE,
'clear' => TRUE,
'callback' => 'pathauto_clean_token_values',
'language' => (object) array('language' => $language),
'pathauto' => TRUE,
));
// Check if the token replacement has not actually replaced any values. If
// that is the case, then stop because we should not generate an alias.
// @see token_scan()
$pattern_tokens_removed = preg_replace('/\[[^\s\]:]*:[^\s\]]*\]/', '', $pattern);
if ($alias === $pattern_tokens_removed) {
return '';
}
$alias = pathauto_clean_alias($alias);
// Allow other modules to alter the alias.
$context = array(
'module' => $module,
'op' => $op,
'source' => &$source,
'data' => $data,
'type' => $type,
'language' => &$language,
'pattern' => $pattern,
);
drupal_alter('pathauto_alias', $alias, $context);
// If we have arrived at an empty string, discontinue.
if (!drupal_strlen($alias)) {
return '';
}
// If the alias already exists, generate a new, hopefully unique, variant.
$original_alias = $alias;
pathauto_alias_uniquify($alias, $source, $language);
if ($original_alias != $alias) {
// Alert the user why this happened.
_pathauto_verbose(t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', array(
'%original_alias' => $original_alias,
'%alias' => $alias,
)), $op);
}
// Return the generated alias if requested.
if ($op == 'return') {
return $alias;
}
// Build the new path alias array and send it off to be created.
$path = array(
'source' => $source,
'alias' => $alias,
'language' => $language,
);
$path = _pathauto_set_alias($path, $existing_alias, $op);
return $path;
}
/**
* Check to ensure a path alias is unique and add suffix variants if necessary.
*
* Given an alias 'content/test' if a path alias with the exact alias already
* exists, the function will change the alias to 'content/test-0' and will
* increase the number suffix until it finds a unique alias.
*
* @param $alias
* A string with the alias. Can be altered by reference.
* @param $source
* A string with the path source.
* @param $langcode
* A string with a language code.
*/
function pathauto_alias_uniquify(&$alias, $source, $langcode) {
if (!_pathauto_alias_exists($alias, $source, $langcode)) {
return;
}
// If the alias already exists, generate a new, hopefully unique, variant
$maxlength = min(variable_get('pathauto_max_length', 100), _pathauto_get_schema_alias_maxlength());
$separator = variable_get('pathauto_separator', '-');
$original_alias = $alias;
$i = 0;
do {
// Append an incrementing numeric suffix until we find a unique alias.
$unique_suffix = $separator . $i;
$alias = truncate_utf8($original_alias, $maxlength - drupal_strlen($unique_suffix, TRUE)) . $unique_suffix;
$i++;
} while (_pathauto_alias_exists($alias, $source, $langcode));
}
/**
* Verify if the given path is a valid menu callback.
*
* Taken from menu_execute_active_handler().
*
* @param $path
* A string containing a relative path.
* @return
* TRUE if the path already exists.
*/
function _pathauto_path_is_callback($path) {
// We need to use a try/catch here because of a core bug which will throw an
// exception if $path is something like 'node/foo/bar'.
// @todo Remove when http://drupal.org/node/1302158 is fixed in core.
try {
$menu = menu_get_item($path);
}
catch (Exception $e) {
return FALSE;
}
if (isset($menu['path']) && $menu['path'] == $path) {
return TRUE;
}
elseif (is_file(DRUPAL_ROOT . '/' . $path) || is_dir(DRUPAL_ROOT . '/' . $path)) {
// Do not allow existing files or directories to get assigned an automatic
// alias. Note that we do not need to use is_link() to check for symbolic
// links since this returns TRUE for either is_file() or is_dir() already.
return TRUE;
}
return FALSE;
}
/**
* Private function for Pathauto to create an alias.
*
* @param $path
* An associative array containing the following keys:
* - source: The internal system path.
* - alias: The URL alias.
* - pid: (optional) Unique path alias identifier.
* - language: (optional) The language of the alias.
* @param $existing_alias
* (optional) An associative array of the existing path alias.
* @param $op
* An optional string with the operation being performed.
*
* @return
* The saved path from path_save() or NULL if the path was not saved.
*
* @see path_save()
*/
function _pathauto_set_alias(array $path, $existing_alias = NULL, $op = NULL) {
$verbose = _pathauto_verbose(NULL, $op);
// Alert users that an existing callback cannot be overridden automatically
if (_pathauto_path_is_callback($path['alias'])) {
if ($verbose) {
_pathauto_verbose(t('Ignoring alias %alias due to existing path conflict.', array('%alias' => $path['alias'])));
}
return;
}
// Alert users if they are trying to create an alias that is the same as the internal path
if ($path['source'] == $path['alias']) {
if ($verbose) {
_pathauto_verbose(t('Ignoring alias %alias because it is the same as the internal path.', array('%alias' => $path['alias'])));
}
return;
}
// Skip replacing the current alias with an identical alias
if (empty($existing_alias) || $existing_alias['alias'] != $path['alias']) {
$path += array('pathauto' => TRUE, 'original' => $existing_alias);
// If there is already an alias, respect some update actions.
if (!empty($existing_alias)) {
switch (variable_get('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE)) {
case PATHAUTO_UPDATE_ACTION_NO_NEW:
// Do not create the alias.
return;
case PATHAUTO_UPDATE_ACTION_LEAVE:
// Create a new alias instead of overwriting the existing by leaving
// $path['pid'] empty.
break;
case PATHAUTO_UPDATE_ACTION_DELETE:
// The delete actions should overwrite the existing alias.
$path['pid'] = $existing_alias['pid'];
break;
}
}
// Save the path array.
path_save($path);
if ($verbose) {
if (!empty($existing_alias['pid'])) {
_pathauto_verbose(t('Created new alias %alias for %source, replacing %old_alias.', array('%alias' => $path['alias'], '%source' => $path['source'], '%old_alias' => $existing_alias['alias'])));
}
else {
_pathauto_verbose(t('Created new alias %alias for %source.', array('%alias' => $path['alias'], '%source' => $path['source'])));
}
}
return $path;
}
}
/**
* Output a helpful message if verbose output is enabled.
*
* Verbose output is only enabled when:
* - The 'pathauto_verbose' setting is enabled.
* - The current user has the 'notify of path changes' permission.
* - The $op parameter is anything but 'bulkupdate' or 'return'.
*
* @param $message
* An optional string of the verbose message to display. This string should
* already be run through t().
* @param $op
* An optional string with the operation being performed.
* @return
* TRUE if verbose output is enabled, or FALSE otherwise.
*/
function _pathauto_verbose($message = NULL, $op = NULL) {
static $verbose;
if (!isset($verbose)) {
$verbose = variable_get('pathauto_verbose', FALSE) && user_access('notify of path changes');
}
if (!$verbose || (isset($op) && in_array($op, array('bulkupdate', 'return')))) {
return FALSE;
}
if ($message) {
drupal_set_message($message);
}
return $verbose;
}
/**
* Clean tokens so they are URL friendly.
*
* @param $replacements
* An array of token replacements that need to be "cleaned" for use in the URL.
* @param $data
* An array of objects used to generate the replacements.
* @param $options
* An array of options used to generate the replacements.
*/
function pathauto_clean_token_values(&$replacements, $data = array(), $options = array()) {
foreach ($replacements as $token => $value) {
// Only clean non-path tokens.
if (!preg_match('/(path|alias|url|url-brief)\]$/', $token)) {
$replacements[$token] = pathauto_cleanstring($value);
}
}
}
/**
* Return an array of arrays for punctuation values.
*
* Returns an array of arrays for punctuation values keyed by a name, including
* the value and a textual description.
* Can and should be expanded to include "all" non text punctuation values.
*
* @return
* An array of arrays for punctuation values keyed by a name, including the
* value and a textual description.
*/
function pathauto_punctuation_chars() {
$punctuation = &drupal_static(__FUNCTION__);
if (!isset($punctuation)) {
$cid = 'pathauto:punctuation:' . $GLOBALS['language']->language;
if ($cache = cache_get($cid)) {
$punctuation = $cache->data;
}
else {
$punctuation = array();
$punctuation['double_quotes'] = array('value' => '"', 'name' => t('Double quotation marks'));
$punctuation['quotes'] = array('value' => '\'', 'name' => t("Single quotation marks (apostrophe)"));
$punctuation['backtick'] = array('value' => '`', 'name' => t('Back tick'));
$punctuation['comma'] = array('value' => ',', 'name' => t('Comma'));
$punctuation['period'] = array('value' => '.', 'name' => t('Period'));
$punctuation['hyphen'] = array('value' => '-', 'name' => t('Hyphen'));
$punctuation['underscore'] = array('value' => '_', 'name' => t('Underscore'));
$punctuation['colon'] = array('value' => ':', 'name' => t('Colon'));
$punctuation['semicolon'] = array('value' => ';', 'name' => t('Semicolon'));
$punctuation['pipe'] = array('value' => '|', 'name' => t('Vertical bar (pipe)'));
$punctuation['left_curly'] = array('value' => '{', 'name' => t('Left curly bracket'));
$punctuation['left_square'] = array('value' => '[', 'name' => t('Left square bracket'));
$punctuation['right_curly'] = array('value' => '}', 'name' => t('Right curly bracket'));
$punctuation['right_square'] = array('value' => ']', 'name' => t('Right square bracket'));
$punctuation['plus'] = array('value' => '+', 'name' => t('Plus sign'));
$punctuation['equal'] = array('value' => '=', 'name' => t('Equal sign'));
$punctuation['asterisk'] = array('value' => '*', 'name' => t('Asterisk'));
$punctuation['ampersand'] = array('value' => '&', 'name' => t('Ampersand'));
$punctuation['percent'] = array('value' => '%', 'name' => t('Percent sign'));
$punctuation['caret'] = array('value' => '^', 'name' => t('Caret'));
$punctuation['dollar'] = array('value' => '$', 'name' => t('Dollar sign'));
$punctuation['hash'] = array('value' => '#', 'name' => t('Number sign (pound sign, hash)'));
$punctuation['at'] = array('value' => '@', 'name' => t('At sign'));
$punctuation['exclamation'] = array('value' => '!', 'name' => t('Exclamation mark'));
$punctuation['tilde'] = array('value' => '~', 'name' => t('Tilde'));
$punctuation['left_parenthesis'] = array('value' => '(', 'name' => t('Left parenthesis'));
$punctuation['right_parenthesis'] = array('value' => ')', 'name' => t('Right parenthesis'));
$punctuation['question_mark'] = array('value' => '?', 'name' => t('Question mark'));
$punctuation['less_than'] = array('value' => '<', 'name' => t('Less-than sign'));
$punctuation['greater_than'] = array('value' => '>', 'name' => t('Greater-than sign'));
$punctuation['slash'] = array('value' => '/', 'name' => t('Slash'));
$punctuation['back_slash'] = array('value' => '\\', 'name' => t('Backslash'));
// Allow modules to alter the punctuation list and cache the result.
drupal_alter('pathauto_punctuation_chars', $punctuation);
cache_set($cid, $punctuation);
}
}
return $punctuation;
}
/**
* Fetch the maximum length of the {url_alias}.alias field from the schema.
*
* @return
* An integer of the maximum URL alias length allowed by the database.
*/
function _pathauto_get_schema_alias_maxlength() {
$maxlength = &drupal_static(__FUNCTION__);
if (!isset($maxlength)) {
$schema = drupal_get_schema('url_alias');
$maxlength = $schema['fields']['alias']['length'];
}
return $maxlength;
}

View File

@@ -0,0 +1,15 @@
name = Pathauto
description = Provides a mechanism for modules to automatically generate aliases for the content they manage.
dependencies[] = path
dependencies[] = token
core = 7.x
files[] = pathauto.test
configure = admin/config/search/path/patterns
recommends[] = redirect
; Information added by drupal.org packaging script on 2012-08-09
version = "7.x-1.2"
core = "7.x"
project = "pathauto"
datestamp = "1344525185"

View File

@@ -0,0 +1,182 @@
<?php
/**
* @file
* Install, update, and uninstall functions for Pathauto.
*
* @ingroup pathauto
*/
/**
* Implements hook_install().
*/
function pathauto_install() {
// Set some default variables necessary for the module to perform.
variable_set('pathauto_node_pattern', 'content/[node:title]');
variable_set('pathauto_taxonomy_term_pattern', '[term:vocabulary]/[term:name]');
variable_set('pathauto_forum_pattern', '[term:vocabulary]/[term:name]');
variable_set('pathauto_user_pattern', 'users/[user:name]');
variable_set('pathauto_blog_pattern', 'blogs/[user:name]');
// Set the default separator character to replace instead of remove (default).
variable_set('pathauto_punctuation_hyphen', 1);
// Set the weight to 1
db_update('system')
->fields(array('weight' => 1))
->condition('type', 'module')
->condition('name', 'pathauto')
->execute();
}
/**
* Implements hook_uninstall().
*/
function pathauto_uninstall() {
// Delete all the pathauto variables and then clear the variable cache.
db_query("DELETE FROM {variable} WHERE name LIKE 'pathauto_%'");
cache_clear_all('variables', 'cache');
}
/**
* Remove the unsupported user/%/contact and user/%/tracker pattern variables.
*/
function pathauto_update_6200() {
variable_del('pathauto_contact_bulkupdate');
variable_del('pathauto_contact_pattern');
variable_del('pathauto_contact_supportsfeeds');
variable_del('pathauto_contact_applytofeeds');
variable_del('pathauto_tracker_bulkupdate');
variable_del('pathauto_tracker_pattern');
variable_del('pathauto_tracker_supportsfeeds');
variable_del('pathauto_tracker_applytofeeds');
}
/**
* Empty update since it is handled by pathauto_update_7000().
*/
function pathauto_update_6201() {
}
/**
* Empty update since it is handled by pathauto_update_7004().
*/
function pathauto_update_6202() {
}
/**
* Remove obsolete variables since batch API is now used.
*/
function pathauto_update_7000() {
variable_del('pathauto_max_bulk_update');
variable_del('pathauto_node_bulkupdate');
variable_del('pathauto_taxonomy_bulkupdate');
variable_del('pathauto_forum_bulkupdate');
variable_del('pathauto_user_bulkupdate');
variable_del('pathauto_blog_bulkupdate');
variable_del('pathauto_modulelist');
variable_del('pathauto_indexaliases');
variable_del('pathauto_indexaliases_bulkupdate');
}
/**
* Empty update since feed paths are no longer supported.
*/
function pathauto_update_7001() {
}
/**
* Update pathauto_taxonomy_[vid]_pattern variables to pathauto_taxonomy_[machinename]_pattern.
*/
function pathauto_update_7002() {
if (module_exists('taxonomy')) {
$vocabularies = taxonomy_get_vocabularies();
foreach ($vocabularies as $vid => $vocabulary) {
if ($vid == variable_get('forum_nav_vocabulary', '')) {
// Skip the forum vocabulary.
continue;
}
if ($pattern = variable_get('pathauto_taxonomy_' . $vid . '_pattern', '')) {
variable_set('pathauto_taxonomy_' . $vocabulary->machine_name . '_pattern', $pattern);
}
variable_del('pathauto_taxonomy_' . $vid . '_pattern');
}
}
}
/**
* Rename 'taxonomy' variables to use the entity type 'taxonomy_term'.
*/
function pathauto_update_7003() {
$variables = db_select('variable', 'v')
->fields('v', array('name'))
->condition(db_and()
->condition('name', db_like("pathauto_taxonomy_") . '%', 'LIKE')
->condition('name', db_like("pathauto_taxonomy_term_") . '%', 'NOT LIKE')
)
->execute()
->fetchCol();
foreach ($variables as $variable) {
$value = variable_get($variable);
variable_del($variable);
$variable = strtr($variable, array('pathauto_taxonomy_' => 'pathauto_taxonomy_term_'));
variable_set($variable, $value);
}
}
/**
* Remove obsolete variables for removed feed handling.
*/
function pathauto_update_7004() {
variable_del('pathauto_node_supportsfeeds');
variable_del('pathauto_node_applytofeeds');
variable_del('pathauto_taxonomy_supportsfeeds');
variable_del('pathauto_taxonomy_applytofeeds');
variable_del('pathauto_forum_supportsfeeds');
variable_del('pathauto_forum_applytofeeds');
variable_del('pathauto_user_supportsfeeds');
variable_del('pathauto_user_applytofeeds');
variable_del('pathauto_blog_supportsfeeds');
variable_del('pathauto_blog_applytofeeds');
}
/**
* Fix original incorrect tokens in taxonomy and forum patterns.
*/
function pathauto_update_7005() {
$replacements = array(
'[vocabulary:name]' => '[term:vocabulary]',
'[vocabulary:' => '[term:vocabulary:',
'[term:catpath]' => '[term:name]',
'[term:path]' => '[term:name]',
);
$variables = db_select('variable', 'v')
->fields('v', array('name'))
->condition(db_or()
->condition('name', db_like("pathauto_taxonomy_term_") . '%' . db_like('pattern'), 'LIKE')
->condition('name', db_like("pathauto_forum_") . '%' . db_like('pattern'), 'LIKE')
)
->execute()
->fetchCol();
foreach ($variables as $variable) {
if ($pattern = variable_get($variable)) {
$pattern = strtr($pattern, $replacements);
variable_set($variable, $pattern);
}
}
return 'Your Pathauto taxonomy and forum patterns have been corrected. You may wish to regenerate your taxonomy and forum term URL aliases.';
}
/**
* Build a list of Drupal 6 tokens and their Drupal 7 token names.
*/
function _pathauto_upgrade_token_list() {
$tokens = array(
//'catpath' => 'node:term-lowest:parent:path][node:term-lowest',
//'catalias' => 'node:term-lowest:path',
//'termpath' => 'term:parent:path][term:name',
//'termalias' => 'term:url:alias',
//'bookpathalias' => 'node:book:parent:path',
);
}

View File

@@ -0,0 +1,22 @@
(function ($) {
Drupal.behaviors.pathFieldsetSummaries = {
attach: function (context) {
$('fieldset.path-form', context).drupalSetSummary(function (context) {
var path = $('.form-item-path-alias input').val();
var automatic = $('.form-item-path-pathauto input').attr('checked');
if (automatic) {
return Drupal.t('Automatic alias');
}
if (path) {
return Drupal.t('Alias: @alias', { '@alias': path });
}
else {
return Drupal.t('No alias');
}
});
}
};
})(jQuery);

View File

@@ -0,0 +1,840 @@
<?php
/**
* @defgroup pathauto Pathauto: Automatically generates aliases for content
*
* The Pathauto module automatically generates path aliases for various kinds of
* content (nodes, categories, users) without requiring the user to manually
* specify the path alias. This allows you to get aliases like
* /category/my-node-title.html instead of /node/123. The aliases are based upon
* a "pattern" system which the administrator can control.
*/
/**
* @file
* Main file for the Pathauto module, which automatically generates aliases for content.
*
* @ingroup pathauto
*/
/**
* The default ignore word list.
*/
define('PATHAUTO_IGNORE_WORDS', 'a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with');
/**
* Implements hook_hook_info().
*/
function pathauto_hook_info() {
$info['pathauto'] = array('group' => 'pathauto');
$info['path_alias_types'] = array('group' => 'pathauto');
return $info;
}
/**
* Implements hook_module_implements_alter().
*
* Adds pathauto support for core modules.
*/
function pathauto_module_implements_alter(&$implementations, $hook) {
$hooks = pathauto_hook_info();
if (isset($hooks[$hook])) {
$modules = array('node', 'taxonomy', 'user', 'forum', 'blog');
foreach ($modules as $module) {
if (module_exists($module)) {
$implementations[$module] = TRUE;
}
}
// Move pathauto.module to get included first since it is responsible for
// other modules.
unset($implementations['pathauto']);
$implementations = array_merge(array('pathauto' => 'pathauto'), $implementations);
}
}
/**
* Implements hook_help().
*/
function pathauto_help($path, $arg) {
switch ($path) {
case 'admin/help#pathauto':
module_load_include('inc', 'pathauto');
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Provides a mechanism for modules to automatically generate aliases for the content they manage.') . '</p>';
$output .= '<h3>' . t('Settings') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Maximum alias and component length') . '</dt>';
$output .= '<dd>' . t('The <strong>maximum alias length</strong> and <strong>maximum component length</strong> values default to 100 and have a limit of @max from Pathauto. This length is limited by the length of the "alias" column of the url_alias database table. The default database schema for this column is @max. If you set a length that is equal to that of the one set in the "alias" column it will cause problems in situations where the system needs to append additional words to the aliased URL. You should enter a value that is the length of the "alias" column minus the length of any strings that might get added to the end of the URL. The length of strings that might get added to the end of your URLs depends on which modules you have enabled and on your Pathauto settings. The recommended and default value is 100.', array('@max' => _pathauto_get_schema_alias_maxlength())) . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_permission().
*/
function pathauto_permission() {
return array(
'administer pathauto' => array(
'title' => t('Administer pathauto'),
'description' => t('Allows a user to configure patterns for automated aliases and bulk delete URL-aliases.'),
),
'notify of path changes' => array(
'title' => t('Notify of Path Changes'),
'description' => t('Determines whether or not users are notified.'),
),
);
}
/**
* Implements hook_menu().
*/
function pathauto_menu() {
$items['admin/config/search/path/patterns'] = array(
'title' => 'Patterns',
'page callback' => 'drupal_get_form',
'page arguments' => array('pathauto_patterns_form'),
'access arguments' => array('administer pathauto'),
'type' => MENU_LOCAL_TASK,
'weight' => 10,
'file' => 'pathauto.admin.inc',
);
$items['admin/config/search/path/settings'] = array(
'title' => 'Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('pathauto_settings_form'),
'access arguments' => array('administer pathauto'),
'type' => MENU_LOCAL_TASK,
'weight' => 20,
'file' => 'pathauto.admin.inc',
);
$items['admin/config/search/path/update_bulk'] = array(
'title' => 'Bulk update',
'page callback' => 'drupal_get_form',
'page arguments' => array('pathauto_bulk_update_form'),
'access arguments' => array('administer url aliases'),
'type' => MENU_LOCAL_TASK,
'weight' => 30,
'file' => 'pathauto.admin.inc',
);
$items['admin/config/search/path/delete_bulk'] = array(
'title' => 'Delete aliases',
'page callback' => 'drupal_get_form',
'page arguments' => array('pathauto_admin_delete'),
'access arguments' => array('administer url aliases'),
'type' => MENU_LOCAL_TASK,
'weight' => 40,
'file' => 'pathauto.admin.inc',
);
return $items;
}
/**
* Load an URL alias pattern by entity, bundle, and language.
*
* @param $entity
* An entity (e.g. node, taxonomy, user, etc.)
* @param $bundle
* A bundle (e.g. content type, vocabulary ID, etc.)
* @param $language
* A language code, defaults to the LANGUAGE_NONE constant.
*/
function pathauto_pattern_load_by_entity($entity, $bundle = '', $language = LANGUAGE_NONE) {
$patterns = &drupal_static(__FUNCTION__, array());
$pattern_id = "$entity:$bundle:$language";
if (!isset($patterns[$pattern_id])) {
$variables = array();
if ($language != LANGUAGE_NONE) {
$variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
}
if ($bundle) {
$variables[] = "pathauto_{$entity}_{$bundle}_pattern";
}
$variables[] = "pathauto_{$entity}_pattern";
foreach ($variables as $variable) {
if ($pattern = trim(variable_get($variable, ''))) {
break;
}
}
$patterns[$pattern_id] = $pattern;
}
return $patterns[$pattern_id];
}
/**
* Delete multiple URL aliases.
*
* Intent of this is to abstract a potential path_delete_multiple() function
* for Drupal 7 or 8.
*
* @param $pids
* An array of path IDs to delete.
*/
function pathauto_path_delete_multiple($pids) {
foreach ($pids as $pid) {
path_delete(array('pid' => $pid));
}
}
/**
* Delete an URL alias and any of its sub-paths.
*
* Given a source like 'node/1' this function will delete any alias that have
* that specific source or any sources that match 'node/1/%'.
*
* @param $source
* An string with a source URL path.
*/
function pathauto_path_delete_all($source) {
$sql = "SELECT pid FROM {url_alias} WHERE source = :source OR source LIKE :source_wildcard";
$pids = db_query($sql, array(':source' => $source, ':source_wildcard' => $source . '/%'))->fetchCol();
if ($pids) {
pathauto_path_delete_multiple($pids);
}
}
/**
* Delete an entity URL alias and any of its sub-paths.
*
* This function also checks to see if the default entity URI is different from
* the current entity URI and will delete any of the default aliases.
*
* @param $entity_type
* A string with the entity type.
* @param $entity
* An entity object.
* @param $default_uri
* The optional default uri path for the entity.
*/
function pathauto_entity_path_delete_all($entity_type, $entity, $default_uri = NULL) {
$uri = entity_uri($entity_type, $entity);
pathauto_path_delete_all($uri['path']);
if (isset($default_uri) && $uri['path'] != $default_uri) {
pathauto_path_delete_all($default_uri);
}
}
/**
* Implements hook_field_attach_rename_bundle().
*
* Respond to machine name changes for pattern variables.
*/
function pathauto_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
$variables = db_select('variable', 'v')
->fields('v', array('name'))
->condition('name', db_like("pathauto_{$entity_type}_{$bundle_old}_") . '%', 'LIKE')
->execute()
->fetchCol();
foreach ($variables as $variable) {
$value = variable_get($variable, '');
variable_del($variable);
$variable = strtr($variable, array("{$entity_type}_{$bundle_old}" => "{$entity_type}_{$bundle_new}"));
variable_set($variable, $value);
}
}
/**
* Implements hook_field_attach_delete_bundle().
*
* Respond to sub-types being deleted, their patterns can be removed.
*/
function pathauto_field_attach_delete_bundle($entity_type, $bundle) {
$variables = db_select('variable', 'v')
->fields('v', array('name'))
->condition('name', db_like("pathauto_{$entity_type}_{$bundle}_") . '%', 'LIKE')
->execute()
->fetchCol();
foreach ($variables as $variable) {
variable_del($variable);
}
}
/**
* Implements hook_field_attach_form().
*
* Add the automatic alias form elements to an existing path form fieldset.
*/
function pathauto_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
list($id, , $bundle) = entity_extract_ids($entity_type, $entity);
if (!isset($form['path'])) {
// This entity must be supported by core's path.module first.
// @todo Investigate removing this and supporting all fieldable entities.
return;
}
else {
// Taxonomy terms do not have an actual fieldset for path settings.
// Merge in the defaults.
$form['path'] += array(
'#type' => 'fieldset',
'#title' => t('URL path settings'),
'#collapsible' => TRUE,
'#collapsed' => empty($form['path']['alias']),
'#group' => 'additional_settings',
'#attributes' => array(
'class' => array('path-form'),
),
'#access' => user_access('create url aliases') || user_access('administer url aliases'),
'#weight' => 30,
'#tree' => TRUE,
'#element_validate' => array('path_form_element_validate'),
);
}
$pattern = pathauto_pattern_load_by_entity($entity_type, $bundle, $langcode);
if (empty($pattern)) {
return;
}
if (!isset($entity->path['pathauto'])) {
if (!empty($id)) {
module_load_include('inc', 'pathauto');
$uri = entity_uri($entity_type, $entity);
$path = drupal_get_path_alias($uri['path'], $langcode);
$pathauto_alias = pathauto_create_alias($entity_type, 'return', $uri['path'], array($entity_type => $entity), $bundle, $langcode);
$entity->path['pathauto'] = ($path != $uri['path'] && $path == $pathauto_alias);
}
else {
$entity->path['pathauto'] = TRUE;
}
}
// Add JavaScript that will disable the path textfield when the automatic
// alias checkbox is checked.
$form['path']['alias']['#states']['!enabled']['input[name="path[pathauto]"]'] = array('checked' => TRUE);
// Override path.module's vertical tabs summary.
$form['path']['#attached']['js'] = array(
'vertical-tabs' => drupal_get_path('module', 'pathauto') . '/pathauto.js'
);
$form['path']['pathauto'] = array(
'#type' => 'checkbox',
'#title' => t('Generate automatic URL alias'),
'#default_value' => $entity->path['pathauto'],
'#description' => t('Uncheck this to create a custom alias below.'),
'#weight' => -1,
);
// Add a shortcut link to configure URL alias patterns.
if (drupal_valid_path('admin/config/search/path/patterns')) {
$form['path']['pathauto']['#description'] .= ' ' . l(t('Configure URL alias patterns.'), 'admin/config/search/path/patterns');
}
if ($entity->path['pathauto'] && !empty($entity->old_alias) && empty($entity->path['alias'])) {
$form['path']['alias']['#default_value'] = $entity->old_alias;
$entity->path['alias'] = $entity->old_alias;
}
// For Pathauto to remember the old alias and prevent the Path module from
// deleting it when Pathauto wants to preserve it.
if (!empty($entity->path['alias'])) {
$form['path']['old_alias'] = array(
'#type' => 'value',
'#value' => $entity->path['alias'],
);
}
}
/**
* Implements hook_entity_presave().
*/
function pathauto_entity_presave($entity, $type) {
// About to be saved (before insert/update)
if (!empty($entity->path['pathauto']) && isset($entity->path['old_alias'])
&& $entity->path['alias'] == '' && $entity->path['old_alias'] != '') {
/**
* There was an old alias, but when pathauto_perform_alias was checked
* the javascript disabled the textbox which led to an empty value being
* submitted. Restoring the old path-value here prevents the Path module
* from deleting any old alias before Pathauto gets control.
*/
$entity->path['alias'] = $entity->path['old_alias'];
}
// Help prevent errors with progromatically creating entities by defining
// path['alias'] as an empty string.
// @see http://drupal.org/node/1328180
// @see http://drupal.org/node/1576552
if (isset($entity->path['pathauto']) && !isset($entity->path['alias'])) {
$entity->path['alias'] = '';
}
}
/**
* Implements hook_action_info().
*/
function pathauto_action_info() {
$info['pathauto_node_update_action'] = array(
'type' => 'node',
'label' => t('Update node alias'),
'configurable' => FALSE,
);
$info['pathauto_taxonomy_term_update_action'] = array(
'type' => 'taxonomy_term',
'label' => t('Update taxonomy term alias'),
'configurable' => FALSE,
);
$info['pathauto_user_update_action'] = array(
'type' => 'user',
'label' => t('Update user alias'),
'configurable' => FALSE,
);
return $info;
}
/**
* Returns the language code of the given entity.
*
* Backward compatibility layer to ensure that installations running an older
* version of core where entity_language() is not avilable do not break.
*
* @param string $entity_type
* An entity type.
* @param object $entity
* An entity object.
* @param bool $check_language_property
* A boolean if TRUE, will attempt to fetch the language code from
* $entity->language if the entity_language() function failed or does not
* exist. Default is TRUE.
*/
function pathauto_entity_language($entity_type, $entity, $check_language_property = TRUE) {
$langcode = NULL;
if (function_exists('entity_language')) {
$langcode = entity_language($entity_type, $entity);
}
elseif ($check_language_property && !empty($entity->language)) {
$langcode = $entity->language;
}
return !empty($langcode) ? $langcode : LANGUAGE_NONE;
}
if (!function_exists('path_field_extra_fields')) {
/**
* Implements hook_field_extra_fields() on behalf of path.module.
*
* Add support for the 'URL path settings' to be re-ordered by the user on the
* 'Manage Fields' tab of content types and vocabularies.
*/
function path_field_extra_fields() {
$info = array();
foreach (node_type_get_types() as $node_type) {
if (!isset($info['node'][$node_type->type]['form']['path'])) {
$info['node'][$node_type->type]['form']['path'] = array(
'label' => t('URL path settings'),
'description' => t('Path module form elements'),
'weight' => 30,
);
}
}
if (module_exists('taxonomy')) {
$vocabularies = taxonomy_get_vocabularies();
foreach ($vocabularies as $vocabulary) {
if (!isset($info['taxonomy_term'][$vocabulary->machine_name]['form']['path'])) {
$info['taxonomy_term'][$vocabulary->machine_name]['form']['path'] = array(
'label' => t('URL path settings'),
'description' => t('Path module form elements'),
'weight' => 30,
);
}
}
}
return $info;
}
}
/**
* @name pathauto_node Pathauto integration for the core node module.
* @{
*/
/**
* Implements hook_node_insert().
*/
function pathauto_node_insert($node) {
// @todo Remove the next line when http://drupal.org/node/1025870 is fixed.
unset($node->uri);
pathauto_node_update_alias($node, 'insert');
}
/**
* Implements hook_node_update().
*/
function pathauto_node_update($node) {
pathauto_node_update_alias($node, 'update');
}
/**
* Implements hook_node_delete().
*/
function pathauto_node_delete($node) {
pathauto_entity_path_delete_all('node', $node, "node/{$node->nid}");
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*
* Add the Pathauto settings to the node form.
*/
function pathauto_form_node_form_alter(&$form, &$form_state) {
$node = $form_state['node'];
$langcode = pathauto_entity_language('node', $node);
pathauto_field_attach_form('node', $node, $form, $form_state, $langcode);
}
/**
* Implements hook_node_operations().
*/
function pathauto_node_operations() {
$operations['pathauto_update_alias'] = array(
'label' => t('Update URL alias'),
'callback' => 'pathauto_node_update_alias_multiple',
'callback arguments' => array('bulkupdate', array('message' => TRUE)),
);
return $operations;
}
/**
* Update the URL aliases for an individual node.
*
* @param $node
* A node object.
* @param $op
* Operation being performed on the node ('insert', 'update' or 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_node_update_alias(stdClass $node, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the node.
if (isset($node->path['pathauto']) && empty($node->path['pathauto'])) {
return;
}
$options += array('language' => pathauto_entity_language('node', $node));
// Skip processing if the node has no pattern.
if (!pathauto_pattern_load_by_entity('node', $node->type, $options['language'])) {
return;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('node', $node);
pathauto_create_alias('node', $op, $uri['path'], array('node' => $node), $node->type, $options['language']);
}
/**
* Update the URL aliases for multiple nodes.
*
* @param $nids
* An array of node IDs.
* @param $op
* Operation being performed on the nodes ('insert', 'update' or
* 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_node_update_alias_multiple(array $nids, $op, array $options = array()) {
$options += array('message' => FALSE);
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
pathauto_node_update_alias($node, $op, $options);
}
if (!empty($options['message'])) {
drupal_set_message(format_plural(count($nids), 'Updated URL alias for 1 node.', 'Updated URL aliases for @count nodes.'));
}
}
/**
* Update action wrapper for pathauto_node_update_alias().
*/
function pathauto_node_update_action($node, $context = array()) {
pathauto_node_update_alias($node, 'bulkupdate', array('message' => TRUE));
}
/**
* @} End of "name pathauto_node".
*/
/**
* @name pathauto_taxonomy Pathauto integration for the core taxonomy module.
* @{
*/
/**
* Implements hook_taxonomy_term_insert().
*/
function pathauto_taxonomy_term_insert($term) {
pathauto_taxonomy_term_update_alias($term, 'insert');
}
/**
* Implements hook_taxonomy_term_update().
*/
function pathauto_taxonomy_term_update($term) {
pathauto_taxonomy_term_update_alias($term, 'update', array('alias children' => TRUE));
}
/**
* Implements hook_taxonomy_term_delete().
*/
function pathauto_taxonomy_term_delete($term) {
pathauto_entity_path_delete_all('taxonomy_term', $term, "taxonomy/term/{$term->tid}");
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Add the Pathauto settings to the taxonomy term form.
*/
function pathauto_form_taxonomy_form_term_alter(&$form, $form_state) {
$term = $form_state['term'];
$langcode = pathauto_entity_language('taxonomy_term', $term);
pathauto_field_attach_form('taxonomy_term', $term, $form, $form_state, $langcode);
}
/**
* Update the URL aliases for an individual taxonomy term.
*
* @param $term
* A taxonomy term object.
* @param $op
* Operation being performed on the term ('insert', 'update' or 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_taxonomy_term_update_alias(stdClass $term, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the term.
if (isset($term->path['pathauto']) && empty($term->path['pathauto'])) {
return;
}
$module = 'taxonomy_term';
if ($term->vid == variable_get('forum_nav_vocabulary', '')) {
if (module_exists('forum')) {
$module = 'forum';
}
else {
return;
}
}
// Check that the term has its bundle, which is the vocabulary's machine name.
if (!isset($term->vocabulary_machine_name)) {
$vocabulary = taxonomy_vocabulary_load($term->vid);
$term->vocabulary_machine_name = $vocabulary->machine_name;
}
$options += array(
'alias children' => FALSE,
'language' => pathauto_entity_language('taxonomy_term', $term),
);
// Skip processing if the term has no pattern.
if (!pathauto_pattern_load_by_entity($module, $term->vocabulary_machine_name)) {
return;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('taxonomy_term', $term);
pathauto_create_alias($module, $op, $uri['path'], array('term' => $term), $term->vocabulary_machine_name, $options['language']);
if (!empty($options['alias children'])) {
// For all children generate new aliases.
$options['alias children'] = FALSE;
unset($options['language']);
foreach (taxonomy_get_tree($term->vid, $term->tid) as $subterm) {
pathauto_taxonomy_term_update_alias($subterm, $op, $options);
}
}
}
/**
* Update the URL aliases for multiple taxonomy terms.
*
* @param $tids
* An array of term IDs.
* @param $op
* Operation being performed on the nodes ('insert', 'update' or
* 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_taxonomy_term_update_alias_multiple(array $tids, $op, array $options = array()) {
$options += array('message' => FALSE);
$terms = taxonomy_term_load_multiple($tids);
foreach ($terms as $term) {
pathauto_taxonomy_term_update_alias($term, $op, $options);
}
if (!empty($options['message'])) {
drupal_set_message(format_plural(count($tids), 'Updated URL alias for 1 term.', 'Updated URL aliases for @count terms.'));
}
}
/**
* Update action wrapper for pathauto_taxonomy_term_update_alias().
*/
function pathauto_taxonomy_term_update_action($term, $context = array()) {
pathauto_taxonomy_term_update_alias($term, 'bulkupdate', array('message' => TRUE));
}
/**
* @} End of "name pathauto_taxonomy".
*/
/**
* @name pathauto_user Pathauto integration for the core user and blog modules.
* @{
*/
/**
* Implements hook_user_insert().
*/
function pathauto_user_insert(&$edit, $account, $category) {
pathauto_user_update_alias($account, 'insert');
}
/**
* Implements hook_user_update().
*/
function pathauto_user_update(&$edit, $account, $category) {
pathauto_user_update_alias($account, 'update');
}
/**
* Implements hook_user_delete().
*/
function pathauto_user_delete($account) {
pathauto_entity_path_delete_all('user', $account, "user/{$account->uid}");
pathauto_path_delete_all("blog/{$account->uid}");
}
/**
* Implements hook_user_operations().
*/
function pathauto_user_operations() {
$operations['pathauto_update_alias'] = array(
'label' => t('Update URL alias'),
'callback' => 'pathauto_user_update_alias_multiple',
'callback arguments' => array('bulkupdate', array('message' => TRUE)),
);
return $operations;
}
/**
* Update the URL aliases for an individual user account.
*
* @param $account
* A user account object.
* @param $op
* Operation being performed on the account ('insert', 'update' or
* 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_user_update_alias(stdClass $account, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the account.
if (isset($account->path['pathauto']) && empty($account->path['pathauto'])) {
return;
}
$options += array(
'alias blog' => module_exists('blog'),
// $user->language is not the user entity language, thus we need to skip
// the property fallback check.
'language' => pathauto_entity_language('user', $account, FALSE),
);
// Skip processing if the account has no pattern.
if (!pathauto_pattern_load_by_entity('user', '', $options['language'])) {
return;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('user', $account);
pathauto_create_alias('user', $op, $uri['path'], array('user' => $account), NULL, $options['language']);
// Because blogs are also associated with users, also generate the blog paths.
if (!empty($options['alias blog'])) {
pathauto_blog_update_alias($account, $op, $options);
}
}
/**
* Update the URL aliases for multiple user accounts.
*
* @param $uids
* An array of user account IDs.
* @param $op
* Operation being performed on the accounts ('insert', 'update' or
* 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_user_update_alias_multiple(array $uids, $op, array $options = array()) {
$options += array('message' => FALSE);
$accounts = user_load_multiple($uids);
foreach ($accounts as $account) {
pathauto_user_update_alias($account, $op, $options);
}
if (!empty($options['message'])) {
drupal_set_message(format_plural(count($uids), 'Updated URL alias for 1 user account.', 'Updated URL aliases for @count user accounts.'));
}
}
/**
* Update action wrapper for pathauto_user_update_alias().
*/
function pathauto_user_update_action($account, $context = array()) {
pathauto_user_update_alias($account, 'bulkupdate', array('message' => TRUE));
}
/**
* Update the blog URL aliases for an individual user account.
*
* @param $account
* A user account object.
* @param $op
* Operation being performed on the blog ('insert', 'update' or
* 'bulkupdate').
* @param $options
* An optional array of additional options.
*/
function pathauto_blog_update_alias(stdClass $account, $op, array $options = array()) {
// Skip processing if the blog has no pattern.
if (!pathauto_pattern_load_by_entity('blog')) {
return;
}
$options += array(
'language' => LANGUAGE_NONE,
);
module_load_include('inc', 'pathauto');
if (node_access('create', 'blog', $account)) {
pathauto_create_alias('blog', $op, "blog/{$account->uid}", array('user' => $account), NULL, $options['language']);
}
else {
pathauto_path_delete_all("blog/{$account->uid}");
}
}
/**
* @} End of "name pathauto_user".
*/

View File

@@ -0,0 +1,392 @@
<?php
/**
* @file
* Pathauto integration for core modules.
*
* @ingroup pathauto
*/
/**
* Implements hook_path_alias_types().
*
* Used primarily by the bulk delete form.
*/
function pathauto_path_alias_types() {
$objects['user/'] = t('Users');
$objects['node/'] = t('Content');
if (module_exists('blog')) {
$objects['blog/'] = t('User blogs');
}
if (module_exists('taxonomy')) {
$objects['taxonomy/term/'] = t('Taxonomy terms');
}
if (module_exists('forum')) {
$objects['forum/'] = t('Forums');
}
return $objects;
}
/**
* Implements hook_pathauto().
*
* This function is empty so that the other core module implementations can be
* defined in this file. This is because in pathauto_module_implements_alter()
* we add pathauto to be included first. The module system then peforms a
* check on any subsequent run if this function still exists. If this does not
* exist, than this file will not get included and the core implementations
* will never get run.
*
* @see pathauto_module_implements_alter().
*/
function pathauto_pathauto() {
// Empty hook; see the above comment.
}
/**
* Implements hook_pathauto().
*/
function node_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'node';
$settings['token_type'] = 'node';
$settings['groupheader'] = t('Content paths');
$settings['patterndescr'] = t('Default path pattern (applies to all content types with blank patterns below)');
$settings['patterndefault'] = 'content/[node:title]';
$settings['batch_update_callback'] = 'node_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$languages = array();
if (module_exists('locale')) {
$languages = array(LANGUAGE_NONE => t('language neutral')) + locale_language_list('name');
}
foreach (node_type_get_names() as $node_type => $node_name) {
if (count($languages) && variable_get('language_content_type_' . $node_type, 0)) {
$settings['patternitems'][$node_type] = t('Default path pattern for @node_type (applies to all @node_type content types with blank patterns below)', array('@node_type' => $node_name));
foreach ($languages as $lang_code => $lang_name) {
$settings['patternitems'][$node_type . '_' . $lang_code] = t('Pattern for all @language @node_type paths', array('@node_type' => $node_name, '@language' => $lang_name));
}
}
else {
$settings['patternitems'][$node_type] = t('Pattern for all @node_type paths', array('@node_type' => $node_name));
}
}
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for nodes.
*/
function node_pathauto_bulk_update_batch_process(&$context) {
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
$query = db_select('node', 'n');
$query->leftJoin('url_alias', 'ua', "CONCAT('node/', n.nid) = ua.source");
$query->addField('n', 'nid');
$query->isNull('ua.source');
$query->condition('n.nid', $context['sandbox']['current'], '>');
$query->orderBy('n.nid');
$query->addTag('pathauto_bulk_update');
$query->addMetaData('entity', 'node');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no nodes to update, the stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$nids = $query->execute()->fetchCol();
pathauto_node_update_alias_multiple($nids, 'bulkupdate');
$context['sandbox']['count'] += count($nids);
$context['sandbox']['current'] = max($nids);
$context['message'] = t('Updated alias for node @nid.', array('@nid' => end($nids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}
/**
* Implements hook_pathauto().
*/
function taxonomy_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'taxonomy_term';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Taxonomy term paths');
$settings['patterndescr'] = t('Default path pattern (applies to all vocabularies with blank patterns below)');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'taxonomy_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$vocabularies = taxonomy_get_vocabularies();
if (count($vocabularies)) {
$settings['patternitems'] = array();
foreach ($vocabularies as $vid => $vocabulary) {
if ($vid == variable_get('forum_nav_vocabulary', '')) {
// Skip the forum vocabulary.
continue;
}
$settings['patternitems'][$vocabulary->machine_name] = t('Pattern for all %vocab-name paths', array('%vocab-name' => $vocabulary->name));
}
}
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for taxonomy terms.
*/
function taxonomy_pathauto_bulk_update_batch_process(&$context) {
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
$query = db_select('taxonomy_term_data', 'td');
$query->leftJoin('url_alias', 'ua', "CONCAT('taxonomy/term/', td.tid) = ua.source");
$query->addField('td', 'tid');
$query->isNull('ua.source');
$query->condition('td.tid', $context['sandbox']['current'], '>');
// Exclude the forums terms.
if ($forum_vid = variable_get('forum_nav_vocabulary', '')) {
$query->condition('td.vid', $forum_vid, '<>');
}
$query->orderBy('td.tid');
$query->addTag('pathauto_bulk_update');
$query->addMetaData('entity', 'taxonomy_term');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no nodes to update, the stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$tids = $query->execute()->fetchCol();
pathauto_taxonomy_term_update_alias_multiple($tids, 'bulkupdate');
$context['sandbox']['count'] += count($tids);
$context['sandbox']['current'] = max($tids);
$context['message'] = t('Updated alias for term @tid.', array('@tid' => end($tids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}
/**
* Implements hook_pathauto() for forum module.
*/
function forum_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'forum';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Forum paths');
$settings['patterndescr'] = t('Pattern for forums and forum containers');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'forum_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for forums.
*/
function forum_pathauto_bulk_update_batch_process(&$context) {
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
$query = db_select('taxonomy_term_data', 'td');
$query->leftJoin('url_alias', 'ua', "CONCAT('forum/', td.tid) = ua.source");
$query->addField('td', 'tid');
$query->isNull('ua.source');
$query->condition('td.tid', $context['sandbox']['current'], '>');
$query->condition('td.vid', variable_get('forum_nav_vocabulary', ''));
$query->orderBy('td.tid');
$query->addTag('pathauto_bulk_update');
$query->addMetaData('entity', 'taxonomy_term');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no nodes to update, the stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$tids = $query->execute()->fetchCol();
pathauto_taxonomy_term_update_alias_multiple($tids, 'bulkupdate');
$context['sandbox']['count'] += count($tids);
$context['sandbox']['current'] = max($tids);
$context['message'] = t('Updated alias for forum @tid.', array('@tid' => end($tids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}
/**
* Implements hook_pathauto().
*/
function user_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'user';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('User paths');
$settings['patterndescr'] = t('Pattern for user account page paths');
$settings['patterndefault'] = 'users/[user:name]';
$settings['batch_update_callback'] = 'user_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for users.
*/
function user_pathauto_bulk_update_batch_process(&$context) {
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
$query = db_select('users', 'u');
$query->leftJoin('url_alias', 'ua', "CONCAT('user/', u.uid) = ua.source");
$query->addField('u', 'uid');
$query->isNull('ua.source');
$query->condition('u.uid', $context['sandbox']['current'], '>');
$query->orderBy('u.uid');
$query->addTag('pathauto_bulk_update');
$query->addMetaData('entity', 'user');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no nodes to update, the stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$uids = $query->execute()->fetchCol();
pathauto_user_update_alias_multiple($uids, 'bulkupdate', array('alias blog' => FALSE));
$context['sandbox']['count'] += count($uids);
$context['sandbox']['current'] = max($uids);
$context['message'] = t('Updated alias for user @uid.', array('@uid' => end($uids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}
/**
* Implements hook_pathauto().
*/
function blog_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'blog';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('Blog paths');
$settings['patterndescr'] = t('Pattern for blog page paths');
$settings['patterndefault'] = 'blogs/[user:name]';
$settings['batch_update_callback'] = 'blog_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for blogs.
*/
function blog_pathauto_bulk_update_batch_process(&$context) {
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['count'] = 0;
$context['sandbox']['current'] = 0;
}
$query = db_select('users', 'u');
$query->leftJoin('url_alias', 'ua', "CONCAT('blog/', u.uid) = ua.source");
$query->addField('u', 'uid');
$query->isNull('ua.source');
$query->condition('u.uid', $context['sandbox']['current'], '>');
$query->orderBy('u.uid');
$query->addTag('pathauto_bulk_update');
$query->addMetaData('entity', 'user');
// Get the total amount of items to process.
if (!isset($context['sandbox']['total'])) {
$context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
// If there are no nodes to update, the stop immediately.
if (!$context['sandbox']['total']) {
$context['finished'] = 1;
return;
}
}
$query->range(0, 25);
$uids = $query->execute()->fetchCol();
$accounts = user_load_multiple($uids);
foreach ($accounts as $account) {
pathauto_blog_update_alias($account, 'bulkupdate');
}
$context['sandbox']['count'] += count($uids);
$context['sandbox']['current'] = max($uids);
$context['message'] = t('Updated alias for blog user @uid.', array('@uid' => end($uids)));
if ($context['sandbox']['count'] != $context['sandbox']['total']) {
$context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
}
}

View File

@@ -0,0 +1,793 @@
<?php
/**
* @file
* Functionality tests for Pathauto.
*
* @ingroup pathauto
*/
/**
* Helper test class with some added functions for testing.
*/
class PathautoTestHelper extends DrupalWebTestCase {
function setUp(array $modules = array()) {
$modules[] = 'path';
$modules[] = 'token';
$modules[] = 'pathauto';
$modules[] = 'taxonomy';
parent::setUp($modules);
}
function assertToken($type, $object, $token, $expected) {
$tokens = token_generate($type, array($token => $token), array($type => $object));
$tokens += array($token => '');
$this->assertIdentical($tokens[$token], $expected, t("Token value for [@type:@token] was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $tokens[$token], '@expected' => $expected)));
}
function saveAlias($source, $alias, $language = LANGUAGE_NONE) {
$alias = array(
'source' => $source,
'alias' => $alias,
'language' => $language,
);
path_save($alias);
return $alias;
}
function saveEntityAlias($entity_type, $entity, $alias, $language = LANGUAGE_NONE) {
$uri = entity_uri($entity_type, $entity);
return $this->saveAlias($uri['path'], $alias, $language);
}
function assertEntityAlias($entity_type, $entity, $expected_alias, $language = LANGUAGE_NONE) {
$uri = entity_uri($entity_type, $entity);
$this->assertAlias($uri['path'], $expected_alias, $language);
}
function assertEntityAliasExists($entity_type, $entity) {
$uri = entity_uri($entity_type, $entity);
return $this->assertAliasExists(array('source' => $uri['path']));
}
function assertNoEntityAlias($entity_type, $entity, $language = LANGUAGE_NONE) {
$uri = entity_uri($entity_type, $entity);
$this->assertEntityAlias($entity_type, $entity, $uri['path'], $language);
}
function assertNoEntityAliasExists($entity_type, $entity) {
$uri = entity_uri($entity_type, $entity);
$this->assertNoAliasExists(array('source' => $uri['path']));
}
function assertAlias($source, $expected_alias, $language = LANGUAGE_NONE) {
drupal_clear_path_cache($source);
$alias = drupal_get_path_alias($source, $language);
$this->assertIdentical($alias, $expected_alias, t("Alias for %source with language '@language' was %actual, expected %expected.", array('%source' => $source, '%actual' => $alias, '%expected' => $expected_alias, '@language' => $language)));
}
function assertAliasExists($conditions) {
$path = path_load($conditions);
$this->assertTrue($path, t('Alias with conditions @conditions found.', array('@conditions' => var_export($conditions, TRUE))));
return $path;
}
function assertNoAliasExists($conditions) {
$alias = path_load($conditions);
$this->assertFalse($alias, t('Alias with conditions @conditions not found.', array('@conditions' => var_export($conditions, TRUE))));
}
function deleteAllAliases() {
db_delete('url_alias')->execute();
drupal_clear_path_cache();
}
function addVocabulary(array $vocabulary = array()) {
$name = drupal_strtolower($this->randomName(5));
$vocabulary += array(
'name' => $name,
'machine_name' => $name,
'nodes' => array('article' => 'article'),
);
$vocabulary = (object) $vocabulary;
taxonomy_vocabulary_save($vocabulary);
return $vocabulary;
}
function addTerm(stdClass $vocabulary, array $term = array()) {
$term += array(
'name' => drupal_strtolower($this->randomName(5)),
'vocabulary_machine_name' => $vocabulary->machine_name,
'vid' => $vocabulary->vid,
);
$term = (object) $term;
taxonomy_term_save($term);
return $term;
}
function assertEntityPattern($entity_type, $bundle, $language = LANGUAGE_NONE, $expected) {
drupal_static_reset('pathauto_pattern_load_by_entity');
$this->refreshVariables();
$pattern = pathauto_pattern_load_by_entity($entity_type, $bundle, $language);
$this->assertIdentical($expected, $pattern);
}
function drupalGetTermByName($name, $reset = FALSE) {
$terms = entity_load('taxonomy_term', array(), array('name' => $name), $reset);
return !empty($terms) ? reset($terms) : FALSE;
}
}
/**
* Unit tests for Pathauto functions.
*/
class PathautoUnitTestCase extends PathautoTestHelper {
public static function getInfo() {
return array(
'name' => 'Pathauto unit tests',
'description' => 'Unit tests for Pathauto functions.',
'group' => 'Pathauto',
'dependencies' => array('token'),
);
}
function setUp(array $modules = array()) {
parent::setUp($modules);
module_load_include('inc', 'pathauto');
}
/**
* Test _pathauto_get_schema_alias_maxlength().
*/
function testGetSchemaAliasMaxLength() {
$this->assertIdentical(_pathauto_get_schema_alias_maxlength(), 255);
}
/**
* Test pathauto_pattern_load_by_entity().
*/
function testPatternLoadByEntity() {
variable_set('pathauto_node_story_en_pattern', ' story/en/[node:title] ');
variable_set('pathauto_node_story_pattern', 'story/[node:title]');
variable_set('pathauto_node_pattern', 'content/[node:title]');
variable_set('pathauto_user_pattern', 'users/[user:name]');
$tests = array(
array('entity' => 'node', 'bundle' => 'story', 'language' => 'fr', 'expected' => 'story/[node:title]'),
array('entity' => 'node', 'bundle' => 'story', 'language' => 'en', 'expected' => 'story/en/[node:title]'),
array('entity' => 'node', 'bundle' => 'story', 'language' => LANGUAGE_NONE, 'expected' => 'story/[node:title]'),
array('entity' => 'node', 'bundle' => 'page', 'language' => 'en', 'expected' => 'content/[node:title]'),
array('entity' => 'user', 'bundle' => 'user', 'language' => LANGUAGE_NONE, 'expected' => 'users/[user:name]'),
array('entity' => 'invalid-entity', 'bundle' => '', 'language' => LANGUAGE_NONE, 'expected' => ''),
);
foreach ($tests as $test) {
$actual = pathauto_pattern_load_by_entity($test['entity'], $test['bundle'], $test['language']);
$this->assertIdentical($actual, $test['expected'], t("pathauto_pattern_load_by_entity('@entity', '@bundle', '@language') returned '@actual', expected '@expected'", array('@entity' => $test['entity'], '@bundle' => $test['bundle'], '@language' => $test['language'], '@actual' => $actual, '@expected' => $test['expected'])));
}
}
/**
* Test pathauto_cleanstring().
*/
function testCleanString() {
$tests = array();
variable_set('pathauto_ignore_words', ', in, is,that, the , this, with, ');
variable_set('pathauto_max_component_length', 35);
// Test the 'ignored words' removal.
$tests['this'] = 'this';
$tests['this with that'] = 'this-with-that';
$tests['this thing with that thing'] = 'thing-thing';
// Test length truncation and duplicate separator removal.
$tests[' - Pathauto is the greatest - module ever in Drupal history - '] = 'pathauto-greatest-module-ever';
// Test that HTML tags are removed.
$tests['This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.'] = 'text-has-html-tags';
$tests[check_plain('This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.')] = 'text-has-html-tags';
foreach ($tests as $input => $expected) {
$output = pathauto_cleanstring($input);
$this->assertEqual($output, $expected, t("pathauto_cleanstring('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output)));
}
}
/**
* Test pathauto_path_delete_multiple().
*/
function testPathDeleteMultiple() {
$this->saveAlias('node/1', 'node-1-alias');
$this->saveAlias('node/1/view', 'node-1-alias/view');
$this->saveAlias('node/1', 'node-1-alias-en', 'en');
$this->saveAlias('node/1', 'node-1-alias-fr', 'fr');
$this->saveAlias('node/2', 'node-2-alias');
pathauto_path_delete_all('node/1');
$this->assertNoAliasExists(array('source' => "node/1"));
$this->assertNoAliasExists(array('source' => "node/1/view"));
$this->assertAliasExists(array('source' => "node/2"));
}
/**
* Test the different update actions in pathauto_create_alias().
*/
function testUpdateActions() {
// Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'insert'.
variable_set('pathauto_update_action', PATHAUTO_UPDATE_ACTION_NO_NEW);
$node = $this->drupalCreateNode(array('title' => 'First title'));
$this->assertEntityAlias('node', $node, 'content/first-title');
// Default action is PATHAUTO_UPDATE_ACTION_DELETE.
variable_set('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE);
$node->title = 'Second title';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/second-title');
$this->assertNoAliasExists(array('alias' => 'content/first-title'));
// Test PATHAUTO_UPDATE_ACTION_LEAVE
variable_set('pathauto_update_action', PATHAUTO_UPDATE_ACTION_LEAVE);
$node->title = 'Third title';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/third-title');
$this->assertAliasExists(array('source' => "node/{$node->nid}", 'alias' => 'content/second-title'));
variable_set('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE);
$node->title = 'Fourth title';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/fourth-title');
$this->assertNoAliasExists(array('alias' => 'content/third-title'));
// The older second alias is not deleted yet.
$older_path = $this->assertAliasExists(array('source' => "node/{$node->nid}", 'alias' => 'content/second-title'));
path_delete($older_path);
variable_set('pathauto_update_action', PATHAUTO_UPDATE_ACTION_NO_NEW);
$node->title = 'Fifth title';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/fourth-title');
$this->assertNoAliasExists(array('alias' => 'content/fith-title'));
// Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'update'.
$this->deleteAllAliases();
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/fifth-title');
// Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'bulkupdate'.
$this->deleteAllAliases();
$node->title = 'Sixth title';
pathauto_node_update_alias($node, 'bulkupdate');
$this->assertEntityAlias('node', $node, 'content/sixth-title');
}
/**
* Test that pathauto_create_alias() will not create an alias for a pattern
* that does not get any tokens replaced.
*/
function testNoTokensNoAlias() {
$node = $this->drupalCreateNode(array('title' => ''));
$this->assertNoEntityAliasExists('node', $node);
$node->title = 'hello';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/hello');
}
/**
* Test the handling of path vs non-path tokens in pathauto_clean_token_values().
*/
function testPathTokens() {
variable_set('pathauto_taxonomy_term_pattern', '[term:parent:url:path]/[term:name]');
$vocab = $this->addVocabulary();
$term1 = $this->addTerm($vocab, array('name' => 'Parent term'));
$this->assertEntityAlias('taxonomy_term', $term1, 'parent-term');
$term2 = $this->addTerm($vocab, array('name' => 'Child term', 'parent' => $term1->tid));
$this->assertEntityAlias('taxonomy_term', $term2, 'parent-term/child-term');
$this->saveEntityAlias('taxonomy_term', $term1, 'My Crazy/Alias/');
pathauto_taxonomy_term_update($term2);
$this->assertEntityAlias('taxonomy_term', $term2, 'My Crazy/Alias/child-term');
}
function testEntityBundleRenamingDeleting() {
// Create a vocabulary and test that it's pattern variable works.
$vocab = $this->addVocabulary(array('machine_name' => 'old_name'));
variable_set('pathauto_taxonomy_term_pattern', 'base');
variable_set("pathauto_taxonomy_term_old_name_pattern", 'bundle');
$this->assertEntityPattern('taxonomy_term', 'old_name', LANGUAGE_NONE, 'bundle');
// Rename the vocabulary's machine name, which should cause its pattern
// variable to also be renamed.
$vocab->machine_name = 'new_name';
taxonomy_vocabulary_save($vocab);
$this->assertEntityPattern('taxonomy_term', 'new_name', LANGUAGE_NONE, 'bundle');
$this->assertEntityPattern('taxonomy_term', 'old_name', LANGUAGE_NONE, 'base');
// Delete the vocabulary, which should cause its pattern variable to also
// be deleted.
taxonomy_vocabulary_delete($vocab->vid);
$this->assertEntityPattern('taxonomy_term', 'new_name', LANGUAGE_NONE, 'base');
}
function testNoExistingPathAliases() {
variable_set('pathauto_node_page_pattern', '[node:title]');
variable_set('pathauto_punctuation_period', PATHAUTO_PUNCTUATION_DO_NOTHING);
// Check that Pathauto does not create an alias of '/admin'.
$node = $this->drupalCreateNode(array('title' => 'Admin', 'type' => 'page'));
$this->assertNoEntityAlias('node', $node);
// Check that Pathauto does not create an alias of '/modules'.
$node->title = 'Modules';
node_save($node);
$this->assertNoEntityAlias('node', $node);
// Check that Pathauto does not create an alias of '/index.php'.
$node->title = 'index.php';
node_save($node);
$this->assertNoEntityAlias('node', $node);
// Check that a safe value gets an automatic alias. This is also a control
// to ensure the above tests work properly.
$node->title = 'Safe value';
node_save($node);
$this->assertEntityAlias('node', $node, 'safe-value');
}
}
/**
* Helper test class with some added functions for testing.
*/
class PathautoFunctionalTestHelper extends PathautoTestHelper {
protected $admin_user;
function setUp(array $modules = array()) {
parent::setUp($modules);
// Set pathauto settings we assume to be as-is in this test.
variable_set('pathauto_node_page_pattern', 'content/[node:title]');
// Allow other modules to add additional permissions for the admin user.
$permissions = array(
'administer pathauto',
'administer url aliases',
'create url aliases',
'administer nodes',
'bypass node access',
'access content overview',
'administer taxonomy',
'administer users',
);
$args = func_get_args();
if (isset($args[1]) && is_array($args[1])) {
$permissions = array_merge($permissions, $args[1]);
}
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
}
}
/**
* Test basic pathauto functionality.
*/
class PathautoFunctionalTestCase extends PathautoFunctionalTestHelper {
public static function getInfo() {
return array(
'name' => 'Pathauto basic tests',
'description' => 'Test basic pathauto functionality.',
'group' => 'Pathauto',
'dependencies' => array('token'),
);
}
/**
* Basic functional testing of Pathauto.
*/
function testNodeEditing() {
// Delete the default node pattern. Only the page content type will have a pattern.
variable_del('pathauto_node_pattern');
// Ensure that the Pathauto checkbox is checked by default on the node add form.
$this->drupalGet('node/add/page');
$this->assertFieldChecked('edit-path-pathauto');
// Create node for testing by previewing and saving the node form.
$title = ' Testing: node title [';
$automatic_alias = 'content/testing-node-title';
$this->drupalPost(NULL, array('title' => $title), 'Preview');
$this->drupalPost(NULL, array(), 'Save');
$node = $this->drupalGetNodeByTitle($title);
// Look for alias generated in the form.
$this->drupalGet("node/{$node->nid}/edit");
$this->assertFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', $automatic_alias, 'Generated alias visible in the path alias field.');
// Check whether the alias actually works.
$this->drupalGet($automatic_alias);
$this->assertText($title, 'Node accessible through automatic alias.');
// Manually set the node's alias.
$manual_alias = 'content/' . $node->nid;
$edit = array(
'path[pathauto]' => FALSE,
'path[alias]' => $manual_alias,
);
$this->drupalPost("node/{$node->nid}/edit", $edit, t('Save'));
$this->assertText("Basic page $title has been updated.");
// Check that the automatic alias checkbox is now unchecked by default.
$this->drupalGet("node/{$node->nid}/edit");
$this->assertNoFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', $manual_alias);
// Submit the node form with the default values.
$this->drupalPost(NULL, array(), t('Save'));
$this->assertText("Basic page $title has been updated.");
// Test that the old (automatic) alias has been deleted and only accessible
// through the new (manual) alias.
$this->drupalGet($automatic_alias);
$this->assertResponse(404, 'Node not accessible through automatic alias.');
$this->drupalGet($manual_alias);
$this->assertText($title, 'Node accessible through manual alias.');
// Now attempt to create a node that has no pattern (article content type).
// The Pathauto checkbox should not exist.
$this->drupalGet('node/add/article');
$this->assertNoFieldById('edit-path-pathauto');
$this->assertFieldByName('path[alias]', '');
$edit = array();
$edit['title'] = 'My test article';
$this->drupalPost(NULL, $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($edit['title']);
// Pathauto checkbox should still not exist.
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertNoFieldById('edit-path-pathauto');
$this->assertFieldByName('path[alias]', '');
$this->assertNoEntityAlias('node', $node);
}
/**
* Test node operations.
*/
function testNodeOperations() {
$node1 = $this->drupalCreateNode(array('title' => 'node1'));
$node2 = $this->drupalCreateNode(array('title' => 'node2'));
// Delete all current URL aliases.
$this->deleteAllAliases();
$edit = array(
'operation' => 'pathauto_update_alias',
"nodes[{$node1->nid}]" => TRUE,
);
$this->drupalPost('admin/content', $edit, t('Update'));
$this->assertText('Updated URL alias for 1 node.');
$this->assertEntityAlias('node', $node1, 'content/' . $node1->title);
$this->assertEntityAlias('node', $node2, 'node/' . $node2->nid);
}
/**
* Basic functional testing of Pathauto with taxonomy terms.
*/
function testTermEditing() {
$this->drupalGet('admin/structure');
$this->drupalGet('admin/structure/taxonomy');
// Create term for testing.
$name = ' Testing: term name [ ';
$automatic_alias = 'tags/testing-term-name';
$this->drupalPost('admin/structure/taxonomy/tags/add', array('name' => $name), 'Save');
$name = trim($name);
$this->assertText("Created new term $name.");
$term = $this->drupalGetTermByName($name);
// Look for alias generated in the form.
$this->drupalGet("taxonomy/term/{$term->tid}/edit");
$this->assertFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', $automatic_alias, 'Generated alias visible in the path alias field.');
// Check whether the alias actually works.
$this->drupalGet($automatic_alias);
$this->assertText($name, 'Term accessible through automatic alias.');
// Manually set the term's alias.
$manual_alias = 'tags/' . $term->tid;
$edit = array(
'path[pathauto]' => FALSE,
'path[alias]' => $manual_alias,
);
$this->drupalPost("taxonomy/term/{$term->tid}/edit", $edit, t('Save'));
$this->assertText("Updated term $name.");
// Check that the automatic alias checkbox is now unchecked by default.
$this->drupalGet("taxonomy/term/{$term->tid}/edit");
$this->assertNoFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', $manual_alias);
// Submit the term form with the default values.
$this->drupalPost(NULL, array(), t('Save'));
$this->assertText("Updated term $name.");
// Test that the old (automatic) alias has been deleted and only accessible
// through the new (manual) alias.
$this->drupalGet($automatic_alias);
$this->assertResponse(404, 'Term not accessible through automatic alias.');
$this->drupalGet($manual_alias);
$this->assertText($name, 'Term accessible through manual alias.');
}
/**
* Basic functional testing of Pathauto with users.
*/
function testUserEditing() {
// There should be no Pathauto checkbox on user forms.
$this->drupalGet('user/' . $this->admin_user->uid . '/edit');
$this->assertNoFieldById('edit-path-pathauto');
}
/**
* Test user operations.
*/
function testUserOperations() {
$account = $this->drupalCreateUser();
// Delete all current URL aliases.
$this->deleteAllAliases();
$edit = array(
'operation' => 'pathauto_update_alias',
"accounts[{$account->uid}]" => TRUE,
);
$this->drupalPost('admin/people', $edit, t('Update'));
$this->assertText('Updated URL alias for 1 user account.');
$this->assertEntityAlias('user', $account, 'users/' . drupal_strtolower($account->name));
$this->assertEntityAlias('user', $this->admin_user, 'user/' . $this->admin_user->uid);
}
function testSettingsValidation() {
$edit = array();
$edit['pathauto_max_length'] = 'abc';
$edit['pathauto_max_component_length'] = 'abc';
$this->drupalPost('admin/config/search/path/settings', $edit, 'Save configuration');
$this->assertText('The field Maximum alias length is not a valid number.');
$this->assertText('The field Maximum component length is not a valid number.');
$this->assertNoText('The configuration options have been saved.');
$edit['pathauto_max_length'] = '0';
$edit['pathauto_max_component_length'] = '0';
$this->drupalPost('admin/config/search/path/settings', $edit, 'Save configuration');
$this->assertText('The field Maximum alias length cannot be less than 1.');
$this->assertText('The field Maximum component length cannot be less than 1.');
$this->assertNoText('The configuration options have been saved.');
$edit['pathauto_max_length'] = '999';
$edit['pathauto_max_component_length'] = '999';
$this->drupalPost('admin/config/search/path/settings', $edit, 'Save configuration');
$this->assertText('The field Maximum alias length cannot be greater than 255.');
$this->assertText('The field Maximum component length cannot be greater than 255.');
$this->assertNoText('The configuration options have been saved.');
$edit['pathauto_max_length'] = '50';
$edit['pathauto_max_component_length'] = '50';
$this->drupalPost('admin/config/search/path/settings', $edit, 'Save configuration');
$this->assertText('The configuration options have been saved.');
}
function testPatternsValidation() {
$edit = array();
$edit['pathauto_node_pattern'] = '[node:title]/[user:name]/[term:name]';
$edit['pathauto_node_page_pattern'] = 'page';
$this->drupalPost('admin/config/search/path/patterns', $edit, 'Save configuration');
$this->assertText('The Default path pattern (applies to all content types with blank patterns below) is using the following invalid tokens: [user:name], [term:name].');
$this->assertText('The Pattern for all Basic page paths cannot contain fewer than one token.');
$this->assertNoText('The configuration options have been saved.');
$edit['pathauto_node_pattern'] = '[node:title]';
$edit['pathauto_node_page_pattern'] = 'page/[node:title]';
$edit['pathauto_node_article_pattern'] = '';
$this->drupalPost('admin/config/search/path/patterns', $edit, 'Save configuration');
$this->assertText('The configuration options have been saved.');
}
/**
* Test programmatic entity creation for aliases.
*/
function testProgrammaticEntityCreation() {
$node = $this->drupalCreateNode(array('title' => 'Test node', 'path' => array('pathauto' => TRUE)));
$this->assertEntityAlias('node', $node, 'content/test-node');
$vocabulary = $this->addVocabulary(array('name' => 'Tags'));
$term = $this->addTerm($vocabulary, array('name' => 'Test term', 'path' => array('pathauto' => TRUE)));
$this->assertEntityAlias('taxonomy_term', $term, 'tags/test-term');
$edit['name'] = 'Test user';
$edit['mail'] = 'test-user@example.com';
$edit['pass'] = user_password();
$edit['path'] = array('pathauto' => TRUE);
$edit['status'] = 1;
$account = user_save(drupal_anonymous_user(), $edit);
$this->assertEntityAlias('user', $account, 'users/test-user');
}
}
class PathautoLocaleTestCase extends PathautoFunctionalTestHelper {
public static function getInfo() {
return array(
'name' => 'Pathauto localization tests',
'description' => 'Test pathauto functionality with localization and translation.',
'group' => 'Pathauto',
'dependencies' => array('token'),
);
}
function setUp(array $modules = array()) {
$modules[] = 'locale';
$modules[] = 'translation';
parent::setUp($modules, array('administer languages'));
// Add predefined French language and reset the locale cache.
require_once DRUPAL_ROOT . '/includes/locale.inc';
locale_add_language('fr', NULL, NULL, LANGUAGE_LTR, '', 'fr');
drupal_language_initialize();
}
/**
* Test that when an English node is updated, its old English alias is
* updated and its newer French alias is left intact.
*/
function testLanguageAliases() {
$node = array(
'title' => 'English node',
'language' => 'en',
'body' => array('en' => array(array())),
'path' => array(
'alias' => 'english-node',
'pathauto' => FALSE,
),
);
$node = $this->drupalCreateNode($node);
$english_alias = path_load(array('alias' => 'english-node', 'language' => 'en'));
$this->assertTrue($english_alias, 'Alias created with proper language.');
// Also save a French alias that should not be left alone, even though
// it is the newer alias.
$this->saveEntityAlias('node', $node, 'french-node', 'fr');
// Add an alias with the soon-to-be generated alias, causing the upcoming
// alias update to generate a unique alias with the '-0' suffix.
$this->saveAlias('node/invalid', 'content/english-node', LANGUAGE_NONE);
// Update the node, triggering a change in the English alias.
$node->path['pathauto'] = TRUE;
pathauto_node_update($node);
// Check that the new English alias replaced the old one.
$this->assertEntityAlias('node', $node, 'content/english-node-0', 'en');
$this->assertEntityAlias('node', $node, 'french-node', 'fr');
$this->assertAliasExists(array('pid' => $english_alias['pid'], 'alias' => 'content/english-node-0'));
}
}
/**
* Bulk update functionality tests.
*/
class PathautoBulkUpdateTestCase extends PathautoFunctionalTestHelper {
private $nodes;
public static function getInfo() {
return array(
'name' => 'Pathauto bulk updating',
'description' => 'Tests bulk updating of URL aliases.',
'group' => 'Pathauto',
'dependencies' => array('token'),
);
}
function testBulkUpdate() {
// Create some nodes.
$this->nodes = array();
for ($i = 1; $i <= 5; $i++) {
$node = $this->drupalCreateNode();
$this->nodes[$node->nid] = $node;
}
// Clear out all aliases.
$this->deleteAllAliases();
// Bulk create aliases.
$edit = array(
'update[node_pathauto_bulk_update_batch_process]' => TRUE,
'update[user_pathauto_bulk_update_batch_process]' => TRUE,
);
$this->drupalPost('admin/config/search/path/update_bulk', $edit, t('Update'));
$this->assertText('Generated 7 URL aliases.'); // 5 nodes + 2 users
// Check that aliases have actually been created.
foreach ($this->nodes as $node) {
$this->assertEntityAliasExists('node', $node);
}
$this->assertEntityAliasExists('user', $this->admin_user);
// Add a new node.
$new_node = $this->drupalCreateNode(array('path' => array('alias' => '', 'pathauto' => FALSE)));
// Run the update again which should only run against the new node.
$this->drupalPost('admin/config/search/path/update_bulk', $edit, t('Update'));
$this->assertText('Generated 1 URL alias.'); // 1 node + 0 users
$this->assertEntityAliasExists('node', $new_node);
}
}
/**
* Token functionality tests.
*/
class PathautoTokenTestCase extends PathautoFunctionalTestHelper {
public static function getInfo() {
return array(
'name' => 'Pathauto tokens',
'description' => 'Tests tokens provided by Pathauto.',
'group' => 'Pathauto',
'dependencies' => array('token'),
);
}
function testPathautoTokens() {
$array = array(
'test first arg',
'The Array / value',
);
$tokens = array(
'join-path' => 'test-first-arg/array-value',
);
$data['array'] = $array;
$replacements = $this->assertTokens('array', $data, $tokens);
// Ensure that the pathauto_clean_token_values() function does not alter
// this token value.
module_load_include('inc', 'pathauto');
pathauto_clean_token_values($replacements, $data, array());
$this->assertEqual($replacements['[array:join-path]'], 'test-first-arg/array-value');
}
/**
* Function copied from TokenTestHelper::assertTokens().
*/
function assertTokens($type, array $data, array $tokens, array $options = array()) {
$input = $this->mapTokenNames($type, array_keys($tokens));
$replacements = token_generate($type, $input, $data, $options);
foreach ($tokens as $name => $expected) {
$token = $input[$name];
if (!isset($expected)) {
$this->assertTrue(!isset($values[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
}
elseif (!isset($replacements[$token])) {
$this->fail(t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
}
elseif (!empty($options['regex'])) {
$this->assertTrue(preg_match('/^' . $expected . '$/', $replacements[$token]), t("Token value for @token was '@actual', matching regular expression pattern '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected)));
}
else {
$this->assertIdentical($replacements[$token], $expected, t("Token value for @token was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $replacements[$token], '@expected' => $expected)));
}
}
return $replacements;
}
function mapTokenNames($type, array $tokens = array()) {
$return = array();
foreach ($tokens as $token) {
$return[$token] = "[$type:$token]";
}
return $return;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* @file
* Token integration for the Pathauto module.
*/
/**
* Implements hook_token_info().
*/
function pathauto_token_info() {
$info = array();
$info['tokens']['array']['join-path'] = array(
'name' => t('Joined path'),
'description' => t('The array values each cleaned by Pathauto and then joined with the slash into a string that resembles an URL.'),
);
return $info;
}
/**
* Implements hook_tokens().
*/
function pathauto_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();
if ($type == 'array' && !empty($data['array'])) {
$array = $data['array'];
foreach ($tokens as $name => $original) {
switch ($name) {
case 'join-path':
module_load_include('inc', 'pathauto');
$values = array();
foreach (element_children($array) as $key) {
$value = is_array($array[$key]) ? render($array[$key]) : (string) $array[$key];
$value = pathauto_cleanstring($value);
$values[] = $value;
}
$replacements[$original] = implode('/', $values);
break;
}
}
}
return $replacements;
}