FINAL suepr merge step : added all modules to this super repos

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 16:46:59 +02:00
7585 changed files with 1723356 additions and 18 deletions

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,108 @@
Admin 2.x
=========
The admin module provides UI improvements to the standard Drupal admin interface. The 2.x branch focuses on the following goals:
1. Sustainability - avoid excessive overrides of code, markup, and
interface strings to ensure the module keeps the workload overhead
on the maintainers and community to a minimum.
2. Pluggable/extensible architecture - ensure that admin serves as a
starting point for other modules in contrib to implement admin
interfaces.
3. Expose Drupal's strengths and downplay its weaknesses where possible.
An honest approach to the underlying framework and architecture
of Drupal will be less confusing to the user down the road.
Admin is not an original work - many of its decisions have had direct
influences from other work in the community:
- [Administration menu](http://drupal.org/project/admin_menu)
Daniel Kudwien (sun)
- [Navigate](http://drupal.org/project/navigate)
Chris Shattuck (chrisshattuck)
- [d7ux](http://www.d7ux.org)
Mark Boulton & Leisa Reichelt
Installation
============
1. Install & enable the module.
2. Admin makes a permission available that allows only properly
permissioned users to make use of the admin toolbar. Users with the
'use admin toolbar' permission will be able to use the toolbar.
3. You can configure the layout, position, and enabled tools for the
admin toolbar on `admin/config/user-interface/admin`, or by navigating
to `Administration > Configuration > User interface > Administration tools`
Implementing your own Admin "plugins"
=====================================
Admin's "plugins" are simply Drupal blocks. In order to expose one of your
module's blocks as one suitable for use in the admin toolbar you can set the `admin` key in your `hook_block()` to `TRUE`. Note that users can add any blocks to the admin toolbar if they wish at `admin/settings/admin`, though not all will work well in the context of the admin toolbar.
/**
* Implementation of hook_block().
*/
function my_module_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks = array();
$blocks['example'] = array(
'info' => t('Example block'),
'admin' => TRUE
);
return $blocks;
}
}
Theming your block and other tips
=================================
Your block should provide general rules for either of the admin toolbar
layouts (horizontal or vertical). You can specify CSS rules using the
following selectors:
#admin-toolbar.horizontal {}
#admin-toolbar.vertical {}
Admin provides fairly decent defaults for the following Drupal core
theme functions:
- `theme('item_list')`
- menu output (e.g. `menu_tree_output()`).
- most form elements (with the exception of fieldsets)
- admin panes (see below)
Admin provides an additional FormAPI element type `admin_panes`. Admin
panes allow you to fit multiple elements of content into a togglable
interface. The panes will automatically adjust to the layout to the toolbar
and display as either vertical tabs (horizontal layout) or accordian boxes
(vertical layout).
Here is an example of using admin panes in a form API array:
$form['panes'] = array(
'#tree' => FALSE,
'#type' => 'admin_panes',
'foo' => array(
'#title' => t('Pane 1'),
...
),
'bar' => array(
'#title' => t('Pane 2'),
...
),
);
Note that each child element must have a #title attribute to be labeled
properly.
Contributors
============
- yhahn (Young Hahn)
- ajashton (AJ Ashton)

View File

@@ -0,0 +1,204 @@
<?php
/**
* System settings form for admin toolbar.
*/
function admin_settings_form($form, &$form_state) {
$form['admin_toolbar'] = array(
'#tree' => TRUE,
'#theme' => 'admin_settings_form',
);
$form['admin_toolbar']['layout'] = array(
'#type' => 'select',
'#title' => t('Layout'),
'#description' => t('Choose a layout for the admin toolbar. Vertical works well with large, wide screens. Horizontal works well on screens with limited real estate.'),
'#options' => array(
'horizontal' => t('Horizontal'),
'vertical' => t('Vertical'),
),
'#default_value' => admin_get_settings('layout'),
);
$form['admin_toolbar']['position'] = array(
'#type' => 'select',
'#title' => t('Position'),
'#description' => t('Choose a position for the admin toolbar that will not collide with other elements in your current theme.'),
'#options' => array(
'ne' => t('Top right'),
'nw' => t('Top left'),
'se' => t('Bottom right'),
'sw' => t('Bottom left'),
),
'#default_value' => admin_get_settings('position'),
);
$form['admin_toolbar']['behavior'] = array(
'#type' => 'select',
'#title' => t('State on new pages'),
'#description' => t('Choose toolbar behavior on new page loads.'),
'#options' => array(
'df' => t('Remember from previous page'),
'ah' => t('Collapsed'),
),
'#default_value' => admin_get_settings('behavior'),
);
$block_info = array();
foreach (module_implements('block_info') as $module) {
$module_blocks = module_invoke($module, 'block_info');
if ($module_blocks) {
foreach ($module_blocks as $delta => $info) {
$block_info["{$module}-{$delta}"] = $info;
}
}
}
// Store block info for use in form processing.
$form['#block_info'] = $block_info;
// Get default block options.
$options = array();
$enabled = array_filter(admin_get_settings('blocks')) + admin_get_default_blocks(TRUE);
foreach ($block_info as $bid => $info) {
if (!empty($enabled[$bid])) {
$options[$bid] = $info['info'];
}
}
asort($options);
$form['admin_toolbar']['blocks'] = array(
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => drupal_map_assoc(array_keys(array_filter(admin_get_settings('blocks')))),
);
// Grab an array of human-readable module names. It hurts that we need to do this.
$result = db_query("SELECT name,type,info FROM {system} WHERE type = :type AND status = :status", array(':type' => 'module', ':status' => 1));
$modules = array();
while ($row = $result->fetchObject()) {
$info = unserialize($row->info);
$modules[$row->name] = isset($info['name']) ? $info['name'] : $row->name;
}
$custom_options = array();
foreach (array_diff_key($block_info, $options) as $bid => $info) {
$block_parts = (explode('-', $bid));
$module = array_shift($block_parts);
$module = isset($modules[$module]) ? $modules[$module] : $module;
$custom_options[$module][$bid] = $info['info'];
}
$custom_options = $custom_options + array(-1 => '<' . t('Choose a block') . '>');
ksort($custom_options);
$form['admin_toolbar']['custom'] = array(
'#type' => 'select',
'#options' => $custom_options,
'#default_value' => -1,
'#element_validate' => array('admin_settings_form_custom_validate'),
'#description' => t('Enable other blocks for use in the admin toolbar.'),
);
$form['admin_toolbar']['add'] = array(
'#type' => 'submit',
'#value' => t('Add block'),
);
$form = system_settings_form($form);
// Add a submit handler for expanding block information.
array_unshift($form['#submit'], 'admin_settings_form_submit');
return $form;
}
/**
* Submit handler for admin_settings_form().
*
* Retrieves cache type for each block and saves that instead of `1` for each
* enabled block.
*/
function admin_settings_form_submit($form, &$form_state) {
if (isset($form['#block_info'], $form_state['values']['admin_toolbar']['blocks'])) {
$blocks = array();
foreach (array_keys(array_filter($form_state['values']['admin_toolbar']['blocks'])) as $bid) {
$blocks[$bid] = isset($form['#block_info'][$bid]['cache']) ? $form['#block_info'][$bid]['cache'] : DRUPAL_NO_CACHE;
}
$form_state['values']['admin_toolbar']['blocks'] = $blocks;
}
}
/**
* Element validator for custom block adder. Moves values within
* $form_state['values'] and prevents additional variables from being saved.
*/
function admin_settings_form_custom_validate($element, &$form_state) {
if ($form_state['values']['admin_toolbar']['custom'] != -1) {
$bid = $form_state['values']['admin_toolbar']['custom'];
$form_state['values']['admin_toolbar']['blocks'][$bid] = $bid;
}
unset($form_state['values']['admin_toolbar']['custom']);
unset($form_state['values']['admin_toolbar']['add']);
}
/**
* Theme function for the admin settings form.
*/
function theme_admin_settings_form($variables) {
$form = $variables['element'];
$rows = array();
// Admin blocks
$header = array(array(
'data' => t('Administrative blocks'),
'colspan' => 2,
));
foreach (array_keys(admin_get_default_blocks(TRUE)) as $block) {
$rows[] = array(array(
'data' => drupal_render($form['blocks'][$block]),
'colspan' => 2,
));
}
// "Custom" blocks
$rows[] = array(array(
'data' => t('Other blocks'),
'colspan' => 2,
'header' => TRUE,
));
foreach (element_children($form['blocks']) as $block) {
if (empty($form['blocks'][$block]['#printed'])) {
$rows[] = array(array(
'data' => drupal_render($form['blocks'][$block]),
'colspan' => 2,
));
}
}
$rows[] = array(drupal_render($form['custom']), drupal_render($form['add']));
$form['blocks']['#children'] = theme('table', array('header' => $header, 'rows' => $rows));
return drupal_render_children($form);
}
/**
* Rebuild form.
*/
function admin_settings_rebuild($form_state) {
$form = array();
$form['rebuild'] = array(
'#type' => 'fieldset',
'#title' => t('Wipe and rebuild'),
'#description' => t('If the administrative menu is not working properly, you may need to wipe and rebuild it from scratch. <strong>This option will reset any customizations made to your administrative menu items.</strong>'),
);
$form['rebuild']['submit'] = array(
'#type' => 'submit',
'#value' => t('Rebuild'),
'#submit' => array('admin_settings_rebuild_submit'),
);
return $form;
}
/**
* Wipe and rebuild the admin menu.
*/
function admin_settings_rebuild_submit($form, &$form_state) {
db_delete('menu_links')
->condition('menu_name', 'management')
->execute();
menu_rebuild();
if (module_exists('block')) {
cache_clear_all('admin', 'cache_block', TRUE);
}
}

View File

@@ -0,0 +1,21 @@
name = Admin
description = UI helpers for Drupal admins and managers.
package = Administration
core = 7.x
configure = admin/config/user-interface/admin
files[] = admin.admin.inc
files[] = admin.install
files[] = admin.module
files[] = includes/admin.devel.inc
files[] = includes/admin.theme.inc
files[] = theme/admin-panes.tpl.php
files[] = theme/admin-toolbar.tpl.php
files[] = theme/theme.inc
; Information added by drupal.org packaging script on 2011-09-30
version = "7.x-2.x-dev"
core = "7.x"
project = "admin"
datestamp = "1317340920"

View File

@@ -0,0 +1,25 @@
<?php
/**
* @file
* Install, update and uninstall functions for the admin module.
*/
/**
* Implements hook_uninstall().
*/
function admin_uninstall() {
variable_del('admin_toolbar');
}
/**
* Implements hook_enable().
*/
function admin_enable() {
// Weight admin to come after other modules -- in particular, admin_theme().
db_update('system')
->fields(array('weight' => 1))
->condition('name', 'admin')
->condition('type', 'module')
->execute();
}

View File

@@ -0,0 +1,450 @@
<?php
/**
* Implements hook_block_info().
*/
function admin_block_info() {
$blocks = array();
$blocks['create'] = array(
'info' => t('Create content'),
'cache' => DRUPAL_NO_CACHE,
'admin' => TRUE,
);
$blocks['theme'] = array(
'info' => t('Theme switcher'),
'cache' => DRUPAL_CACHE_PER_ROLE,
'admin' => TRUE,
);
$blocks['account'] = array(
'info' => t('My Account'),
'cache' => DRUPAL_NO_CACHE,
'admin' => TRUE,
);
if (module_exists('menu')) {
$blocks['menu'] = array(
'info' => t('Administration menu'),
'cache' => DRUPAL_CACHE_PER_ROLE,
'admin' => TRUE,
);
}
if (module_exists('devel')) {
$blocks['devel'] = array(
'info' => t('Devel'),
'cache' => DRUPAL_NO_CACHE,
'admin' => TRUE,
);
}
return $blocks;
}
/**
* Implements hook_block_view().
*/
function admin_block_view($delta) {
switch ($delta) {
case 'create':
$item = menu_get_item('node/add');
$links = system_admin_menu_block($item);
if (!empty($links)) {
$menu = array();
foreach ($links as $key => $link) {
$menu[$key] = array(
'link' => $link + array('in_active_trail' => FALSE),
'below' => FALSE,
);
}
return array(
'subject' => !empty($item['title']) ? $item['title'] : t('Create content'),
'content' => menu_tree_output($menu),
);
}
break;
case 'theme':
if (user_access('select different theme')) {
module_load_include('inc', 'admin', 'includes/admin.theme');
return admin_block_theme();
}
return NULL;
case 'account':
return admin_account_block();
case 'menu':
$item = menu_get_item('admin');
if ($item && $item['access']) {
$tree = menu_tree_all_data('management');
foreach ($tree as $key => $branch) {
if ($branch['link']['link_path'] !== 'admin') {
unset($tree[$key]);
}
}
return array(
'subject' => !empty($item['title']) ? $item['title'] : t('Administer'),
'content' => menu_tree_output($tree),
);
}
break;
case 'devel':
module_load_include('inc', 'admin', 'includes/admin.devel');
return admin_block_devel();
}
}
/**
* Implements hook_element_info().
*/
function admin_element_info() {
return array(
'admin_panes' => array(
'#value' => '',
'#theme_wrappers' => array('admin_panes'),
),
);
}
/**
* Implements hook_menu().
*/
function admin_menu() {
$items = array();
$items['admin/config/user-interface/admin'] =
$items['admin/config/user-interface/admin/settings'] = array(
'title' => 'Administration tools',
'description' => 'Settings for site administration tools.',
'page callback' => 'drupal_get_form',
'page arguments' => array('admin_settings_form'),
'access callback' => 'user_access',
'access arguments' => array('administer site configuration'),
'type' => MENU_NORMAL_ITEM,
'file' => 'admin.admin.inc',
'module' => 'admin',
);
$items['admin/config/user-interface/admin/settings']['title'] = 'Settings';
$items['admin/config/user-interface/admin/settings']['type'] = MENU_DEFAULT_LOCAL_TASK;
$items['admin/config/user-interface/admin/rebuild'] = array(
'title' => 'Rebuild',
'description' => 'Wipe and rebuild the administrative menu.',
'page callback' => 'drupal_get_form',
'page arguments' => array('admin_settings_rebuild'),
'access callback' => 'user_access',
'access arguments' => array('administer site configuration'),
'type' => MENU_LOCAL_TASK,
'file' => 'admin.admin.inc',
'module' => 'admin',
'weight' => 10,
);
return $items;
}
/**
* Implements hook_menu_alter().
*/
function admin_menu_alter(&$items) {
foreach ($items as $path => $item) {
// Smarter access callback for poorly checked landing pages
if (!empty($item['access arguments']) && !empty($item['page callback']) && $item['access arguments'] === array('access administration pages') && in_array($item['page callback'], array('system_admin_menu_block_page', 'system_settings_overview'))) {
$items[$path]['access callback'] = 'admin_landing_page_access';
$items[$path]['access arguments'] = array($path);
}
}
}
/**
* Menu access callback for admin landing pages.
*
* For a given landing page, grant access if the current user has access
* to any of its child menu items.
*/
function admin_landing_page_access($path) {
static $paths;
if (!isset($paths[$path])) {
$paths[$path] = FALSE;
// Retrieve menu item but without menu_get_item()
$item = db_select('menu_links')
->fields('menu_links')
->condition('module', 'system')
->condition('router_path', $path)
->execute()
->fetchAssoc();
if ($item) {
$query = db_select('menu_links', 'ml');
$query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
$query->fields('ml');
$query->fields('m', array_diff(drupal_schema_fields_sql('menu_router'), array('weight')));
$query->condition('ml.plid', $item['mlid']);
$result = $query->execute();
while ($item = $result->fetchAssoc()) {
_menu_link_translate($item);
if ($item['access']) {
$paths[$path] = TRUE;
break;
}
}
}
}
return $paths[$path];
}
/**
* Implements hook_permission().
*/
function admin_permission() {
return array(
'use admin toolbar' => array(
'title' => t('use admin toolbar'),
'description' => t('Use the admin toolbar'),
),
'select different theme' => array(
'title' => t('select different theme'),
'description' => t("Select different theme for the current user's session."),
),
);
}
/**
* Implements hook_theme().
*/
function admin_theme($cache, $type, $theme, $path) {
$path = drupal_get_path('module', 'admin');
$items['admin_tab'] = array(
'variables' => array(
'tab' => array(),
'class' => '',
),
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_toolbar'] = array(
'variables' => array(
'blocks' => array(),
'position' => 'ne',
'layout' => 'horizontal',
'behavior' => 'df',
),
'template' => 'admin-toolbar',
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_drilldown_menu_tree_output'] = array(
'variables' => array('menu' => array()),
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_drilldown_menu_tree'] = array(
'variables' => array('menu' => array()),
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_drilldown_menu_item'] = array(
'variables' => array(
'link' => NULL,
'has_children' => NULL,
'menu' => '',
'in_active_trail' => FALSE,
'extra_class' => NULL,
),
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_drilldown_menu_item_link'] = array(
'variables' => array('item' => array()),
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_panes'] = array(
'render element' => 'element',
'template' => 'admin-panes',
'path' => $path . '/theme',
'file' => 'theme.inc',
);
$items['admin_settings_form'] = array(
'render element' => 'element',
'path' => $path,
'file' => 'admin.admin.inc',
);
return $items;
}
/**
* Get variable settings or fallback to defaults.
*/
function admin_get_settings($key = NULL) {
static $settings;
if (!isset($settings)) {
// Try to gather what information we can from the cookie.
// Note that this information should not be trusted in any
// way for affecting *anything* but trivial changes to the site.
$cookie = array();
if (isset($_REQUEST['DrupalAdminToolbar'])) {
parse_str($_REQUEST['DrupalAdminToolbar'], $cookie);
}
$settings = variable_get('admin_toolbar', array()) + array(
'layout' => 'vertical',
'position' => 'nw',
'behavior' => 'df',
'blocks' => admin_get_default_blocks(),
'expanded' => isset($cookie['expanded']) ? check_plain($cookie['expanded']) : 0,
'active_tab' => isset($cookie['activeTab']) ? check_plain($cookie['activeTab']) : 0,
);
// Ensure that if behavior is set to autohide the toolbar is collapsed.
if ($settings['behavior'] === 'ah') {
$settings['expanded'] = 0;
}
}
if (isset($key)) {
return isset($settings[$key]) ? $settings[$key] : FALSE;
}
return $settings;
}
/**
* Get all blocks that have declared themselves visible in the admin toolbar by default.
*/
function admin_get_default_blocks($reset = FALSE) {
static $defaults;
if (!isset($defaults) || $reset) {
$cache = cache_get('admin_default_blocks');
if ($cache && !$reset) {
$defaults = $cache->data;
}
else {
$defaults = array();
foreach (module_implements('block_info') as $module) {
$module_blocks = module_invoke($module, 'block_info');
if ($module_blocks) {
foreach ($module_blocks as $delta => $info) {
if (isset($info['admin'])) {
$defaults["{$module}-{$delta}"] = isset($info['cache']) ? $info['cache'] : DRUPAL_NO_CACHE;
}
}
}
}
cache_set('admin_default_blocks', $defaults);
}
}
return $defaults;
}
/**
* Get blocks enabled for the admin toolbar.
*/
function admin_get_admin_blocks() {
$blocks = array();
if (user_access('use admin toolbar') && $enabled_blocks = admin_get_settings('blocks')) {
module_load_include('module', 'block', 'block');
foreach ($enabled_blocks as $bid => $cache) {
$block = NULL;
$split = explode('-', $bid, 2);
if (count($split) === 2) {
list($module, $delta) = $split;
$block = new stdClass();
$block->module = $module;
$block->delta = $delta;
$block->bid = $bid;
$block->title = NULL;
$block->cache = is_numeric($cache) ? $cache : DRUPAL_NO_CACHE;
$block->region = 'admin_toolbar'; // Fake the block region.
$blocks[$bid] = $block;
}
}
$blocks = _block_render_blocks($blocks);
}
return $blocks;
}
/**
* Preprocessor that runs *before* template_preprocess_page().
*/
function admin_page_build(&$page) {
if (user_access('use admin toolbar') && $trail = menu_get_active_trail()) {
do {
$last = array_pop($trail);
} while (count($trail) && !($last['type'] & MENU_VISIBLE_IN_TREE));
if ($last) {
drupal_add_js(array('activePath' => url($last['href'])), array('type' => 'setting', 'scope' => JS_DEFAULT));
}
}
if (!admin_suppress(FALSE) && $blocks = admin_get_admin_blocks()) {
$path = drupal_get_path('module', 'admin');
drupal_add_js("misc/jquery.cookie.js");
drupal_add_js("{$path}/includes/jquery.drilldown.js");
drupal_add_js("{$path}/includes/admin.toolbar.js");
drupal_add_js("{$path}/includes/admin.menu.js");
drupal_add_css("{$path}/includes/admin.toolbar.base.css");
drupal_add_css("{$path}/includes/admin.toolbar.css");
drupal_add_css("{$path}/includes/admin.menu.css");
$position = admin_get_settings('position');
$layout = admin_get_settings('layout');
$behavior = admin_get_settings('behavior');
$class = admin_get_settings('expanded') ? 'admin-expanded' : '';
$page['page_bottom']['admin_toolbar'] = array(
'#type' => 'markup',
'#markup' => theme('admin_toolbar', array('blocks' => $blocks, 'position' => $position, 'layout' => $layout, 'behavior' => $behavior)),
);
}
}
/**
* Implements hook_preprocess_html().
*/
function admin_preprocess_html(&$vars) {
if (!admin_suppress(FALSE) && $blocks = admin_get_admin_blocks()) {
$position = admin_get_settings('position');
$layout = admin_get_settings('layout');
$behavior = admin_get_settings('behavior');
$class = admin_get_settings('expanded') ? 'admin-expanded' : '';
$vars['classes_array'][] = " admin-{$position} admin-{$layout} admin-{$behavior} {$class} ";
}
}
/**
* Implements hook_suppress().
*
* Suppress display of administration toolbar.
*
* This function should be called from within another module's page callback
* preferably using module_invoke_all('suppress') when the menu should not be
* displayed. This is useful for modules that implement popup pages or other
* special pages where the menu would be distracting or break the layout.
*
* @param $set
* Defaults to TRUE. If called before hook_footer(), the menu will not be
* displayed. If FALSE is passed, the suppression state is returned.
*/
function admin_suppress($set = TRUE) {
static $suppress = FALSE;
if (!empty($set) && $suppress === FALSE) {
$suppress = TRUE;
}
return $suppress;
}
/**
* My Account block.
*/
function admin_account_block() {
$block = array(
'subject' => t('My Account'),
'content' => '',
);
global $user;
if ($user->uid > 0) {
$menu = array();
$menu[] = array(
'data' => l(t('View my account'), 'user/' . $user->uid),
'class' => array('leaf'),
);
$menu[] = array(
'data' => l(t('Edit my account'), 'user/' . $user->uid . '/edit'),
'class' => array('leaf'),
);
$menu[] = array(
'data' => l(t('Logout'), 'user/logout'),
'class' => array('leaf'),
);
$block['content'] = theme('item_list', array('items' => $menu, 'attributes' => array('class' => array('menu'))));
}
return $block;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 934 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 612 B

View File

@@ -0,0 +1,192 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="40"
height="400"
id="svg2657"
sodipodi:version="0.32"
inkscape:version="0.46"
version="1.0"
sodipodi:docname="bleeds.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape">
<defs
id="defs2659">
<linearGradient
inkscape:collect="always"
id="linearGradient3410">
<stop
style="stop-color:#ffffff;stop-opacity:1"
offset="0"
id="stop3412" />
<stop
style="stop-color:#dddddd;stop-opacity:1"
offset="1"
id="stop3414" />
</linearGradient>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient3410"
id="linearGradient2637"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.75,240,-240)"
x1="0"
y1="360"
x2="0"
y2="400" />
<linearGradient
id="linearGradient3418"
inkscape:collect="always">
<stop
id="stop3420"
offset="0"
style="stop-color:#444444;stop-opacity:1" />
<stop
id="stop3422"
offset="1"
style="stop-color:#222222;stop-opacity:1" />
</linearGradient>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient3418"
id="linearGradient3416"
gradientUnits="userSpaceOnUse"
x1="0"
y1="360"
x2="0"
y2="400"
gradientTransform="matrix(1,0,0,0.75,240,-270)" />
<linearGradient
inkscape:collect="always"
id="linearGradient3397">
<stop
style="stop-color:#222222;stop-opacity:1"
offset="0"
id="stop3400" />
<stop
style="stop-color:#111111;stop-opacity:1"
offset="1"
id="stop3402" />
</linearGradient>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient3397"
id="linearGradient3407"
x1="0"
y1="360"
x2="0"
y2="400"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1,0,0,0.75,240,100)" />
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
id="perspective2665" />
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
gridtolerance="10000"
guidetolerance="10"
objecttolerance="10"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="-33.318742"
inkscape:cy="141.59317"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false">
<inkscape:grid
type="xygrid"
id="grid2685"
visible="true"
enabled="true" />
</sodipodi:namedview>
<metadata
id="metadata2662">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<g
style="display:inline"
id="g3449"
inkscape:export-filename="/home/yh/Private/www/d6/sites/all/modules/admin/images/bleeds.png"
inkscape:export-xdpi="90"
inkscape:export-ydpi="90"
transform="matrix(0.1666667,0,0,1,-40.000016,0)">
<rect
inkscape:export-ydpi="90"
inkscape:export-xdpi="90"
inkscape:export-filename="/home/yh/d6/sites/all/modules/admin/toolbar/bleeds.png"
y="370"
x="240"
height="30"
width="240"
id="rect2624"
style="opacity:1;fill:url(#linearGradient3407);fill-opacity:1;stroke:none;stroke-width:1.7854991;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" />
<rect
inkscape:export-ydpi="90"
inkscape:export-xdpi="90"
inkscape:export-filename="/home/yh/d6/sites/all/modules/admin/toolbar/bleeds.png"
style="opacity:1;fill:#222222;fill-opacity:1;stroke:none;stroke-width:1.7854991;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect3409"
width="240"
height="1"
x="240"
y="399" />
<rect
inkscape:export-ydpi="90"
inkscape:export-xdpi="90"
inkscape:export-filename="/home/yh/d6/sites/all/modules/admin/toolbar/bleeds.png"
style="opacity:1;fill:url(#linearGradient3416);fill-opacity:1;stroke:none;stroke-width:1.7854991;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect3413"
width="240"
height="30"
x="240"
y="0" />
<rect
y="30"
x="240"
height="30"
width="240"
id="rect2635"
style="opacity:1;fill:url(#linearGradient2637);fill-opacity:1;stroke:none;stroke-width:1.7854991;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
inkscape:export-filename="/home/yh/d6/sites/all/modules/admin/toolbar/bleeds.png"
inkscape:export-xdpi="90"
inkscape:export-ydpi="90" />
<rect
y="-6.8212105e-14"
x="240"
height="1"
width="240"
id="rect2675"
style="opacity:1;fill:#555555;fill-opacity:1;stroke:none;stroke-width:1.7854991;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
inkscape:export-filename="/home/yh/d6/sites/all/modules/admin/toolbar/bleeds.png"
inkscape:export-xdpi="90"
inkscape:export-ydpi="90" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 55 KiB

View File

@@ -0,0 +1,54 @@
div.dev-query,
div.dev-timer,
div.dev-memory-usage,
div.devel-querylog { display:none; }
.devel-hide { display:none !important; }
/**
* Admin devel block ==================================================
*/
#block-admin-devel div.dev-info strong {
color:#fff;
font-weight:bold;
}
#block-admin-devel input.dev-querylog-show,
#block-admin-devel input.dev-querylog-hide { margin-top:5px; }
#block-admin-devel input.dev-querylog-hide { display:none; }
#block-admin-devel .marker {
color:#f40;
font-weight:bold;
}
/* Override menu styling */
#admin-toolbar #block-admin-devel { padding-bottom:10px; }
/**
* Query list =========================================================
*/
div.devel-querylog {
border-bottom:1px solid #181818;
background:#080808;
color:#999;
font-size:11px;
line-height:15px;
position:relative;
display:none;
}
div.devel-querylog-header {
border:0px;
font-weight:bold;
}
div.devel-querylog .marker {
color:#f40;
font-weight: bold;
}
div.devel-querylog a { color:#fff; }
div.devel-querylog-even { background:#0c0c0c; }
div.devel-querylog-odd { background:#101010; }

View File

@@ -0,0 +1,79 @@
<?php
/**
* Devel admin block.
*/
function admin_block_devel() {
if (module_exists('devel') && (user_access('access devel information') || user_access('switch users') || user_access('execute php code'))) {
drupal_add_css(drupal_get_path('module', 'admin') . '/includes/admin.devel.css');
drupal_add_js(drupal_get_path('module', 'admin') . '/includes/admin.devel.js');
return array('subject' => t('Devel'), 'content' => drupal_get_form('admin_block_devel_form'));
}
}
/**
* Devel admin block form.
*/
function admin_block_devel_form($form, $form_state) {
$panes = array();
if (user_access('access devel information')) {
$panes['performance'] = admin_devel_performance_form();
}
if (user_access('switch users')) {
$panes['switch_user'] = array(
'#title' => t('Switch user'),
'list' => array('#markup' => theme('links', array(
'links' => devel_switch_user_list(),
'attributes' => array('class' => 'links clearfix'),
))),
'user' => devel_switch_user_form(),
);
$panes['switch_user']['user']['#submit'] = array('devel_switch_user_form_submit');
}
if (user_access('execute php code')) {
$panes['execute'] = devel_execute_form() + array('#title' => t('Execute PHP'));
$panes['execute']['op']['#submit'] = array('devel_execute_form_submit');
}
if (user_access('access devel information')) {
$panes['menu'] = menu_tree_output(menu_tree_all_data('devel'));
$panes['menu']['#title'] = t('Other tools');
}
if (!empty($panes)) {
$panes['#type'] = 'admin_panes';
return array('panes' => $panes);
}
return array();
}
/**
* Performance "form". Actually renders placeholders that are populated post-exit via javascript.
*/
function admin_devel_performance_form() {
$items = array();
if (variable_get('dev_timer', 0) && !variable_get('devel_query_display', FALSE)) {
$items[] = array(
'data' => "<div class='dev-info'></div>",
'class' => array('dev-timer'),
);
}
if (variable_get('dev_mem', FALSE) && function_exists('memory_get_usage')) {
$items[] = array(
'data' => "<div class='dev-info'></div>",
'class' => array('dev-memory-usage'),
);
}
if (variable_get('devel_query_display', FALSE)) {
$show = "<input type='button' class='form-submit dev-querylog-show' value='" . t('Show querylog') . "'/>";
$hide = "<input type='button' class='form-submit dev-querylog-hide' value='" . t('Hide querylog') . "'/>";
$items[] = array(
'data' => "<div class='dev-info'></div>{$show}{$hide}",
'class' => array('dev-query'),
);
}
if ($items) {
return array(
'#title' => t('Performance'),
'#markup' => theme('item_list', array('items' => $items)),
);
}
}

View File

@@ -0,0 +1,36 @@
(function($) {
Drupal.behaviors.adminDevel = {};
Drupal.behaviors.adminDevel.attach = function(context) {
$('#block-admin-devel:not(.admin-processed)').each(function() {
var devel = $(this);
devel.addClass('admin-processed');
// Pull logged values from footer output into the block.
$('li', devel).each(function() {
var key = $(this).attr('class').split(' ')[0];
if (key && $('body > .'+key).size() > 0) {
var value = $('body > .'+key).html();
$('div.dev-info', this).html(value);
}
});
// Query list show handler.
$('input.dev-querylog-show', devel).click(function() {
$(this).hide().siblings('input.dev-querylog-hide').show();
$('body > *:not(#admin-toolbar, .region-page-bottom, .devel-querylog)').addClass('devel-hide');
$('body > .devel-querylog').show();
return false;
});
// Query list hide handler.
$('input.dev-querylog-hide').click(function() {
$(this).hide().siblings('input.dev-querylog-show').show();
$('body > *:not(#admin-toolbar, .region-page-bottom, .devel-querylog)').removeClass('devel-hide');
$('body > .devel-querylog').hide();
return false;
});
});
};
})(jQuery);

View File

@@ -0,0 +1,38 @@
/**
* Breadcrumb
*/
div#admin-toolbar div.admin-tab.admin-menu a {
background-image:url(../images/sprite-rtl.png);
background-position:0% -70px;
padding-left:20px;
padding-right:0px;
}
/**
* Tooltips
*/
div#admin-toolbar.horizontal span.menu-description {
left:auto;
right:60%;
padding-left:0;
padding-right:20px;
}
/**
* Menu
*/
#admin-toolbar ul.drilldown-active-menu li {
background-image:url(../images/sprite-rtl.png);
background-position:100% -85px;
}
#admin-toolbar ul.drilldown-active-menu li.leaf { background-position:100% -110px; }
#admin-toolbar ul.menu li a {
margin-left:0;
margin-right:25px;
}
#admin-toolbar.horizontal ul.drilldown-active-menu { float:right; }
#admin-toolbar.horizontal ul.drilldown-active-menu li { float:right; }

View File

@@ -0,0 +1,127 @@
/**
* Breadcrumb
*/
div#admin-toolbar div.admin-tab.admin-menu #admin-tab-admin-menu {
display:block;
height:20px;
overflow:hidden;
position:relative;
}
div#admin-toolbar div.admin-tab a {
background:url(../images/sprite.png) 100% -70px no-repeat;
padding-right:20px;
}
div#admin-toolbar div.admin-tab a:last-child {
background:transparent;
padding:0px;
}
/**
* Tooltips
*/
div#admin-toolbar.vertical div.admin-toolbar-menu-hover div.block-content { bottom:100px; }
div#admin-toolbar span.menu-description { display:none; }
div#admin-toolbar a.menu-hover span.menu-description {
color:#ccc;
display:block;
}
div#admin-toolbar.vertical a.menu-hover span.menu-description {
position:absolute;
overflow:hidden;
left:0px;
right:0px;
bottom:0px;
padding:0px 20px;
height:90px;
}
div#admin-toolbar.horizontal a.menu-hover span.menu-description {
position:absolute;
top:0px;
left:60%;
width:35%;
padding-left:20px;
}
/**
* Menu
*/
#admin-toolbar ul.menu,
#admin-toolbar ul.menu ul,
#admin-toolbar ul.menu li,
#admin-toolbar ul.menu li a {
list-style:none;
background:transparent;
padding:0px;
margin:0px;
border:0px;
}
/* IE7 */
*:first-child+html #admin-toolbar ul.menu,
*:first-child+html #admin-toolbar ul.menu ul,
*:first-child+html #admin-toolbar ul.menu li,
*:first-child+html #admin-toolbar ul.menu li a { overflow:hidden; }
#admin-toolbar.horizontal ul.drilldown-active-menu {
float:left;
width:60%;
}
#admin-toolbar.horizontal div.admin-pane ul.drilldown-active-menu {
float:none;
width:auto;
}
#admin-toolbar.horizontal ul.drilldown-active-menu li {
float:left;
width:49.9%;
}
#admin-toolbar ul.drilldown-active-menu li { background:url(../images/sprite.png) 0% -85px no-repeat; }
#admin-toolbar ul.menu li.leaf,
#admin-toolbar ul.drilldown-active-menu li.leaf { background:url(../images/sprite.png) 0% -110px no-repeat; }
#admin-toolbar ul.menu li a {
-moz-border-radius:5px;
-webkit-border-radius:5px;
display:block;
margin-left:25px;
height:15px;
padding:5px 10px 4px;
border-bottom:1px solid #222;
white-space:nowrap;
overflow:hidden;
}
#admin-toolbar ul.menu li a span.menu-description { white-space:normal; }
/* IE7 requires height to be explicitly set. */
#admin-toolbar ul.menu li.leaf,
#admin-toolbar ul.drilldown-active-menu li { height:25px; }
#admin-toolbar ul.menu li a.active { background:#222; }
#admin-toolbar ul.menu li a:hover {
color:#000;
background:url(../images/bleeds.png) 0px -30px repeat-x;
}
/* Drilldown generic styles */
.drilldown ul.menu li { display:none !important; }
.drilldown ul.menu li a { display:none !important; }
.drilldown ul.menu li.drilldown-active-trail { display:block !important; }
.drilldown ul.drilldown-active-menu li { display:block !important; }
.drilldown ul.drilldown-active-menu li a { display:block !important; }
.drilldown ul.drilldown-active-menu li ul { display:none !important; }
.drilldown ul.drilldown-active-menu li.expanded { cursor:pointer; }
.drilldown ul.drilldown-active-menu ul.menu li a { display:none !important; }

View File

@@ -0,0 +1,65 @@
(function($) {
Drupal.behaviors.adminToolbarMenu = {};
Drupal.behaviors.adminToolbarMenu.attach = function(context) {
if (jQuery().drilldown) {
$('#admin-toolbar div.admin-block:has(ul.menu):not(.admin-toolbar-menu)')
.addClass('admin-toolbar-menu')
.each(function() {
var menu = $(this);
var trail = '#admin-toolbar div.admin-tab.' + $(this).attr('id').split('block-')[1] + ' span';
var rootTitle = $(trail).text();
if ($('a:has(span.menu-description)', menu).size() > 0) {
menu.addClass('admin-toolbar-menu-hover');
$('a:has(span.menu-description)', menu).hover(
function() {
$('<a></a>')
.attr('class', $(this).attr('class'))
.addClass('menu-hover')
.addClass('overlay-exclude')
.append($('span.menu-description', this).clone())
.appendTo(menu)
.show();
},
function() {
$(menu)
.children('a.menu-hover')
.remove();
}
);
}
// Replace the standard trail click handler with one that only
// adjusts menu if the admin tab is active. Otherwise, switch
// to that admin tab.
menu.bind('refresh.drilldown', function() {
$(trail + ' a').unbind('click').click(function() {
if ($(this).parents('div.admin-tab').is('.admin-tab-active')) {
var settings = {'activeLink': $(this).data('original'), 'trail': trail};
// If the clicked link does not reference the current
// active menu, set it to be active.
if (settings.activeLink.siblings('ul.drilldown-active-menu').size() === 0) {
menu.drilldown('setActive', settings);
return false;
}
// Otherwise, pass-through and allow the link to be clicked.
return menu.drilldown('goTo', settings);
}
$(this).parents('div.admin-tab').click();
return false;
});
});
// Init drilldown plugin.
menu.drilldown('init', {
activePath: Drupal.settings.activePath,
trail: trail,
rootTitle: rootTitle
});
});
}
};
})(jQuery);

View File

@@ -0,0 +1,38 @@
<?php
/**
* Theme switcher admin block.
*/
function admin_block_theme() {
$themes = list_themes();
if (count($themes) > 2) {
return array(
'subject' => t('Switch theme'),
'content' => drupal_get_form('admin_block_theme_form', $themes),
);
}
}
/**
* Devel admin block form.
*/
function admin_block_theme_form($form, $form_state, $themes) {
$options = array();
foreach ($themes as $theme) {
if ($theme->status) {
$options[$theme->name] = isset($theme->info['name']) ? check_plain($theme->info['name']) : $theme->name;
}
}
$form = array();
$form['theme_default'] = array(
'#type' => 'radios',
'#options' => $options,
'#default_value' => variable_get('theme_default', 'garland'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save configuration'),
);
$form['#submit'] = array('system_settings_form_submit');
return $form;
}

View File

@@ -0,0 +1,3 @@
/**
* @TODO: Update RTL support.
*/

View File

@@ -0,0 +1,35 @@
div#admin-toolbar.horizontal div.admin-tab {
float:right;
margin-left:5px;
margin-right:0;
}
div#admin-toolbar div.admin-tab-active {
-moz-border-radius:5px 0px 0px 5px;
}
/**
* Horizontal layout.
*/
#admin-toolbar.horizontal div.admin-panes {
padding-left:0;
padding-right:25%;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs {
left:auto;
right:0px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a {
-moz-border-radius:3px 3px 0px 0px;
-webkit-border-top-right-radius:3px;
-webkit-border-bottom-right-radius:3px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a.admin-pane-active {
border-width:1px 1px 1px 0px;
margin-left:-1px;
margin-right:0;
}

View File

@@ -0,0 +1,472 @@
/**
* Admin toolbar CSS resets ===========================================
*/
/* Text */
#admin-toolbar,
#admin-toolbar h1,
#admin-toolbar h2,
#admin-toolbar h3,
#admin-toolbar h4,
#admin-toolbar h5,
#admin-toolbar h6,
#admin-toolbar p,
#admin-toolbar blockquote,
#admin-toolbar pre,
#admin-toolbar a,
#admin-toolbar abbr,
#admin-toolbar acronym,
#admin-toolbar address,
#admin-toolbar big,
#admin-toolbar cite,
#admin-toolbar code,
#admin-toolbar del,
#admin-toolbar dfn,
#admin-toolbar em,
#admin-toolbar font,
#admin-toolbar img,
#admin-toolbar ins,
#admin-toolbar kbd,
#admin-toolbar q,
#admin-toolbar s,
#admin-toolbar samp,
#admin-toolbar small,
#admin-toolbar strike,
#admin-toolbar strong,
#admin-toolbar sub,
#admin-toolbar sup,
#admin-toolbar tt,
#admin-toolbar var,
#admin-toolbar b,
#admin-toolbar u,
#admin-toolbar i,
#admin-toolbar center,
/* Common classes */
#admin-toolbar .buttons,
/* Lists */
#admin-toolbar dl,
#admin-toolbar dt,
#admin-toolbar dd,
#admin-toolbar ol,
#admin-toolbar ul,
#admin-toolbar li,
/* Forms */
#admin-toolbar fieldset,
#admin-toolbar form,
#admin-toolbar input,
#admin-toolbar select,
#admin-toolbar textarea,
#admin-toolbar label,
#admin-toolbar legend,
/* Tables */
#admin-toolbar table,
#admin-toolbar caption,
#admin-toolbar tbody,
#admin-toolbar tfoot,
#admin-toolbar thead,
#admin-toolbar tr,
#admin-toolbar th,
#admin-toolbar td,
/* Drupal: system.css */
#admin-toolbar tr.even,
#admin-toolbar tr.odd,
#admin-toolbar tr.drag,
#admin-toolbar tbody,
#admin-toolbar tbody th,
#admin-toolbar thead th,
#admin-toolbar .breadcrumb,
#admin-toolbar .error,
#admin-toolbar div.error,
#admin-toolbar tr.error,
#admin-toolbar .warning,
#admin-toolbar div.warning,
#admin-toolbar tr.warning,
#admin-toolbar .ok,
#admin-toolbar div.ok,
#admin-toolbar tr.ok,
#admin-toolbar .item-list,
#admin-toolbar .item-list .icon,
#admin-toolbar .item-list .title,
#admin-toolbar .item-list ul,
#admin-toolbar .item-list ul li,
#admin-toolbar ol.task-list li.active,
#admin-toolbar .form-item,
#admin-toolbar tr.odd .form-item,
#admin-toolbar tr.even .form-item,
#admin-toolbar tr.merge-down,
#admin-toolbar tr.merge-up,
#admin-toolbar .form-item .description,
#admin-toolbar .form-item label,
#admin-toolbar .form-item label.option,
#admin-toolbar .form-checkboxes,
#admin-toolbar .form-radios,
#admin-toolbar .form-checkboxes .form-item,
#admin-toolbar .form-radios .form-item,
#admin-toolbar .marker,
#admin-toolbar .form-required,
#admin-toolbar .more-link,
#admin-toolbar .more-help-link,
#admin-toolbar .item-list .pager,
#admin-toolbar .item-list .pager li,
#admin-toolbar .pager-current,
#admin-toolbar .tips,
#admin-toolbar html.js fieldset.collapsible legend a,
#admin-toolbar html.js fieldset.collapsed legend a,
#admin-toolbar .resizable-textarea {
margin:0px;
padding:0px;
border:0px;
outline:0px;
font-size:100%;
vertical-align:baseline;
background:transparent;
line-height:inherit;
position:static;
-moz-box-shadow:none;
-webkit-box-shadow:none;
-moz-border-radius:none;
-webkit-border-radius:none;
}
/**
* Base styles ========================================================
*/
div#admin-toolbar {
z-index:100;
position:fixed;
}
html.overlay-open div#admin-toolbar { z-index:600; }
/**
* Toggling ===========================================================
*/
div#admin-toolbar div.admin-blocks {
overflow:hidden;
display:none;
}
body.admin-expanded div#admin-toolbar div.admin-blocks { display:block; }
div#admin-toolbar.ne,
div#admin-toolbar.nw { top:0px; }
div#admin-toolbar.se,
div#admin-toolbar.sw { bottom:0px; }
div#admin-toolbar.nw,
div#admin-toolbar.sw,
div#admin-toolbar.nw span.admin-toggle,
div#admin-toolbar.sw span.admin-toggle { left:0px; }
div#admin-toolbar.ne,
div#admin-toolbar.se,
div#admin-toolbar.ne span.admin-toggle,
div#admin-toolbar.se span.admin-toggle { right:0px; }
/**
* Vertical =========================================================
*/
div#admin-toolbar.vertical {
position:fixed;
bottom:0px;
top:0px;
}
div#admin-toolbar.vertical div.admin-blocks { width:0px; }
body.admin-expanded div#admin-toolbar.vertical div.admin-blocks { width:260px; }
div#admin-toolbar.vertical div.admin-block { width:240px; }
div#admin-toolbar.vertical div.admin-tabs { width:215px; }
body div#admin-toolbar.vertical div.admin-blocks { position:absolute; top:0px; bottom:0px; }
body.admin-expanded div#admin-toolbar.vertical.ne div.admin-blocks,
body.admin-expanded div#admin-toolbar.vertical.se div.admin-blocks { right:0px; }
body.admin-expanded div#admin-toolbar.vertical.nw div.admin-blocks,
body.admin-expanded div#admin-toolbar.vertical.sw div.admin-blocks { left:0px; }
body.admin-expanded.admin-vertical.admin-ne,
body.admin-expanded.admin-vertical.admin-se { margin-right:260px; }
body.admin-expanded.admin-vertical.admin-nw,
body.admin-expanded.admin-vertical.admin-sw { margin-left:260px; }
/**
* Horizontal =======================================================
*/
div#admin-toolbar.horizontal { left:0px; right:0px; }
body.admin-expanded div#admin-toolbar.horizontal div.admin-blocks { height:260px; }
body.admin-expanded.admin-horizontal.admin-ne,
body.admin-expanded.admin-horizontal.admin-nw { margin-top:260px; }
body.admin-expanded.admin-horizontal.admin-sw,
body.admin-expanded.admin-horizontal.admin-se { margin-bottom:260px; }
/**
* Toggler ============================================================
*/
div#admin-toolbar span.admin-toggle {
display:block;
width:35px;
height:35px;
cursor:pointer;
overflow:hidden;
text-indent:-999px;
position:absolute;
top:0px;
z-index:1000;
}
div#admin-toolbar.se span.admin-toggle,
div#admin-toolbar.sw span.admin-toggle {
position:fixed;
bottom:0px;
top:auto;
}
body.admin-expanded div#admin-toolbar span.admin-toggle {
position:absolute;
top:0px;
}
/**
* Admin tabs =========================================================
*/
div#admin-toolbar.horizontal div.admin-tabs {
height:30px;
padding:5px 10px 0px;
overflow:hidden;
}
div#admin-toolbar.vertical div.admin-tabs {
position:relative;
padding:5px 10px 25px;
}
div#admin-toolbar.ne div.admin-tabs,
div#admin-toolbar.se div.admin-tabs { padding-right:35px !important; }
div#admin-toolbar.nw div.admin-tabs,
div#admin-toolbar.sw div.admin-tabs { padding-left:35px !important; }
div#admin-toolbar div.admin-tab,
div#admin-toolbar div.admin-tab span,
div#admin-toolbar div.admin-tab a {
list-style:none;
background:transparent;
padding:0px;
margin:0px;
}
div#admin-toolbar div.admin-tab {
cursor:pointer;
padding:4px 19px;
height:15px;
border-width:1px;
border-style:solid;
}
div#admin-toolbar.vertical div.admin-tab {
overflow:hidden;
white-space:nowrap;
margin-bottom:5px;
padding-left:9px;
padding-right:9px;
width:195px;
}
div#admin-toolbar.horizontal div.admin-tab {
float:left;
margin-right:5px;
}
div#admin-toolbar div.admin-tab-active {
border-width:1px 1px 0px;
padding-bottom:10px;
}
div#admin-toolbar.vertical div.admin-tab-active {
padding-bottom:5px;
position:absolute;
bottom:0px;
margin:0px;
}
/**
* Admin blocks =======================================================
*/
div#admin-toolbar div.admin-block {
position:relative;
padding:10px;
display:none;
}
div#admin-toolbar div.block-content {
overflow-x:hidden;
overflow-y:auto;
position:absolute;
top:10px;
left:10px;
right:10px;
bottom:10px;
}
div#admin-toolbar div.admin-active { display:block; }
/**
* Horizontal =======================================================
*/
div#admin-toolbar.horizontal div.block-content { height:200px; }
/**
* Vertical =========================================================
*/
div#admin-toolbar.vertical div.admin-block { position:absolute; bottom:0px; left:0px; right:0px; }
div#admin-toolbar.vertical div.admin-blocks-1 div.admin-block { top:30px; }
div#admin-toolbar.vertical div.admin-blocks-2 div.admin-block { top:60px; }
div#admin-toolbar.vertical div.admin-blocks-3 div.admin-block { top:90px; }
div#admin-toolbar.vertical div.admin-blocks-4 div.admin-block { top:120px; }
div#admin-toolbar.vertical div.admin-blocks-5 div.admin-block { top:150px; }
div#admin-toolbar.vertical div.admin-blocks-6 div.admin-block { top:180px; }
div#admin-toolbar.vertical div.admin-blocks-7 div.admin-block { top:210px; }
div#admin-toolbar.vertical div.admin-blocks-8 div.admin-block { top:240px; }
div#admin-toolbar.vertical div.admin-blocks-9 div.admin-block { top:270px; }
div#admin-toolbar.vertical div.admin-blocks-10 div.admin-block { top:300px; }
/**
* Lists ==============================================================
*/
#admin-toolbar div.item-list li {
padding:5px 0px 4px;
border-style:solid;
border-width:0px 0px 1px;
}
/**
* Reasonable inline links
*/
#admin-toolbar ul.links {
-moz-border-radius:5px;
-webkit-border-radius:5px;
padding:5px;
}
#admin-toolbar ul.links li a { padding:2px 10px; }
/**
* Form elements ======================================================
*/
#admin-toolbar input.form-autocomplete,
#admin-toolbar input.form-text,
#admin-toolbar textarea.form-textarea,
#admin-toolbar select.form-select {
padding:2px;
border-width:2px;
border-style:solid;
width:90%;
}
#admin-toolbar input.form-submit {
cursor:pointer;
padding:2px 5px;
text-align:center;
font-weight:normal;
border-width:1px;
border-style:solid;
}
#admin-toolbar.vertical div.admin-panes div.admin-pane,
#admin-toolbar div.admin-panes div.admin-pane-active,
#admin-toolbar div.fieldset,
#admin-toolbar div.form-item {
position:relative;
margin:0px 0px 5px;
border-width:1px;
border-style:solid;
}
#admin-toolbar div.form-item { padding:4px; }
#admin-toolbar div.form-item label {
margin:0px;
padding:0px;
font-weight:bold;
font-size:10px;
text-transform:uppercase;
}
#admin-toolbar div.form-item label.option {
text-transform:none;
font-size:11px;
}
#admin-toolbar div.form-item label.option input { vertical-align:middle; }
#admin-toolbar.vertical div.form-item div.description { font-size:10px; }
/**
* Admin panes ========================================================
*/
#admin-toolbar div.admin-panes h2.admin-pane-title a {
display:block;
padding:4px;
}
#admin-toolbar div.admin-panes div.admin-pane-content {
padding:4px;
display:none;
}
#admin-toolbar div.admin-panes div.admin-pane-active div.admin-pane-content { display:block; }
#admin-toolbar div.admin-pane div.form-item {
border:0px;
-moz-border-radius:0px;
-webkit-border-radius:0px;
padding:5px 0px;
margin:0px;
background:transparent;
}
/**
* Horizontal layout.
*/
#admin-toolbar.horizontal div.admin-panes {
position:relative;
padding-left:200px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane {
-moz-border-radius:0px;
-webkit-border-radius:0px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-content { padding:4px 9px; }
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs {
z-index:500;
position:absolute;
left:0px;
width:200px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a { padding:5px; }
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a.admin-pane-active {
padding:4px;
border-width:1px 0px 1px 1px;
border-style:solid;
margin-right:-1px;
}
body.toolbar.admin-nw #admin-toolbar,
body.toolbar.admin-ne #admin-toolbar {
margin-top: 65px;
}

View File

@@ -0,0 +1,188 @@
/**
* Base styles ========================================================
*/
div#admin-toolbar,
div#admin-toolbar * {
font:normal 11px/15px "Lucida Grande",Tahoma,Verdana,sans-serif;
color:#ccc;
}
div#admin-toolbar a {
text-decoration:none;
color:#fff;
font-weight:normal;
}
/**
* Toolbar background =================================================
*/
div#admin-toolbar div.admin-blocks { background:url(../images/black.png) 0px 35px repeat-x; }
div#admin-toolbar.vertical div.admin-blocks { background-color:#000; }
/**
* Toggle =============================================================
*/
div#admin-toolbar span.admin-toggle { background:url(../images/sprite.png) 0px 0px no-repeat; }
/* Positions */
div#admin-toolbar.nw span.admin-toggle { background-position:0px 0px; }
div#admin-toolbar.ne span.admin-toggle { background-position:-35px 0px; }
div#admin-toolbar.se span.admin-toggle { background-position:-70px 0px; }
div#admin-toolbar.sw span.admin-toggle { background-position:-105px 0px; }
/* Expanded */
body.admin-expanded div#admin-toolbar span.admin-toggle { background-position:0px -35px; }
/**
* Tabs ===============================================================
*/
div#admin-toolbar div.admin-tabs { background:#222 url(../images/bleeds.png) 0px 100% repeat-x; }
div#admin-toolbar div.admin-tab {
-moz-border-radius:5px;
-moz-box-shadow: #333 0px 1px 0px;
-webkit-border-radius:5px;
-webkit-box-shadow: #333 0px 1px 0px;
text-shadow: #222 0px 1px 0px;
background:url(../images/bleeds.png) 0px 0px repeat-x;
cursor:pointer;
border-color:#111;
}
div#admin-toolbar div.admin-tab,
div#admin-toolbar div.admin-tab a { color:#999; }
div#admin-toolbar div.admin-tab-active {
-moz-border-radius:5px 5px 0px 0px;
-moz-box-shadow: none;
-webkit-border-radius:0px;
-webkit-border-top-left-radius:5px;
-webkit-border-top-right-radius:5px;
-webkit-box-shadow: none;
background:#000;
border-color:#555 #333;
}
div#admin-toolbar div.admin-tab:hover,
div#admin-toolbar div.admin-tab-active,
div#admin-toolbar div.admin-tab-active a { color:#fff; }
/**
* Drupal elements ====================================================
*/
/* Lists */
#admin-toolbar div.item-list li { border-color:#222; }
/* Links */
#admin-toolbar ul.links { background:#111; }
#admin-toolbar ul.links li a {
-moz-border-radius:3px;
-webkit-border-radius:3px;
background:#333;
}
#admin-toolbar ul.links li a:hover {
background:#eee;
color:#333;
}
/**
* Form elements ======================================================
*/
#admin-toolbar input.form-autocomplete,
#admin-toolbar input.form-text,
#admin-toolbar textarea.form-textarea,
#admin-toolbar select.form-select {
border-color:#000;
background:#000;
color:#999;
}
#admin-toolbar input.form-autocomplete:hover,
#admin-toolbar input.form-text:hover,
#admin-toolbar textarea.form-textarea:hover,
#admin-toolbar select.form-select:hover,
#admin-toolbar div.form-item:hover input.form-autocomplete,
#admin-toolbar div.form-item:hover input.form-text,
#admin-toolbar div.form-item:hover textarea.form-textarea,
#admin-toolbar div.form-item:hover select.form-select,
#admin-toolbar input.form-autocomplete:focus,
#admin-toolbar input.form-text:focus,
#admin-toolbar textarea.form-textarea:focus,
#admin-toolbar select.form-select:focus {
color:#fff;
border-color:#333;
}
#admin-toolbar input.form-submit {
color:#999;
border-color:#555 #444 #333;
background:#222 url(../images/bleeds.png) 0px 100% repeat-x;
-moz-border-radius:3px;
-webkit-border-radius:3px;
}
#admin-toolbar input.form-submit:hover {
border-color:#aaa #888 #666;
background:#444 url(../images/bleeds.png) 0px 0px repeat-x;
color:#fff;
}
#admin-toolbar input.form-submit:active {
border-color:#333;
background:#111;
color:#fff;
}
#admin-toolbar.vertical div.admin-panes div.admin-pane,
#admin-toolbar div.admin-panes div.admin-pane-active,
#admin-toolbar div.fieldset,
#admin-toolbar div.form-item {
background:#111;
border-color:#222;
-moz-border-radius:3px;
-webkit-border-radius:3px;
}
#admin-toolbar div.form-item { padding:4px; }
#admin-toolbar div.form-item div.description,
#admin-toolbar div.form-item label { color:#999; }
/**
* Admin panes ========================================================
*/
#admin-toolbar div.admin-panes div.admin-pane:hover,
#admin-toolbar div.admin-panes div.admin-pane-active,
#admin-toolbar.vertical div.admin-panes div.admin-pane-active {
background:#222;
border-color:#333;
}
#admin-toolbar div.admin-panes h2.admin-pane-title a { color:#666; }
#admin-toolbar div.admin-panes h2.admin-pane-title a:hover,
#admin-toolbar div.admin-panes h2.admin-pane-title a.admin-pane-active { color:#fff; }
#admin-toolbar div.admin-pane div.item-list li { border-color:#333; }
/* Horizontal */
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a {
-moz-border-radius:3px 0px 0px 3px;
-webkit-border-top-left-radius:3px;
-webkit-border-bottom-left-radius:3px;
}
#admin-toolbar.horizontal div.admin-panes div.admin-pane-tabs a.admin-pane-active {
background:#222;
border-color:#333;
}
body.toolbar #admin-toolbar.vertical {
margin-top: 65px;
}

View File

@@ -0,0 +1,257 @@
(function($) {
Drupal.behaviors.adminToolbar = {};
Drupal.behaviors.adminToolbar.attach = function(context) {
$('#admin-toolbar:not(.processed)').each(function() {
var toolbar = $(this);
toolbar.addClass('processed');
// Set initial toolbar state.
Drupal.adminToolbar.init(toolbar);
// Admin toggle.
$('.admin-toggle', this).click(function() { Drupal.adminToolbar.toggle(toolbar); });
// Admin tabs.
$('div.admin-tab', this).click(function() { Drupal.adminToolbar.tab(toolbar, $(this), true); });
$(document).bind('drupalOverlayLoad', {adminToolbar: Drupal.adminToolbar, toolbar: toolbar}, function(event) {
var body = $(document.body);
var adminToolbar = event.data.adminToolbar;
var expand = parseInt(adminToolbar.getState('expanded'));
if (!expand) {
return;
}
var toolbar = event.data.toolbar;
var size = adminToolbar.SIZE + 'px';
adminToolbar.setOverlayState(toolbar, toolbar.is('.vertical'), expand);
});
});
$('div.admin-panes:not(.processed)').each(function() {
var panes = $(this);
panes.addClass('processed');
$('h2.admin-pane-title a').click(function() {
var target = $(this).attr('href').split('#')[1];
var panes = $(this).parents('div.admin-panes')[0];
$('.admin-pane-active', panes).removeClass('admin-pane-active');
$('div.admin-pane.' + target, panes).addClass('admin-pane-active');
$(this).addClass('admin-pane-active');
return false;
});
});
};
/**
* Admin toolbar methods.
*/
Drupal.adminToolbar = {};
/**
* The width or height of the toolbar, depending on orientation.
*/
Drupal.adminToolbar.SIZE = 260;
/**
* Set the initial state of the toolbar.
*/
Drupal.adminToolbar.init = function (toolbar) {
// Set expanded state.
var expanded = this.getState('expanded');
if (!$(document.body).hasClass('admin-ah')) {
if (expanded == 1) {
$(document.body).addClass('admin-expanded');
}
}
// Set default tab state.
var target = this.getState('activeTab');
if (target) {
if ($('div.admin-tab.'+target).size() > 0) {
var tab = $('div.admin-tab.'+target);
this.tab(toolbar, tab, false);
}
}
// Add layout class to body.
var classes = toolbar.attr('class').split(' ');
if (classes[0] === 'nw' || classes[0] === 'ne' || classes[0] === 'se' || classes[0] === 'sw' ) {
$(document.body).addClass('admin-'+classes[0]);
}
if (classes[1] === 'horizontal' || classes[1] === 'vertical') {
$(document.body).addClass('admin-'+classes[1]);
}
if (classes[2] === 'df' || classes[2] === 'ah') {
$(document.body).addClass('admin-'+classes[2]);
}
var vertical = true;
if(classes[1] === 'horizontal') {
vertical = false;
}
};
/**
* Set the active tab.
*/
Drupal.adminToolbar.tab = function(toolbar, tab, animate) {
if (!tab.is('.admin-tab-active')) {
var target = $('span', tab).attr('id').split('admin-tab-')[1];
// Vertical
// Use animations to make the vertical tab transition a bit smoother.
if (toolbar.is('.vertical') && animate) {
$('.admin-tab-active', toolbar).fadeOut('fast');
$(tab).fadeOut('fast', function() {
$('.admin-tab-active', toolbar).fadeIn('fast').removeClass('admin-tab-active');
$(tab).slideDown('fast').addClass('admin-tab-active');
Drupal.adminToolbar.setState('activeTab', target);
});
}
// Horizontal
// Tabs don't need animation assistance.
else {
$('div.admin-tab', toolbar).removeClass('admin-tab-active');
$(tab, toolbar).addClass('admin-tab-active');
Drupal.adminToolbar.setState('activeTab', target);
}
// Blocks
$('div.admin-block.admin-active', toolbar).removeClass('admin-active');
$('#block-'+target, toolbar).addClass('admin-active');
}
return false;
};
/**
* Set the width/height of the of the overlay body based on the state admin toolbar.
*
* @param vertical
* A boolean indicating if the toolbar is vertical.
* @param expanded
* A boolean indicating if the toolbar is expanded.
*/
Drupal.adminToolbar.setOverlayState = function(toolbar, vertical, expanded) {
var margin,
size = this.SIZE + 65;
if (!expanded) {
size = 0;
}
margin = {marginLeft: size+'px'};
if (vertical) {
if (toolbar.is('.ne') || toolbar.is('.se')) {
margin = {marginRight: size+'px'}
}
}
else {
if (toolbar.is('.ne') || toolbar.is('.nw')) {
margin = {marginTop: size+'px'};
}
else {
margin = {marginBottom: size+'px'};
}
}
$('iframe.overlay-element').contents().find('body').animate(margin, 'fast');
};
/**
* Toggle the toolbar open or closed.
*/
Drupal.adminToolbar.toggle = function (toolbar) {
var size = '0px';
if ($(document.body).is('.admin-expanded')) {
if ($(toolbar).is('.vertical')) {
$('div.admin-blocks', toolbar).animate({width:size}, 'fast');
if ($(toolbar).is('.nw') || $(toolbar).is('.sw')) {
$(document.body).animate({marginLeft:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
else {
$(document.body).animate({marginRight:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
this.setOverlayState(toolbar, true, false);
}
else {
$('div.admin-blocks', toolbar).animate({height:size}, 'fast');
if ($(toolbar).is('.nw') || $(toolbar).is('.ne')) {
$(document.body).animate({marginTop:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
else {
$(document.body).animate({marginBottom:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
this.setOverlayState(toolbar, false, false);
}
this.setState('expanded', 0);
}
else {
size = this.SIZE + 'px';
if ($(toolbar).is('.vertical')) {
$('div.admin-blocks', toolbar).animate({width:size}, 'fast');
if ($(toolbar).is('.nw') || $(toolbar).is('.sw')) {
$(document.body).animate({marginLeft:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
else {
$(document.body).animate({marginRight:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
this.setOverlayState(toolbar, true, true);
}
else {
$('div.admin-blocks', toolbar).animate({height:size}, 'fast');
if ($(toolbar).is('.nw') || $(toolbar).is('.ne')) {
$(document.body).animate({marginTop:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
else {
$(document.body).animate({marginBottom:size}, 'fast', function() { $(this).toggleClass('admin-expanded'); });
}
this.setOverlayState(toolbar, false, true);
}
if ($(document.body).hasClass('admin-ah')) {
this.setState('expanded', 0);
}
else {
this.setState('expanded', 1);
}
}
};
/**
* Get the value of a cookie variable.
*/
Drupal.adminToolbar.getState = function(key) {
if (!Drupal.adminToolbar.state) {
Drupal.adminToolbar.state = {};
var cookie = $.cookie('DrupalAdminToolbar');
var query = cookie ? cookie.split('&') : [];
if (query) {
for (var i in query) {
// Extra check to avoid js errors in Chrome, IE and Safari when
// combined with JS like twitter's widget.js.
// See http://drupal.org/node/798764.
if (typeof(query[i]) == 'string' && query[i].indexOf('=') != -1) {
var values = query[i].split('=');
if (values.length === 2) {
Drupal.adminToolbar.state[values[0]] = values[1];
}
}
}
}
}
return Drupal.adminToolbar.state[key] ? Drupal.adminToolbar.state[key] : false;
};
/**
* Set the value of a cookie variable.
*/
Drupal.adminToolbar.setState = function(key, value) {
var existing = Drupal.adminToolbar.getState(key);
if (existing != value) {
Drupal.adminToolbar.state[key] = value;
var query = [];
for (var i in Drupal.adminToolbar.state) {
query.push(i + '=' + Drupal.adminToolbar.state[i]);
}
$.cookie('DrupalAdminToolbar', query.join('&'), {expires: 7, path: '/'});
}
};
})(jQuery);

View File

@@ -0,0 +1,165 @@
/**
* Generic menu drilldown plugin for standard Drupal menu tree markup.
* The plugin should be inited against a DOM element that *contains*
* a Drupal ul.menu tree. Example:
*
* $('div.block-menu').drilldown('init', params);
*
* You must provide the following parameters as settings:
*
* var params = {
* activePath : A drupal menu path that is currently active including the basePath e.g. "/mysite/node"
* trail : A jquery selector to the DOM element that should act as the trail container, e.g. "div.my-menu-breadcrumb-trail"
* rootTitle : The title to use for the root menu item if the menu does not already possess one. Optional.
* }
*
*/
(function($) {
$.fn.drilldown = function(method, settings) {
var menu = this;
var activePath;
var rootTitle = settings.rootTitle || 'Home';
switch (method) {
case 'goTo':
// If the passed link refers to the current page, don't follow through
// the link.
if (this.activePath && this.activePath === $(settings.activeLink).attr('href')) {
return false;
}
return true;
case 'setActive':
var breadcrumb = [];
var activeMenu;
$(settings.activeLink).each(function() {
// Traverse backwards through menu parents and build breadcrumb array.
$(this).parents('ul.menu').each(function() {
if ($(this).parents('ul.menu').size() > 0) {
$(this).siblings('a').each(function() {
breadcrumb.unshift($(this));
});
}
// If this is a root menu with no root link to accompany it,
// generate one such that the breadcrumb may reference it.
else if ($(this).children('li').size() > 1) {
var root;
if ($(this).siblings('a.drilldown-root').size() > 0) {
root = $(this).siblings('a.drilldown-root');
}
else {
root = $('<a href="#" class="drilldown-root" style="display:none">'+rootTitle+'</a>');
$(this).before(root);
}
breadcrumb.unshift(root);
}
});
// If we have a child menu (actually a sibling in the DOM), use it
// as the active menu. Otherwise treat our direct parent as the
// active menu.
if ($(this).next().is('ul.menu')) {
activeMenu = $(this).next();
breadcrumb.push($(this));
}
else {
activeMenu = $(this).parents('ul.menu').eq(0);
}
if (activeMenu) {
$('.drilldown-active-trail', menu).removeClass('drilldown-active-trail');
$('ul.menu', menu).removeClass('drilldown-active-menu').removeClass('clearfix');
$(activeMenu)
.addClass('drilldown-active-menu').addClass('clearfix')
.parents('li').addClass('drilldown-active-trail').show();
}
});
// Render the breadcrumb to the target DOM object
if (breadcrumb.length > 0) {
var trail = $(settings.trail);
trail.empty();
for (var key in breadcrumb) {
if (breadcrumb[key]) {
// We don't use the $().clone() method here because of an
// IE & jQuery 1.2 bug.
var clone = $('<a></a>')
.attr('href', $(breadcrumb[key]).attr('href'))
.attr('class', $(breadcrumb[key]).attr('class'))
.html($(breadcrumb[key]).html())
.addClass('depth-'+key)
.appendTo(trail);
// We add a reference to the original link and a click handler
// that traces back to that instance to set as the active link.
$('a.depth-'+key, trail)
.data('original', $(breadcrumb[key]))
.click(function() {
settings.activeLink = $(this).data('original');
// If the clicked link does not reference the current
// active menu, set it to be active.
if (settings.activeLink.siblings('ul.drilldown-active-menu').size() === 0) {
menu.drilldown('setActive', settings);
return false;
}
// Otherwise, pass-through and allow the link to be clicked.
return menu.drilldown('goTo', settings);
});
}
}
}
// Event in case others need to update themselves when a new active
// link is set.
$(menu).trigger('refresh.drilldown');
break;
case 'init':
if ($('ul.menu ul.menu', menu).size() > 0) {
$(menu).addClass('drilldown');
$(settings.trail).addClass('drilldown-trail');
// Set initial active menu state.
var activeLink;
$('ul.menu a', menu).removeClass('active');
if (settings.activePath && $('ul.menu a[href="'+settings.activePath+'"]', menu).size() > 0) {
this.activePath = settings.activePath;
activeLink = $('ul.menu a[href="'+settings.activePath+'"]', menu).addClass('active');
}
if (!activeLink) {
activeLink = $('ul.menu a.active', menu).size() ? $('ul.menu a.active', menu) : $('ul.menu > li > a', menu);
}
if (activeLink) {
menu.drilldown('setActive', {
activeLink: $(activeLink[0]),
trail: settings.trail,
rootTitle: rootTitle
});
}
// Attach click handlers to menu items
$('ul.menu li:has(ul.menu)', this).click(function() {
if ($(this).parent().is('.drilldown-active-menu')) {
if (menu.data('disableMenu')) {
return true;
}
else {
var url = $(this).children('a').attr('href');
var activeLink = $('ul.menu a[href="'+url+'"]', menu);
menu.drilldown('setActive', {
activeLink: activeLink,
trail: settings.trail,
rootTitle: rootTitle
});
return false;
}
}
});
$('ul.menu li:has(ul.menu) a', menu).click(function() {
menu.data('disableMenu', true);
});
}
break;
}
return this;
};
})(jQuery);

View File

@@ -0,0 +1,30 @@
<div class='admin-panes clearfix '>
<?php if ($layout == 'vertical'): ?>
<?php foreach ($panels as $key => $panel): ?>
<div class='admin-pane <?php if (!isset($first)) print 'admin-pane-active' ?> admin-pane-<?php print $key ?>'>
<h2 class='admin-pane-title'><?php print $labels[$key] ?></h2>
<div class='admin-pane-content clearfix'><?php print render($panel) ?></div>
</div>
<?php $first = TRUE ?>
<?php endforeach; ?>
<?php else: ?>
<div class='admin-pane-tabs'>
<?php foreach ($panels as $key => $panel): ?>
<h2 class='admin-pane-title'><?php print $labels[$key] ?></h2>
<?php endforeach; ?>
</div>
<?php foreach ($panels as $key => $panel): ?>
<div class='admin-pane <?php if (!isset($first)) print 'admin-pane-active' ?> admin-pane-<?php print $key ?>'>
<div class='admin-pane-content clearfix'><?php print render($panel) ?></div>
</div>
<?php $first = TRUE ?>
<?php endforeach; ?>
<?php endif; ?>
<?php print render($others) ?>
</div>

View File

@@ -0,0 +1,18 @@
<div id='admin-toolbar' class='<?php print $position ?> <?php print $layout ?> <?php print $behavior ?>'>
<span class='admin-toggle'><?php print t('Admin') ?></span>
<div class='admin-blocks admin-blocks-<?php print count($blocks) ?>'>
<div class='admin-tabs clearfix'>
<?php foreach ($tabs as $bid => $tab): ?>
<?php print theme('admin_tab', array('tab' => $tab, 'class' => $bid)); ?>
<?php endforeach; ?>
</div>
<?php foreach ($blocks as $block): ?>
<div class='admin-block <?php if (isset($block->class)) print $block->class ?>' id='block-<?php print $block->bid ?>'>
<div class='block-content clearfix'><?php print render($block->content) ?></div>
</div>
<?php endforeach; ?>
</div>
</div>

View File

@@ -0,0 +1,144 @@
<?php
/**
* Preprocessor for theme('admin_toolbar').
*/
function template_preprocess_admin_toolbar(&$vars) {
// Set the active block.
$active = admin_get_settings('active_tab') ? admin_get_settings('active_tab') : key($vars['blocks']);
if (!empty($vars['blocks'])) {
$blocks = $vars['blocks'];
$vars['tabs'] = array();
$vars['blocks'] = array();
foreach ($blocks as $block) {
$bid = $block->bid;
$vars['tabs'][$bid] = array(
'title' => $block->subject,
'attributes' => array('id' => 'admin-tab-' . $bid),
);
$vars['blocks'][$bid] = $block;
// Mark active tab, block.
if ($bid == $active) {
$vars['blocks'][$bid]->class = 'admin-active';
$vars['tabs'][$bid]['active'] = TRUE;
}
}
}
}
/**
* Theme function for form API element '#type' => 'admin_panes'.
*/
function template_preprocess_admin_panes(&$vars) {
drupal_add_js(drupal_get_path('module', 'admin') . '/includes/admin.toolbar.js');
$vars['layout'] = admin_get_settings('layout');
$vars['labels'] = $vars['panels'] = $vars['others'] = array();
$first = TRUE;
foreach (element_children($vars['element']) as $key) {
if (!isset($vars['element'][$key]['#access']) || $vars['element'][$key]['#access']) {
if (!empty($vars['element'][$key]['#title'])) {
$vars['labels'][$key] = l($vars['element'][$key]['#title'], $_GET['q'], array(
'fragment' => 'admin-pane-' . $key,
'attributes' => array(
'class' => array($first ? 'admin-pane-active' : '')
)
));
$vars['panels'][$key] = $vars['element'][$key];
$first = FALSE;
}
else {
$vars['others'][] = $vars['element'][$key];
}
}
}
}
/**
* Generate markup for an admin tab.
*/
function theme_admin_tab($variables) {
$tab = $variables['tab'];
$class = $variables['class'];
$attr = isset($tab['attributes']) ? drupal_attributes($tab['attributes']) : '';
$class .= !empty($tab['active']) ? ' admin-tab-active' : '';
$title = filter_xss_admin($tab['title']);
return "<div class='admin-tab {$class}'><span {$attr}>{$title}</span></div>";
}
/**
* Alternative to menu_tree_output() which uses admin implementations of the
* core menu theme functions.
*/
function theme_admin_drilldown_menu_tree_output($variables) {
$tree = $variables['menu'];
$output = '';
$items = array();
// Pull out just the menu items we are going to render so that we
// get an accurate count for the first/last classes.
foreach ($tree as $data) {
if (!$data['link']['hidden']) {
$items[] = $data;
}
}
$num_items = count($items);
foreach ($items as $i => $data) {
$extra_class = NULL;
if ($i == 0) {
$extra_class = 'first';
}
if ($i == $num_items - 1) {
$extra_class = 'last';
}
$link = theme('admin_drilldown_menu_item_link', array('item' => $data['link']));
$in_active_trail = isset($data['link']['in_active_trail']) ? $data['link']['in_active_trail'] : FALSE;
if ($data['below']) {
$output .= theme('admin_drilldown_menu_item', array('link' => $link, 'has_children' => $data['link']['has_children'], 'menu' => theme('admin_drilldown_menu_tree_output', array('menu' => $data['below'])), 'in_active_trail' => $in_active_trail, 'extra_class' => $extra_class));
}
else {
$output .= theme('admin_drilldown_menu_item', array('link' => $link, 'has_children' => $data['link']['has_children'], 'menu' => '', 'in_active_trail' => $in_active_trail, 'extra_class' => $extra_class));
}
}
return $output ? theme('admin_drilldown_menu_tree', array('menu' => $output)) : '';
}
/**
* Alternative to theme_menu_tree().
* Ensures custom theme-level overrides of theme_menu_tree() do not break
* markup expected by admin.
*/
function theme_admin_drilldown_menu_tree($variables) {
$tree = $variables['menu'];
return theme_menu_tree($tree);
}
/**
* Alternative to theme_menu_item().
* Ensures custom theme-level overrides of theme_menu_item() do not break
* markup expected by admin.
*/
function theme_admin_drilldown_menu_item($variables) {
$link = $variables['link'];
$has_children = $variables['has_children'];
$menu = $variables['menu'];
$in_active_trail = $variables['in_active_trail'];
$extra_class = $variables['extra_class'];
return theme_menu_item($link, $has_children, $menu, $in_active_trail, $extra_class);
}
/**
* Alternative to theme_menu_item_link().
*/
function theme_admin_drilldown_menu_item_link($variables) {
$link = $variables['item'];
$link['localized_options'] = empty($link['localized_options']) ? array() : $link['localized_options'];
$link['localized_options']['html'] = TRUE;
$link['localized_options']['purl'] = array('disabled' => TRUE);
$link['description'] = check_plain(truncate_utf8(strip_tags($link['description']), 150, TRUE, TRUE));
$link['title'] .= !empty($link['description']) ? "<span class='menu-description'>{$link['description']}</span>" : '';
$link['title'] = filter_xss_admin($link['title']);
return l($link['title'], $link['href'], $link['localized_options']);
}

View File

@@ -0,0 +1,366 @@
Admin Menu 7.x-3.x, xxxx-xx-xx
------------------------------
#1177202 by das-peter, dereine, sun: Fixed copying and re-injection of child
router items breaks badly. Change them by reference instead.
Requires latest Views 3.x code.
#1212064 by sun: Updated admin_views default views for VBO 3.x.
#1196590 by sun: Fixed errors and notices for admin_views with Views 3.
#1144768 by idlewilder, sun: Fixed devel modules to skip are not displayed.
#1079374 by WillHall: Fixed JS Error: unrecognized expression: [href=/].
#1114132 by joelstein, sun: Added Field UI to list of developer modules.
#1008380 by bdragon, sun: Updated admin_views for D7.
#1146644 by sun: Fixed PHP 5.3 compability in tests.
#442560 by sun: Fixed 'defer' script attribute breaks Drupal.behaviors in FF3.6.
#1022902 by matglas86, sun: Updated for changed core Toolbar styles.
Admin Menu 7.x-3.0-RC1, 2010-01-07
----------------------------------
#990774 by sun: Updated for $closure renamed to $page_bottom.
#991906 by johnv, sun: Added configure to .info file.
#947198 by sun: Added hint about disabling Toolbar.
by sun: Updated administrative settings form for D7 UX guidelines.
by sun: Disabled "Rebuild system links" button on settings form.
#420816 by sun, smk-ka: Improved on-demand loading of dynamic paths.
#420816 by tim.plunkett: Fixed dynamic Field UI paths for vocabularies.
#871774 by swentel: Fixed developer modules toggle still uses referer_uri().
#671760 by sun: Updated for new preprocess defaults.
#731462 by sun: Updated for system_rebuild_theme_data().
by sun: Re-added a "Rebuild system links" button to settings form.
#420816 by tim.plunkett: Updated taxonomy path map for machine names.
#857688 by sun: Updated for reverted system_settings_form().
#420816 by smk-ka, sun: Added merging of menu trees containing dynamic paths.
by sun: Fixed tests and minor admin_menu_toolbar styling issues.
by sun: Fixed various styling issues for admin_menu and admin_menu_toolbar.
by sun: Updated for Schema API, DBTNG, coding standards.
by sun: Updated for new admin/modules path.
#701424 by hutch: Updated for new admin/people/people path.
by sun: Removed orphan menu rewrite function.
#667858 by sun: Don't remove the current user from the switch user list.
#631550 by sun: Updated for fixed MENU_VISIBLE_IN_BREADCRUMB behavior.
#658344 by dereine, sun: Updated for removed drupal_session_count().
by sun: Added separate permission to flush cashes.
by sun: Updated for changed Devel settings form.
by sun: Updated for new {system}.info module data.
#614730 by azriprajwala, sun: Updated for hook_theme() key changes.
by sun: Updated for all theme functions should take a single argument.
by sun: Reverted removal of registry cache flushing option.
#578520 by sun: Fixed destination query parameter is processed wrongly.
#578520 by sun: Updated for $query in url() should always be an array.
by Dave Reid: Updated for PHP 5 date constants.
by sun: Updated for new database API.
by smk-ka: Removed remnants of the registry. Fixed flush admin menu cache
command.
#567618 by smk-ka: Revised test cases. Abstracted out base web test class.
by sun: Updated for removed registry, new admin paths.
#326539 by sun: Updated for class attribute array.
#519782 by sun: Updated for hook_footer() replaced by hook_page_alter().
#525638 by Razorraser: Updated for admin/build renamed to admin/structure.
by Dave Reid: Updated for hook_permission().
#482314 by Dave Reid: Updated for node_type_get_types().
#437506 by yched, Dave Reid: Updated for menu_router_build().
#376816 by sun: Updated for compatibility for other JavaScript libraries.
#337820 by Dave Reid: Updated for new user/logout path.
#340546 by Dave Reid: Updated for drupal_add_js().
#340531 by Dave Reid: Updated for module_list().
#266358 by sun: Updated for drupal_add_css().
#320526 by yettyn, sun: Updated to UNSTABLE-2 (DBTNG queries, permissions, etc).
by sun: Changed admin_menu_wipe() to admin_menu_flush_caches().
by sun: Updated content-type edit menu item locations.
by sun: Fixed sess_count() changed to drupal_session_count().
Admin Menu 6.x-3.x, xxxx-xx-xx
------------------------------
#588936 by fenstrat: Fixed Toolbar shortcuts not visible.
#860390 by Kevin Rogers: Fixed .info file parsing error on uncertain platform.
#551484 by sun: Fixed stale hook_admin_menu_output_alter() docs.
Admin Menu 6.x-3.0-ALPHA4, 2010-03-11
-------------------------------------
#730156 by sun: Fixed Administration views.
by sun: Fixed missing .element-hidden style in D6 for permissions tweak.
#645526 by TravisCarden: Fixed stale local tasks markup after moving them.
#366442 by sun: Added tweak to collapse modules on permissions page.
#655926 by donquixote, sun: Improved performance of delayed mouseout.
#557062 by sun: Fixed admin_menu_toolbar JS/CSS loaded before admin_menu's.
#599462 by sun, koyama: Added background-color to avoid unintentional override.
#601918 by BWPanda: Fixed admin_menu.css overrides admin_menu_toolbar.css.
#586228 by Island Usurper: Fixed for PHP 5.3.
#554124 by Dave Reid: Added missing toolbar.png.
#557062 by Dave Reid: Fixed undefined Drupal.admin error when including
admin_menu_toolbar.js before admin_menu.js.
#511744 by smk-ka, sun: Fixed /admin page links are broken.
by smk-ka: Added missing variables to hook_uninstall().
#571038 by smk-ka: Removed call to admin_menu_wipe() and cleaned install file.
#552190 by Bartezz: Fixed missing t() for user logout link.
Admin Menu 6.x-3.0-ALPHA3, 2009-08-16
-------------------------------------
#502500 by sun: Added "Create content" menu.
#538714 by sun: Fixed wrong re-parenting in Drupal's menu system.
#550132 by sun: Fixed (temporarily) admin_views menu items.
by sun: Added Administration views sub-module, converting all administrative
listing pages in Drupal core into real, ajaxified, and alterable views.
#547206 by sun: Fixed menu link descriptions lead to mouseover clashes.
#540954 by Rob Loach: Added String Overrides to list of developer modules.
#540762 by Deslack: Added Malay translation.
Admin Menu 6.x-3.0-ALPHA2, 2009-08-02
-------------------------------------
#527908 by sun: Changed theme_admin_menu_links() to use $element['#children'].
#527908 by markus_petrux, sun: Changed admin menu into a renderable array.
#420812 by sun, smk-ka: Added support for hook_js().
by sun: Fixed destination query string of current page not applied to links.
by sun: Changed Drupal.admin.attachBehaviors() to accept local JS settings.
#276751 by sun: Revamped rendering of menu additions/widgets.
#500866 by sun: Updated for removed t() from getInfo() in tests.
#402058 by sun: Added Administration menu toolbar module.
by markus_petrux, sun: Added API documentation.
#461264 by sun: Added site/domain as CSS class.
#451270 by smk-ka, sun: Changed visual indication for uid1.
by sun: Minor code clean-up.
#490670 by sun: Fixed missing menu after installation/upgrade.
#515718 by joelstein, sun: Added rules_admin module to developer modules list.
#352065 by sun: Added setting to select developer modules to keep enabled.
#511854 by psynaptic: Fixed logout link.
#424960 by markus_petrux, sun: Fixed gzip compression for cached output.
by sun: Fixed opacity of links in sub-menus.
#479922 by sun: Fixed fieldsets not collapsed on admin/build/modules/list*.
#495148 by sun: Fixed MENU_NORMAL_ITEMs do not appear in administration menu.
by sun: Fixed tests for new content-type locations.
#345984 by markus_petrux, sun: Fixed old menu links not removed on upgrade.
#276751 by sun: Major rewrite. Fixed menu items cannot be moved, altered, or
added as well as various performance issues.
by sun: Added variable to allow to disable caching (rewrite).
Admin Menu 6.x-3.0-ALPHA1, 2009-06-10
-------------------------------------
#236657 by sun: Updated for corrected arguments of system_clear_cache_submit().
#483870 by sun: Fixed compatibility with new Admin module.
#483152 by sun: Fixed admin_menu caches not flushed when clean URLs are toggled.
#479922 by danep: Fixed fieldsets not collapsed on admin/build/modules/list.
#469716 by sun: Fixed wrong AJAX callback URL under various conditions.
#471504 by wulff: Updated Danish translation.
by sun: Fixed admin_menu_suppress() does not suppress margin-top.
#451270 by sun: Added visual indication when working as uid 1.
by Dave Reid: Updated for getInfo() in tests.
#420828 by sun: Added dynamic replacements for cached administration menu.
#420840 by sun: Fixed Drupal.behaviors.adminMenu must be only executed once.
#345984 by markus_petrux, sun: Added client-side caching of administration menu.
Attention: A new era of Drupal user experience starts here. This is the very
first issue of a series of improvements targeting plain awesomeness.
#349169 by sun: Fixed Devel switch user links contain multiple path prefixes.
#345984 by sun: Code clean-up in preparation for client-side caching.
#415196 by psynaptic: Updated for CSS coding standards.
#406672 by mr.j, sun: Fixed "Move local tasks" option leaves stale UL.
by sun: Major code clean-up and sync across 3.x branches.
#349505 by smk-ka, sun: Performance: Added caching of entire menu output.
#315342 by wulff: Added "My account" link (by splitting the "Log out" item).
#384100 by kepol, sun: Fixed content-type items displayed in wrong place.
#373339 by sun: Fixed double-escaped 'Edit <content-type>' link titles.
#373372 by sun: Turned procedural JavaScript into admin menu behaviors.
by sun: Fixed admin menu tests (and updated to 6.x for SimpleTest 2.x).
#359158 by nitrospectide, sun: Fixed Devel Themer breaks admin menu.
#365335 by sun: Fixed not all variables removed after uninstall.
Admin Menu 6.x-1.3, 2009-01-24
------------------------------
#362454 by sun: Fixed Drupal.settings.admin_menu is undefined JS error in some
browsers.
Admin Menu 6.x-1.2, 2009-01-20
------------------------------
#358697 by sun: Added docs about admin_menu_suppress() to README.txt.
#342684 by darumaki, sun: Added notice about Opera configuration to README.txt.
#350932 by sun: Fixed "Run updates" link repeated per language/site.
#342298 by gustz: Updated Spanish translation.
#346106 by sun: Fixed XHTML-Strict validation for admin menu icon.
#287448 by sun: Fixed unnecessary menu rebuild for users without permission to
use admin menu.
#342002 by AltaVida: Fixed improper test for node/add paths.
#272920 by keith.smith: Changed all text strings throughout the module.
#322731 by sun: Fixed improper use of t() in module install file.
#282030 by sun: Fixed "Run updates" item visible for unprivileged users.
#322877 by sun: Added tweak to move page tabs into administration menu.
#287468 by sun: Fixed module paths directly below "admin" get the wrong parent.
#310423 by sun: Added optional position: fixed configuration setting.
#292657 by smk-ka: Improved rendering performance.
#234149 by yhager, sun: Fixed RTL support for IE.
#323726 by danez1972: Added Spanish translation.
#325057 by sun: Updated README.txt.
#234149 by yhager, levavie, sun: Added RTL support.
#325057 by sun: Added links to flush specific caches.
#324334 by AltaVida: Fixed usernames with spaces not in Devel user switch links.
#319382 by betz: Added Dutch translation.
Admin Menu 6.x-1.1, 2008-09-12
------------------------------
#295476 by pwolanin, use <front> for icon path to fix front-page path-change
bug and pathauto conflict, add wipe button to admin form.
#301370 by sun: Disabled module fieldset collapsing behavior by default.
#288672 by sun: Fixed JS hover behavior not working in IE.
#290803 by sun: Fixed missing devel_themer in devel modules; added some others.
#286636 by sun: Fixed menus do not drop down in IE6.
#249537 by pwolanin, sun: Added admin_menu_suppress() to allow other modules to
disable the display of admin_menu on certain pages (f.e. popups).
#268211 by sun: Fixed invalid issue queue links for custom modules and
sub-modules of projects.
#261461 by sun: Added FAQ entry for displaying other menus like admin_menu.
#264067 by sun: Added FAQ entry for huge amount of anonymous users displayed.
#280002 by pwolanin: Clean up .test setUp function.
#242377 by sun: Fixed sub-level menu items exceed total document height.
Admin Menu 6.x-1.0, 2008-06-26
------------------------------
#266308 by sun: Fixed jQuery 1.0.x incompatible selector for collapsing modules.
#268373 by sun: Added hook_update to cleanup for alpha/beta testers.
#268373 by sun: Added menu callback to disable/enable developer modules.
#132524 by pwolanin: Fixed admin_menu links are re-inserted each time menu links
are rebuilt.
by smk-ka: Performance: Use 'defer' attribute for JavaScript to delay execution.
#266099 by sun: Fixed description of "Apply margin-top" configuration setting.
#266308 by sun: Usability: Added Utility module features to collapse module
fieldsets on Modules page.
#251341 by sun: Added docs about display drupal links permission.
Admin Menu 6.x-1.0-BETA, 2008-06-08
-----------------------------------
#132524 by sun: Fixed support for sub-content-types below node/add.
#132524 by pwolanin: Added support for localizable menu links.
#132524 by pwolanin, sun: Fixed menu links adjustments.
#132524 by pwolanin: Added simpletest.
#132524 by pwolanin: Major rewrite to better use Drupal 6 menu system.
#132524 by sun: Moved gettext translation files into translations.
#132524 by sun: Committing pre-alpha code for D6 due to public demand.
Admin Menu 5.x-2.x, xxxx-xx-xx
------------------------------
#246221 by sun: Fixed user counter displays different values than Who's online
block.
#239022 by mikl: Added Danish translation.
#234444 by smk-ka: Fixed admin_menu icon does not respect theme settings.
#198240 by sun: Fixed admin_menu displayed in print output.
Admin Menu 5.x-2.4, 2008-02-24
------------------------------
#214740 by sun: Regression: Fixed directly applied marginTop not supported by IE.
#214725 by sun: Fixed wrong CSS id in admin_menu.js (missed in 5.x-2.3).
Admin Menu 5.x-2.3, 2008-02-24
------------------------------
#214725 by sun: Fixed CSS id and classes should not contain underscores.
#209390 by sun: Added note about interaction with user role permissions.
#214740 by jjeff, sun: Added module settings to configure margin-top CSS.
#200737 by sun: Changed admin_menu (fav)icon to use theme setting, if defined.
#203116 by smk-ka: Improved performance of non-cached admin_menu by storing
already processed URLs in the cache.
#224605 by sun: 'Add <content_type>' items do not appear without 'administer
nodes' permission.
#210615 by robertgarrigos: Fixed Mozilla Mac: Collapsible fieldsets display
error.
Admin Menu 5.x-2.2, 2007-01-08
------------------------------
#204884 by jjeff: Usability: Override theme font family declaration.
#204935 by jjeff: Added mouseout delay for hovered menus (yay!).
#193941 by downgang: Fixed margin in IE6 using Garland theme.
#197306 by sun: Fixed 'Run updates' leads to wrong url with clean URLs disabled.
Moved images into sub-folder.
by smk-ka: Fixed icon title for user counter not displayed & coding style.
Fixed user count not displayed without 'administer users' permission.
Admin Menu 5.x-2.1, 2007-12-02
------------------------------
Fixed adding menu items with negative weight not always working.
Fixed admin_menu_copy_items() is overwriting already existing items.
Fixed display menu item ids in devel settings does not work.
Admin Menu 5.x-2.0, 2007-12-02
------------------------------
Added devel_admin_menu() for fast access to clear-cache, variable editor and
switch_user.
Added username to logout button.
Added hook_admin_menu() to allow other modules to alter admin_menu.
#194189 by sun: Added counter for current anonymous/authenticated users.
Added Drupal.org project issue queue links for all enabled contrib modules.
#189701 by sun: Changed admin_menu icon to be a menu.
#193925 by sun: Removed obsolete menu slicing code.
#193669 by smk-ka: Moved admin_menu builder functions into include file.
Admin Menu 5.x-1.2, 2007-11-18
------------------------------
#176969 by smk-ka: Fixed performance issues with path(auto) module by
introducing a menu cache for admin_menu.
#179648 by sun: Inject admin_menu into theme.
Fixes several CSS bugs in various themes and also activation of admin_menu
immediately after installation.
#191213 by Standard: Fixed block info shouldn't contain the word "block".
#187816 by sun: Fixed "Add" not translatable.
#186218 by sun: Fixed admin menu icon too big in Safari.
#182563 by sun: Fixed wrong datatype for array_search in _admin_menu_get_children().
#183496 by sun: Fixed invalid argument supplied for foreach in admin_menu_copy_items().
Admin Menu 5.x-1.1, 2007-10-10
------------------------------
#178876 by sun: Fixed 3rd-level submenus expand without hover over.
#153455 by sun: Fixed add product node sub-elements are empty.
Fixed path_to_theme() call breaking blocks page.
#177582 by sun: Fixed bluebreeze theme compatibility.
Admin Menu 5.x-1.0, 2007-09-06
------------------------------
#156952 by sun: Fixed admin menu inaccessible due to margins.
#149229 by sun: Fixed admin menu not expanding in IE7.
#172545 by sun: Use opacity instead of -moz-opacity.
#132867 Fixed z-index too low.
- Fixed admin menu block selectors to override any other theme styles.
#155589 by sun: Added permission to access administration menu.
- Fixed a PHP warning when there are no content types defined in the system, as
node/add then has no child menu items.
#155312 by sun: Fixed menu item tooltip clashes.
Added support for custom stylesheets per theme.
Removed 4.7.x compatibility.
Admin Menu 4.7-1.3, 2007-03-30
------------------------------
#126601 Fixed Users can see inaccessible items.
#121027 Fixed Page not found entries for menu-collapsed.png.
Admin Menu 4.7-1.2, 2007-03-04
------------------------------
- Fixed menu item adjustments
- Fixed IE / Safari support
- Fixed base_path for IE support
- Added create content options to content management menu
Admin Menu 4.7-1.1, 2007-01-24
------------------------------
First stable release, compatible to Drupal 4.7.x and 5.x.
Admin Menu 4.7-1.0, 2007-01-16
------------------------------
Initial release of admin_menu module. Already supporting Drupal 5.0.

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,188 @@
-- SUMMARY --
The Administration menu module displays the entire administrative menu tree (and
most local tasks) in a drop-down menu, providing administrators one- or
two-click access to most pages. Other modules may also add menu links to the
menu using hook_admin_menu_output_alter().
For a full description of the module, visit the project page:
http://drupal.org/project/admin_menu
To submit bug reports and feature suggestions, or to track changes:
http://drupal.org/project/issues/admin_menu
-- REQUIREMENTS --
None.
-- INSTALLATION --
* Install as usual, see http://drupal.org/node/70151 for further information.
* You likely want to disable Toolbar module, since its output clashes with
Administration menu.
-- CONFIGURATION --
* Configure user permissions in Administration » People » Permissions:
- Use the administration pages and help (System module)
The top-level administration categories require this permission to be
accessible. The administration menu will be empty unless this permission is
granted.
- Access administration menu
Users in roles with the "Access administration menu" permission will see
the administration menu at the top of each page.
- Display Drupal links
Users in roles with the "Display drupal links" permission will receive
links to drupal.org issue queues for all enabled contributed modules. The
issue queue links appear under the administration menu icon.
Note that the menu items displayed in the administration menu depend on the
actual permissions of the viewing user. For example, the "People" menu item
is not displayed to a user who is not a member of a role with the "Administer
users" permission.
* Customize the menu settings in Administration » Configuration and modules »
Administration » Administration menu.
* To prevent administrative menu items from appearing twice, you may hide the
"Management" menu block.
-- CUSTOMIZATION --
* To override the default administration menu icon, you may:
1) Disable it via CSS in your theme:
body #admin-menu-icon { display: none; }
2) Alter the image by overriding the theme function:
Copy the entire theme_admin_menu_icon() function into your template.php,
rename it to phptemplate_admin_menu_icon() or THEMENAME_admin_menu_icon(),
and customize the output according to your needs.
Remember that the output of the administration menu is cached. To see changes
from your theme override function, you must clear your site cache (via
the "Flush all caches" link on the menu).
* To override the font size, add the following line to your theme's stylesheet:
body #admin-menu { font-size: 10px; }
-- TROUBLESHOOTING --
* If the menu does not display, check the following:
- Are the "Access administration menu" and "Use the administration pages and help"
permissions enabled for the appropriate roles?
- Does html.tpl.php of your theme output the $page_bottom variable?
* If the menu is rendered behind a Flash movie object, add this property to your
Flash object(s):
<param name="wmode" value="transparent" />
See http://drupal.org/node/195386 for further information.
-- FAQ --
Q: When the administration menu module is enabled, blank space is added to the
bottom of my theme. Why?
A: This is caused by a long list of links to module issue queues at Drupal.org.
Use Administer >> User management >> Permissions to disable the "display
drupal links" permission for all appropriate roles. Note that since UID 1
automatically receives all permissions, the list of issue queue links cannot
be disabled for UID 1.
Q: After upgrading to 6.x-1.x, the menu disappeared. Why?
A: You may need to regenerate your menu. Visit
http://example.com/admin/build/modules to regenerate your menu (substitute
your site name for example.com).
Q: Can I configure the administration menu module to display another menu (like
the Navigation menu, for instance)?
A: No. As the name implies, administration menu module is for administrative
menu links only. However, you can copy and paste the contents of
admin_menu.css into your theme's stylesheet and replace #admin-menu with any
other menu block id (#block-menu-1, for example).
Q: Sometimes, the user counter displays a lot of anonymous users, but no spike
of users or requests appear in Google Analytics or other tracking tools.
A: If your site was concurrently spidered by search-engine robots, it may have
a significant number of anonymous users for a short time. Most web tracking
tools like Google Analytics automatically filter out these requests.
Q: I enabled "Aggregate and compress CSS files", but admin_menu.css is still
there. Is this normal?
A: Yes, this is the intended behavior. the administration menu module only loads
its stylesheet as needed (i.e., on page requests by logged-on, administrative
users).
Q: Why are sub-menus not visible in Opera?
A: In the Opera browser preferences under "web pages" there is an option to fit
to width. By disabling this option, sub-menus in the administration menu
should appear.
Q: How can the administration menu be hidden on certain pages?
A: You can suppress it by simply calling the following function in PHP:
module_invoke('admin_menu', 'suppress');
However, this needs to happen as early as possible in the page request, so
placing it in the theming layer (resp. a page template file) is too late.
Ideally, the function is called in hook_init() in a custom module. If you do
not have a custom module, placing it into some conditional code at the top of
template.php may work out, too.
-- CONTACT --
Current maintainers:
* Daniel F. Kudwien (sun) - http://drupal.org/user/54136
* Peter Wolanin (pwolanin) - http://drupal.org/user/49851
* Stefan M. Kudwien (smk-ka) - http://drupal.org/user/48898
* Dave Reid (Dave Reid) - http://drupal.org/user/53892
Major rewrite for Drupal 6 by Peter Wolanin (pwolanin).
This project has been sponsored by:
* UNLEASHED MIND
Specialized in consulting and planning of Drupal powered sites, UNLEASHED
MIND offers installation, development, theming, customization, and hosting
to get you started. Visit http://www.unleashedmind.com for more information.
* Lullabot
Friendly Drupal experts providing professional consulting & education
services. Visit http://www.lullabot.com for more information.
* Acquia
Commercially Supported Drupal. Visit http://acquia.com for more information.

View File

@@ -0,0 +1,12 @@
name = Administration Development tools
description = Administration and debugging functionality for developers and site builders.
package = Administration
core = 7.x
scripts[] = admin_devel.js
; Information added by drupal.org packaging script on 2013-01-31
version = "7.x-3.0-rc4"
core = "7.x"
project = "admin_menu"
datestamp = "1359651687"

View File

@@ -0,0 +1,40 @@
(function($) {
/**
* jQuery debugging helper.
*
* Invented for Dreditor.
*
* @usage
* $.debug(var [, name]);
* $variable.debug( [name] );
*/
jQuery.extend({
debug: function () {
// Setup debug storage in global window. We want to look into it.
window.debug = window.debug || [];
args = jQuery.makeArray(arguments);
// Determine data source; this is an object for $variable.debug().
// Also determine the identifier to store data with.
if (typeof this == 'object') {
var name = (args.length ? args[0] : window.debug.length);
var data = this;
}
else {
var name = (args.length > 1 ? args.pop() : window.debug.length);
var data = args[0];
}
// Store data.
window.debug[name] = data;
// Dump data into Firebug console.
if (typeof console != 'undefined') {
console.log(name, data);
}
return this;
}
});
// @todo Is this the right way?
jQuery.fn.debug = jQuery.debug;
})(jQuery);

View File

@@ -0,0 +1,33 @@
<?php
/**
* @file
* Administration and debugging functionality for developers and site builders.
*/
/**
* Implements hook_form_FORMID_alter().
*/
function admin_devel_form_admin_menu_theme_settings_alter(&$form, &$form_state) {
$form['actions']['wipe_rebuild'] = array(
'#type' => 'submit',
'#value' => t('Rebuild system links'),
'#submit' => array('admin_devel_form_admin_menu_theme_settings_alter_rebuild_submit'),
// @todo Not necessarily ready for mass-consumption yet.
'#access' => FALSE,
);
}
/**
* Form submit handler to wipe and rebuild all 'module' = 'system' menu links.
*/
function admin_devel_form_admin_menu_theme_settings_alter_rebuild_submit($form, &$form_state) {
// Delete all auto-generated menu links derived from menu router items.
db_delete('menu_links')
->condition('module', 'system')
->execute();
// Rebuild menu links from current menu router items.
menu_rebuild();
drupal_set_message(t('System links derived from menu router paths have been rebuilt.'));
}

View File

@@ -0,0 +1,64 @@
#admin-menu {
text-align: right;
}
#admin-menu .dropdown .admin-menu-users a {
background-position: 10% center;
padding-left: 22px;
padding-right: 0;
}
#admin-menu .dropdown .admin-menu-action,
#admin-menu .dropdown .admin-menu-search {
float: left;
}
#admin-menu .dropdown .admin-menu-action a {
border-left: none;
border-right: 1px solid #323232;
}
/* All lists */
#admin-menu a {
text-align: right;
}
#admin-menu .dropdown a {
border-left: 1px solid #323232;
border-right: 0;
}
#admin-menu .dropdown .admin-menu-tab a {
border-left: 1px solid #52565E;
border-right: 0;
}
#admin-menu .dropdown li li a {
border-left: 0;
}
/* All list items */
#admin-menu .dropdown li {
float: right;
}
#admin-menu .dropdown li li {
}
/* Second-level lists */
#admin-menu .dropdown li ul {
left: auto;
right: -999em;
}
/* Third-and-above-level lists */
#admin-menu .dropdown li li.expandable ul {
margin-left: 0;
margin-right: 160px;
}
/* Lists nested under hovered list items */
#admin-menu .dropdown li.admin-menu-action:hover ul {
left: 0 !important;
right: auto;
}
/* Second-and-more-level hovering */
#admin-menu .dropdown li li.expandable {
background-image: url(images/arrow-rtl.png);
background-position: 5px 6px;
}

View File

@@ -0,0 +1,62 @@
(function($) {
/**
* Live preview of Administration menu components.
*/
Drupal.behaviors.adminMenuLivePreview = {
attach: function (context, settings) {
$('input[name^="admin_menu_components"]', context).once('admin-menu-live-preview')
.change(function () {
var target = $(this).attr('rel');
$(target).toggle(this.checked);
})
.trigger('change');
}
};
/**
* Automatically enables required permissions on demand.
*
* Many users do not understand that two permissions are required for the
* administration menu to appear. Since Drupal core provides no facility for
* this, we implement a simple manual confirmation for automatically enabling
* the "other" permission.
*/
Drupal.behaviors.adminMenuPermissionsSetupHelp = {
attach: function (context, settings) {
$('#permissions', context).once('admin-menu-permissions-setup', function () {
// Retrieve matrix/mapping - these need to use the same indexes for the
// same permissions and roles.
var $roles = $(this).find('th:not(:first)');
var $admin = $(this).find('input[name$="[access administration pages]"]');
var $menu = $(this).find('input[name$="[access administration menu]"]');
// Retrieve the permission label - without description.
var adminPermission = $.trim($admin.eq(0).parents('td').prev().children().get(0).firstChild.textContent);
var menuPermission = $.trim($menu.eq(0).parents('td').prev().children().get(0).firstChild.textContent);
$admin.each(function (index) {
// Only proceed if both are not enabled already.
if (!(this.checked && $menu[index].checked)) {
// Stack both checkboxes and attach a click event handler to both.
$(this).add($menu[index]).click(function () {
// Do nothing when disabling a permission.
if (this.checked) {
// Figure out which is the other, check whether it still disabled,
// and if so, ask whether to auto-enable it.
var other = (this == $admin[index] ? $menu[index] : $admin[index]);
if (!other.checked && confirm(Drupal.t('Also allow !name role to !permission?', {
'!name': $roles[index].textContent,
'!permission': (this == $admin[index] ? menuPermission : adminPermission)
}))) {
other.checked = 'checked';
}
}
});
}
});
});
}
};
})(jQuery);

View File

@@ -0,0 +1,164 @@
<?php
/**
* @file
* API documentation for Administration menu.
*/
/**
* Provide expansion arguments for dynamic menu items.
*
* The map items must be keyed by the dynamic path to expand, i.e. a menu path
* containing one or more '%' placeholders. Each map item may have the following
* properties:
* - parent: The parent menu path to link the expanded items to.
* - arguments: An array of argument sets that will be used in the expansion.
* Each set consists of an array of one or more placeholders, which again is
* an array of possible expansion values. Upon expansion, each argument is
* combined with every other argument from the set (technically, the cartesian
* product of all arguments). The expansion values may be empty; that is, you
* do not need to insert logic to skip map items for which no values exist,
* since Administration menu will take care of that.
*
* @see admin_menu.map.inc
*/
function hook_admin_menu_map() {
// Expand content types below Structure > Content types.
// The key denotes the dynamic path to expand to multiple menu items.
$map['admin/structure/types/manage/%node_type'] = array(
// Link generated items directly to the "Content types" item.
'parent' => 'admin/structure/types',
// Create expansion arguments for the '%node_type' placeholder.
'arguments' => array(
array(
'%node_type' => array_keys(node_type_get_types()),
),
),
);
return $map;
}
/**
* Add to the administration menu content before it is rendered.
*
* Only use this hook to add new data to the menu structure. Use
* hook_admin_menu_output_alter() to *alter* existing data.
*
* @param array $content
* A structured array suitable for drupal_render(), potentially containing:
* - menu: The administrative menu of links below the path 'admin/*'.
* - icon: The icon menu.
* - account: The user account name and log out link.
* - users: The user counter.
* Additionally, these special properties:
* - #components: The actual components contained in $content are configurable
* and depend on the 'admin_menu_components' configuration value. #components
* holds a copy of that for convenience.
* - #complete: A Boolean indicating whether the complete menu should be built,
* ignoring the current configuration in #components.
* Passed by reference.
*
* @see hook_admin_menu_output_alter()
* @see admin_menu_links_menu()
* @see admin_menu_links_icon()
* @see admin_menu_links_user()
* @see theme_admin_menu_links()
*/
function hook_admin_menu_output_build(&$content) {
// In case your implementation provides a configurable component, check
// whether the component should be displayed:
if (empty($content['#components']['shortcut.links']) && !$content['#complete']) {
return;
}
// Add new top-level item to the menu.
if (isset($content['menu'])) {
$content['menu']['myitem'] = array(
'#title' => t('My item'),
// #attributes are used for list items (LI).
'#attributes' => array('class' => array('mymodule-myitem')),
'#href' => 'mymodule/path',
// #options are passed to l().
'#options' => array(
'query' => drupal_get_destination(),
// Apply a class on the link (anchor).
'attributes' => array('class' => array('myitem-link-anchor')),
),
// #weight controls the order of links in the resulting item list.
'#weight' => 50,
);
}
// Add link to the icon menu to manually run cron.
if (isset($content['icon'])) {
$content['icon']['myitem']['cron'] = array(
'#title' => t('Run cron'),
'#access' => user_access('administer site configuration'),
'#href' => 'admin/reports/status/run-cron',
);
}
}
/**
* Change the administration menu content before it is rendered.
*
* Only use this hook to alter existing data in the menu structure. Use
* hook_admin_menu_output_build() to *add* new data.
*
* @param array $content
* A structured array suitable for drupal_render(). Passed by reference.
*
* @see hook_admin_menu_output_build()
*/
function hook_admin_menu_output_alter(&$content) {
}
/**
* Return content to be replace via JS in the cached menu output.
*
* @param bool $complete
* A Boolean indicating whether all available components of the menu will be
* output and the cache will be skipped.
*
* @return array
* An associative array whose keys are jQuery selectors and whose values are
* strings containing the replacement content.
*/
function hook_admin_menu_replacements($complete) {
$items = array();
// If the complete menu is output, then it is uncached and will contain the
// current counts already.
if (!$complete) {
// Check whether the users count component is enabled.
$components = variable_get('admin_menu_components', array());
if (!empty($components['admin_menu.users']) && ($user_count = admin_menu_get_user_count())) {
// Replace the counters in the cached menu output with current counts.
$items['.admin-menu-users a'] = $user_count;
}
}
return $items;
}
/**
* Inform about additional module-specific caches that can be cleared.
*
* Administration menu uses this hook to gather information about available
* caches that can be flushed individually. Each returned item forms a separate
* menu link below the "Flush all caches" link in the icon menu.
*
* @return array
* An associative array whose keys denote internal identifiers for a
* particular caches (which can be freely defined, but should be in a module's
* namespace) and whose values are associative arrays containing:
* - title: The name of the cache, without "cache" suffix. This label is
* output as link text, but also for the "!title cache cleared."
* confirmation message after flushing the cache; make sure it works and
* makes sense to users in both locations.
* - callback: The name of a function to invoke to flush the individual cache.
*/
function hook_admin_menu_cache_info() {
$caches['update'] = array(
'title' => t('Update data'),
'callback' => '_update_cache_clear',
);
return $caches;
}

View File

@@ -0,0 +1,46 @@
/**
* @file
* Administration menu color override.
*/
#admin-menu {
background-color: #911;
background-image: url(images/bkg-red.png);
}
#admin-menu li.admin-menu-action a {
border-left-color: #a91f1f;
}
/* All lists */
#admin-menu ul a {
border-right-color: #a91f1f;
}
#admin-menu ul li.admin-menu-tab a {
border-right-color: #52565E;
}
#admin-menu li li a {
border-top-color: #801f1f;
}
/* All list items */
#admin-menu li li {
background-color: #991f1f;
}
/* Second-and-more-level hovering */
#admin-menu li li.expandable {
background-color: #b93f3f;
}
#admin-menu li li:hover,
#admin-menu li li.iehover {
background-color: #690f0f;
}
#admin-menu li li.expandable:hover a,
#admin-menu li li.expandable:hover li.expandable:hover a {
border-color: #801f1f;
}
#admin-menu li li.expandable:hover li a,
#admin-menu li li.expandable:hover li.expandable:hover li a {
border-color: #801f1f;
}

View File

@@ -0,0 +1,250 @@
/**
* @file
* Administration menu.
*
* Implementation of Sons of Suckerfish Dropdowns.
*
* @see www.htmldog.com/articles/suckerfish
*/
#admin-menu {
background: #101010 url(images/bkg.png) bottom left repeat-x;
font-size: 9px;
font-family: "lucida grande", tahoma, verdana, arial, sans-serif;
left: 0;
position: absolute;
text-align: left;
top: 0;
width: 100%;
}
#admin-menu-wrapper {
overflow: hidden;
}
#admin-menu .dropdown .admin-menu-icon a {
padding: 1px 8px 4px;
}
#admin-menu .dropdown .admin-menu-icon ul a {
padding: 4px 8px;
}
#admin-menu .dropdown .admin-menu-icon img {
vertical-align: bottom;
}
#admin-menu .dropdown .admin-menu-users a {
background: transparent url(images/icon_users.png) 90% center no-repeat;
padding-right: 22px;
}
#admin-menu .dropdown .admin-menu-action,
#admin-menu .dropdown .admin-menu-search {
float: right;
}
#admin-menu .dropdown .admin-menu-action a {
border-left: 1px solid #323232;
border-right: none;
}
body.admin-menu {
margin-top: 20px !important;
}
/* All lists */
#admin-menu,
#admin-menu .dropdown {
line-height: 1.4em;
list-style: none;
margin: 0;
padding: 0;
z-index: 999;
}
#admin-menu .dropdown {
position: static;
}
#admin-menu a,
#admin-menu li > span {
background: transparent none;
border: none;
color: #EEE;
font-weight: normal;
text-align: left; /* LTR */
text-decoration: none;
}
#admin-menu .dropdown a,
#admin-menu .dropdown li > span {
border-right: 1px solid #323232; /* LTR */
display: block;
padding: 4px 8px;
}
#admin-menu .dropdown .admin-menu-tab a {
border-right: 1px solid #52565E; /* LTR */
}
#admin-menu .dropdown li li a {
border-right: none; /* LTR */
border-top: 1px solid #323232;
}
/* All list items */
#admin-menu .dropdown li {
background-image: none;
float: left; /* LTR */
height: 100%;
list-style-image: none;
list-style-type: none;
margin: 0 !important;
padding: 0;
}
#admin-menu .dropdown .admin-menu-tab {
background: url(images/bkg_tab.png) repeat-x left bottom;
padding-bottom: 1px;
}
#admin-menu .dropdown li li {
background: #202020;
filter: Alpha(opacity=88);
opacity: 0.88;
width: 160px; /* Required for Opera */
}
#admin-menu .dropdown li li li {
filter: Alpha(opacity=100);
opacity: 1;
}
/* Second-level lists */
/* Note: We must hide sub-lists or scrollbars might appear (display: none is not read by screen readers). */
#admin-menu .dropdown li ul {
background: none;
display: none;
left: -999em; /* LTR */
line-height: 1.2em;
margin: 0;
position: absolute;
width: 160px;
}
/* Third-and-above-level lists */
#admin-menu .dropdown li li.expandable ul {
margin: -20px 0 0 160px; /* LTR */
}
#admin-menu .dropdown li:hover ul ul,
#admin-menu .dropdown li:hover ul ul ul,
#admin-menu .dropdown li:hover ul ul ul ul,
#admin-menu .dropdown li:hover ul ul ul ul ul,
#admin-menu .dropdown li.iehover ul ul,
#admin-menu .dropdown li.iehover ul ul ul,
#admin-menu .dropdown li.iehover ul ul ul ul,
#admin-menu .dropdown li.iehover ul ul ul ul ul {
display: none;
left: -999em; /* LTR */
}
/* Lists nested under hovered list items */
#admin-menu .dropdown li:hover ul,
#admin-menu .dropdown li li:hover ul,
#admin-menu .dropdown li li li:hover ul,
#admin-menu .dropdown li li li li:hover ul,
#admin-menu .dropdown li li li li li:hover ul,
#admin-menu .dropdown li.iehover ul,
#admin-menu .dropdown li li.iehover ul,
#admin-menu .dropdown li li li.iehover ul,
#admin-menu .dropdown li li li li.iehover ul,
#admin-menu .dropdown li li li li li.iehover ul {
display: block;
left: auto; /* LTR */
}
#admin-menu .dropdown li.admin-menu-action:hover ul {
right: 0; /* LTR */
}
/* Second-and-more-level hovering */
#admin-menu .dropdown li li.expandable {
background: #45454A url(images/arrow.png) no-repeat 145px 6px;
}
#admin-menu .dropdown li li:hover,
#admin-menu .dropdown li li.iehover {
background-color: #111;
}
#admin-menu .dropdown li li:hover a,
#admin-menu .dropdown li li:hover li:hover a,
#admin-menu .dropdown li li:hover li:hover li:hover a {
color: #FFF;
}
#admin-menu .dropdown li li.expandable:hover a,
#admin-menu .dropdown li li.expandable:hover li.expandable:hover a {
border-color: #444;
color: #EEE;
}
#admin-menu .dropdown li li.expandable:hover li a,
#admin-menu .dropdown li li.expandable:hover li.expandable:hover li a {
border-color: #323232;
}
#admin-menu .dropdown li li:hover li a,
#admin-menu .dropdown li li.iehover li a,
#admin-menu .dropdown li li.iehover li.iehover li a {
color: #EEE;
}
#admin-menu .dropdown li li.iehover a,
#admin-menu .dropdown li li.iehover li.iehover a,
#admin-menu .dropdown li li.iehover li.iehover li.iehover a {
color: #FFF;
width: 90%; /* IE */
}
/* Search form */
#admin-menu .admin-menu-search .form-item {
margin: 0;
padding: 0;
}
#admin-menu .admin-menu-search input {
background: #fff none center right no-repeat;
border: none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
font-size: 10px;
margin: 1px 0;
outline: none;
padding: 2px 22px 2px 4px;
width: 158px;
}
#admin-menu .dropdown .admin-menu-search-results {
display: block !important;
left: auto !important;
top: 100%;
}
#admin-menu .admin-menu-search-results,
#admin-menu .admin-menu-search-results li {
width: 186px;
}
#admin-menu li.highlight {
background-color: #eee !important;
}
#admin-menu li.highlight > a {
border-color: #ccc !important;
color: #111 !important;
}
/* #210615: Mozilla on Mac fix */
html.js fieldset.collapsible div.fieldset-wrapper {
overflow: visible;
}
/* Hide the menu on print output. */
@media print {
#admin-menu {
display: none !important;
}
body.admin-menu {
margin-top: 0 !important;
}
}
/**
* Tweaks permissions, if enabled.
*/
tr.admin-menu-tweak-permissions-processed {
cursor: pointer;
cursor: hand;
}
tr.admin-menu-tweak-permissions-processed td.module {
border-top: 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
name = Administration menu
description = "Provides a dropdown menu to most administrative tasks and other common destinations (to users with the proper permissions)."
package = Administration
core = 7.x
configure = admin/config/administration/admin_menu
; Requires menu_build_tree() conditions; available after 7.10.
; @see http://drupal.org/node/1025582
dependencies[] = system (>7.10)
files[] = tests/admin_menu.test
; Information added by drupal.org packaging script on 2013-01-31
version = "7.x-3.0-rc4"
core = "7.x"
project = "admin_menu"
datestamp = "1359651687"

View File

@@ -0,0 +1,122 @@
<?php
/**
* @file
* Install, update, and uninstall functions for the admin menu module.
*/
/**
* Implements hook_schema().
*/
function admin_menu_schema() {
$schema['cache_admin_menu'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_admin_menu']['description'] = 'Cache table for Administration menu to store client-side caching hashes.';
return $schema;
}
/**
* Implements hook_install().
*/
function admin_menu_install() {
// Increase the module weight, so admin_menu catches any alterations made by
// other modules in hook_menu_alter().
db_update('system')
->fields(array('weight' => 100))
->condition('type', 'module')
->condition('name', 'admin_menu')
->execute();
}
/**
* Implements hook_uninstall().
*/
function admin_menu_uninstall() {
// Delete variables.
variable_del('admin_menu_components');
variable_del('admin_menu_devel_modules');
variable_del('admin_menu_devel_modules_enabled');
variable_del('admin_menu_devel_modules_skip');
variable_del('admin_menu_margin_top');
variable_del('admin_menu_position_fixed');
variable_del('admin_menu_tweak_modules');
variable_del('admin_menu_tweak_tabs');
variable_del('admin_menu_show_all');
variable_del('admin_menu_display');
variable_del('admin_menu_cache_server');
variable_del('admin_menu_cache_client');
}
/**
* Ensure that admin_menu is rebuilt after upgrading to D6.
*/
function admin_menu_update_6000() {
// Drop the {admin_menu} table in admin_menu_update_6000() on sites that used
// one of the later patches in #132524.
if (db_table_exists('admin_menu')) {
db_drop_table('admin_menu');
}
}
/**
* Wipe and rebuild so we can switch the icon path to <front>.
*/
function admin_menu_update_6001() {
db_delete('menu_links')->condition('module', 'admin_menu')->execute();
menu_cache_clear('admin_menu');
}
/**
* Add {cache_admin_menu} table.
*/
function admin_menu_update_7300() {
if (!db_table_exists('cache_admin_menu')) {
$schema = drupal_get_schema_unprocessed('system', 'cache');
db_create_table('cache_admin_menu', $schema);
}
}
/**
* Increase the module weight.
*
* @see admin_menu_install()
*/
function admin_menu_update_7302() {
db_update('system')
->fields(array('weight' => 100))
->condition('type', 'module')
->condition('name', 'admin_menu')
->execute();
}
/**
* Remove local tasks from {menu_links} table.
*/
function admin_menu_update_7303() {
db_delete('menu_router')
->condition('path', 'admin/%', 'LIKE')
->condition('type', MENU_IS_LOCAL_TASK, '&')
->execute();
}
/**
* Remove obsolete 'admin_menu' menu and all orphan links in it.
*/
function admin_menu_update_7304() {
// Remove the custom menu used by 6.x-1.x.
if (db_table_exists('menu_custom')) {
db_delete('menu_custom')->condition('menu_name', 'admin_menu')->execute();
}
// 6.x-1.x cloned the entire link structure below the path 'admin' into a
// separate 'menu_name' "admin_menu" with 'module' "admin_menu". 6.x-3.x and
// early alpha versions of 7.x-3.x still did something similar. All of these
// records are obsolete. Removal of the 'module' records (without different
// menu_name) is particularly important, since they would otherwise appear
// as duplicate links.
db_delete('menu_links')
->condition(db_or()
->condition('module', 'admin_menu')
->condition('menu_name', 'admin_menu')
)
->execute();
}

View File

@@ -0,0 +1,397 @@
(function($) {
Drupal.admin = Drupal.admin || {};
Drupal.admin.behaviors = Drupal.admin.behaviors || {};
Drupal.admin.hashes = Drupal.admin.hashes || {};
/**
* Core behavior for Administration menu.
*
* Test whether there is an administration menu is in the output and execute all
* registered behaviors.
*/
Drupal.behaviors.adminMenu = {
attach: function (context, settings) {
// Initialize settings.
settings.admin_menu = $.extend({
suppress: false,
margin_top: false,
position_fixed: false,
tweak_modules: false,
tweak_permissions: false,
tweak_tabs: false,
destination: '',
basePath: settings.basePath,
hash: 0,
replacements: {}
}, settings.admin_menu || {});
// Check whether administration menu should be suppressed.
if (settings.admin_menu.suppress) {
return;
}
var $adminMenu = $('#admin-menu:not(.admin-menu-processed)', context);
// Client-side caching; if administration menu is not in the output, it is
// fetched from the server and cached in the browser.
if (!$adminMenu.length && settings.admin_menu.hash) {
Drupal.admin.getCache(settings.admin_menu.hash, function (response) {
if (typeof response == 'string' && response.length > 0) {
$('body', context).append(response);
}
var $adminMenu = $('#admin-menu:not(.admin-menu-processed)', context);
// Apply our behaviors.
Drupal.admin.attachBehaviors(context, settings, $adminMenu);
// Allow resize event handlers to recalculate sizes/positions.
$(window).triggerHandler('resize');
});
}
// If the menu is in the output already, this means there is a new version.
else {
// Apply our behaviors.
Drupal.admin.attachBehaviors(context, settings, $adminMenu);
}
}
};
/**
* Collapse fieldsets on Modules page.
*/
Drupal.behaviors.adminMenuCollapseModules = {
attach: function (context, settings) {
if (settings.admin_menu.tweak_modules) {
$('#system-modules fieldset:not(.collapsed)', context).addClass('collapsed');
}
}
};
/**
* Collapse modules on Permissions page.
*/
Drupal.behaviors.adminMenuCollapsePermissions = {
attach: function (context, settings) {
if (settings.admin_menu.tweak_permissions) {
// Freeze width of first column to prevent jumping.
$('#permissions th:first', context).css({ width: $('#permissions th:first', context).width() });
// Attach click handler.
$modules = $('#permissions tr:has(td.module)', context).once('admin-menu-tweak-permissions', function () {
var $module = $(this);
$module.bind('click.admin-menu', function () {
// @todo Replace with .nextUntil() in jQuery 1.4.
$module.nextAll().each(function () {
var $row = $(this);
if ($row.is(':has(td.module)')) {
return false;
}
$row.toggleClass('element-hidden');
});
});
});
// Collapse all but the targeted permission rows set.
if (window.location.hash.length) {
$modules = $modules.not(':has(' + window.location.hash + ')');
}
$modules.trigger('click.admin-menu');
}
}
};
/**
* Apply margin to page.
*
* Note that directly applying marginTop does not work in IE. To prevent
* flickering/jumping page content with client-side caching, this is a regular
* Drupal behavior.
*/
Drupal.behaviors.adminMenuMarginTop = {
attach: function (context, settings) {
if (!settings.admin_menu.suppress && settings.admin_menu.margin_top) {
$('body:not(.admin-menu)', context).addClass('admin-menu');
}
}
};
/**
* Retrieve content from client-side cache.
*
* @param hash
* The md5 hash of the content to retrieve.
* @param onSuccess
* A callback function invoked when the cache request was successful.
*/
Drupal.admin.getCache = function (hash, onSuccess) {
if (Drupal.admin.hashes.hash !== undefined) {
return Drupal.admin.hashes.hash;
}
$.ajax({
cache: true,
type: 'GET',
dataType: 'text', // Prevent auto-evaluation of response.
global: false, // Do not trigger global AJAX events.
url: Drupal.settings.admin_menu.basePath.replace(/admin_menu/, 'js/admin_menu/cache/' + hash),
success: onSuccess,
complete: function (XMLHttpRequest, status) {
Drupal.admin.hashes.hash = status;
}
});
};
/**
* TableHeader callback to determine top viewport offset.
*
* @see toolbar.js
*/
Drupal.admin.height = function() {
var $adminMenu = $('#admin-menu');
var height = $adminMenu.outerHeight();
// In IE, Shadow filter adds some extra height, so we need to remove it from
// the returned height.
if ($adminMenu.css('filter') && $adminMenu.css('filter').match(/DXImageTransform\.Microsoft\.Shadow/)) {
height -= $adminMenu.get(0).filters.item("DXImageTransform.Microsoft.Shadow").strength;
}
return height;
};
/**
* @defgroup admin_behaviors Administration behaviors.
* @{
*/
/**
* Attach administrative behaviors.
*/
Drupal.admin.attachBehaviors = function (context, settings, $adminMenu) {
if ($adminMenu.length) {
$adminMenu.addClass('admin-menu-processed');
$.each(Drupal.admin.behaviors, function() {
this(context, settings, $adminMenu);
});
}
};
/**
* Apply 'position: fixed'.
*/
Drupal.admin.behaviors.positionFixed = function (context, settings, $adminMenu) {
if (settings.admin_menu.position_fixed) {
$adminMenu.addClass('admin-menu-position-fixed');
$adminMenu.css('position', 'fixed');
}
};
/**
* Move page tabs into administration menu.
*/
Drupal.admin.behaviors.pageTabs = function (context, settings, $adminMenu) {
if (settings.admin_menu.tweak_tabs) {
var $tabs = $(context).find('ul.tabs.primary');
$adminMenu.find('#admin-menu-wrapper > ul').eq(1)
.append($tabs.find('li').addClass('admin-menu-tab'));
$(context).find('ul.tabs.secondary')
.appendTo('#admin-menu-wrapper > ul > li.admin-menu-tab.active')
.removeClass('secondary');
$tabs.remove();
}
};
/**
* Perform dynamic replacements in cached menu.
*/
Drupal.admin.behaviors.replacements = function (context, settings, $adminMenu) {
for (var item in settings.admin_menu.replacements) {
$(item, $adminMenu).html(settings.admin_menu.replacements[item]);
}
};
/**
* Inject destination query strings for current page.
*/
Drupal.admin.behaviors.destination = function (context, settings, $adminMenu) {
if (settings.admin_menu.destination) {
$('a.admin-menu-destination', $adminMenu).each(function() {
this.search += (!this.search.length ? '?' : '&') + Drupal.settings.admin_menu.destination;
});
}
};
/**
* Apply JavaScript-based hovering behaviors.
*
* @todo This has to run last. If another script registers additional behaviors
* it will not run last.
*/
Drupal.admin.behaviors.hover = function (context, settings, $adminMenu) {
// Hover emulation for IE 6.
if ($.browser.msie && parseInt(jQuery.browser.version) == 6) {
$('li', $adminMenu).hover(
function () {
$(this).addClass('iehover');
},
function () {
$(this).removeClass('iehover');
}
);
}
// Delayed mouseout.
$('li.expandable', $adminMenu).hover(
function () {
// Stop the timer.
clearTimeout(this.sfTimer);
// Display child lists.
$('> ul', this)
.css({left: 'auto', display: 'block'})
// Immediately hide nephew lists.
.parent().siblings('li').children('ul').css({left: '-999em', display: 'none'});
},
function () {
// Start the timer.
var uls = $('> ul', this);
this.sfTimer = setTimeout(function () {
uls.css({left: '-999em', display: 'none'});
}, 400);
}
);
};
/**
* Apply the search bar functionality.
*/
Drupal.admin.behaviors.search = function (context, settings, $adminMenu) {
// @todo Add a HTML ID.
var $input = $('input.admin-menu-search', $adminMenu);
// Initialize the current search needle.
var needle = $input.val();
// Cache of all links that can be matched in the menu.
var links;
// Minimum search needle length.
var needleMinLength = 2;
// Append the results container.
var $results = $('<div />').insertAfter($input);
/**
* Executes the search upon user input.
*/
function keyupHandler() {
var matches, $html, value = $(this).val();
// Only proceed if the search needle has changed.
if (value !== needle) {
needle = value;
// Initialize the cache of menu links upon first search.
if (!links && needle.length >= needleMinLength) {
// @todo Limit to links in dropdown menus; i.e., skip menu additions.
links = buildSearchIndex($adminMenu.find('li:not(.admin-menu-action, .admin-menu-action li) > a'));
}
// Empty results container when deleting search text.
if (needle.length < needleMinLength) {
$results.empty();
}
// Only search if the needle is long enough.
if (needle.length >= needleMinLength && links) {
matches = findMatches(needle, links);
// Build the list in a detached DOM node.
$html = buildResultsList(matches);
// Display results.
$results.empty().append($html);
}
}
}
/**
* Builds the search index.
*/
function buildSearchIndex($links) {
return $links
.map(function () {
var text = (this.textContent || this.innerText);
// Skip menu entries that do not contain any text (e.g., the icon).
if (typeof text === 'undefined') {
return;
}
return {
text: text,
textMatch: text.toLowerCase(),
element: this
};
});
}
/**
* Searches the index for a given needle and returns matching entries.
*/
function findMatches(needle, links) {
var needleMatch = needle.toLowerCase();
// Select matching links from the cache.
return $.grep(links, function (link) {
return link.textMatch.indexOf(needleMatch) !== -1;
});
}
/**
* Builds the search result list in a detached DOM node.
*/
function buildResultsList(matches) {
var $html = $('<ul class="dropdown admin-menu-search-results" />');
$.each(matches, function () {
var result = this.text;
var $element = $(this.element);
// Check whether there is a top-level category that can be prepended.
var $category = $element.closest('#admin-menu-wrapper > ul > li');
var categoryText = $category.find('> a').text()
if ($category.length && categoryText) {
result = categoryText + ': ' + result;
}
var $result = $('<li><a href="' + $element.attr('href') + '">' + result + '</a></li>');
$result.data('original-link', $(this.element).parent());
$html.append($result);
});
return $html;
}
/**
* Highlights selected result.
*/
function resultsHandler(e) {
var $this = $(this);
var show = e.type === 'mouseenter' || e.type === 'focusin';
$this.trigger(show ? 'showPath' : 'hidePath', [this]);
}
/**
* Closes the search results and clears the search input.
*/
function resultsClickHandler(e, link) {
var $original = $(this).data('original-link');
$original.trigger('mouseleave');
$input.val('').trigger('keyup');
}
/**
* Shows the link in the menu that corresponds to a search result.
*/
function highlightPathHandler(e, link) {
if (link) {
var $original = $(link).data('original-link');
var show = e.type === 'showPath';
// Toggle an additional CSS class to visually highlight the matching link.
// @todo Consider using same visual appearance as regular hover.
$original.toggleClass('highlight', show);
$original.trigger(show ? 'mouseenter' : 'mouseleave');
}
}
// Attach showPath/hidePath handler to search result entries.
$results.delegate('li', 'mouseenter mouseleave focus blur', resultsHandler);
// Hide the result list after a link has been clicked, useful for overlay.
$results.delegate('li', 'click', resultsClickHandler);
// Attach hover/active highlight behavior to search result entries.
$adminMenu.delegate('.admin-menu-search-results li', 'showPath hidePath', highlightPathHandler);
// Attach the search input event handler.
$input.bind('keyup search', keyupHandler);
};
/**
* @} End of "defgroup admin_behaviors".
*/
})(jQuery);

View File

@@ -0,0 +1,164 @@
<?php
/**
* @file
* Implements hook_admin_menu_map() on behalf of core modules.
*
* @todo Replace all/most of those API functions with direct DB queries;
* we only need the menu arguments (keys), not fully loaded objects.
*/
/**
* Implements hook_admin_menu_map() on behalf of Filter module.
*/
function filter_admin_menu_map() {
if (!user_access('administer filters')) {
return;
}
$map['admin/config/content/formats/%filter_format'] = array(
'parent' => 'admin/config/content/formats',
'arguments' => array(
array('%filter_format' => array_keys(filter_formats())),
),
);
return $map;
}
/**
* Implements hook_admin_menu_map() on behalf of Menu module.
*/
function menu_admin_menu_map() {
if (!user_access('administer menu')) {
return;
}
$map['admin/structure/menu/manage/%menu'] = array(
'parent' => 'admin/structure/menu',
'arguments' => array(
array('%menu' => array_keys(menu_get_menus())),
),
);
return $map;
}
/**
* Implements hook_admin_menu_map() on behalf of Node module.
*/
function node_admin_menu_map() {
if (!user_access('administer content types')) {
return;
}
$map['admin/structure/types/manage/%node_type'] = array(
'parent' => 'admin/structure/types',
'arguments' => array(
array('%node_type' => array_keys(node_type_get_types())),
),
);
return $map;
}
/**
* Implements hook_admin_menu_map() on behalf of Field UI module.
*/
function field_ui_admin_menu_map() {
$map = array();
foreach (entity_get_info() as $obj_type => $info) {
foreach ($info['bundles'] as $bundle_name => $bundle_info) {
if (isset($bundle_info['admin'])) {
$arguments = array();
switch ($obj_type) {
case 'comment':
$fields = array();
foreach (field_info_instances($obj_type, $bundle_name) as $field) {
$fields[] = $field['field_name'];
}
// @todo Make Comment module expose the original node type bundle,
// pretty please.
if (drupal_substr($bundle_name, 0, 13) == 'comment_node_') {
$bundle_name = drupal_substr($bundle_name, 13);
}
// @todo Doesn't work yet. Why?
$arguments = array(
'%comment_node_type' => array($bundle_name),
'%field_ui_menu' => $fields,
);
break;
case 'node':
$fields = array();
foreach (field_info_instances($obj_type, $bundle_name) as $field) {
$fields[] = $field['field_name'];
}
$arguments = array(
'%node_type' => array($bundle_name),
'%field_ui_menu' => $fields,
);
break;
case 'taxonomy_term':
$fields = array();
foreach (field_info_instances($obj_type, $bundle_name) as $field) {
$fields[] = $field['field_name'];
}
// Map machine_name to vid.
$arguments = array(
'%taxonomy_vocabulary_machine_name' => array($bundle_name),
'%field_ui_menu' => $fields,
);
break;
case 'user':
$arguments = array(
'%field_ui_menu' => array_keys(field_info_fields('user')),
);
break;
}
if (!empty($arguments)) {
$path = $bundle_info['admin']['path'];
$map["$path/fields/%field_ui_menu"]['parent'] = "$path/fields";
$map["$path/fields/%field_ui_menu"]['arguments'][] = $arguments;
}
}
}
}
return $map;
}
/**
* Implements hook_admin_menu_map() on behalf of Taxonomy module.
*/
function taxonomy_admin_menu_map() {
if (!user_access('administer taxonomy')) {
return;
}
$map['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
'parent' => 'admin/structure/taxonomy',
'arguments' => array(
array('%taxonomy_vocabulary_machine_name' => array_keys(taxonomy_vocabulary_get_names())),
),
);
return $map;
}
/**
* Implements hook_admin_menu_map() on behalf of Views UI module.
*/
function views_ui_admin_menu_map() {
if (!user_access('administer views')) {
return;
}
$views = array();
foreach (views_get_enabled_views() as $name => $view) {
$views[] = $name;
}
if (empty($views)) {
return;
}
$map['admin/structure/views/view/%views_ui_cache'] = array(
'parent' => 'admin/structure/views',
'arguments' => array(
array('%views_ui_cache' => $views),
),
);
return $map;
}

View File

@@ -0,0 +1,858 @@
<?php
/**
* @file
* Render an administrative menu as a dropdown menu at the top of the window.
*/
/**
* Implements hook_help().
*/
function admin_menu_help($path, $arg) {
switch ($path) {
case 'admin/config/administration/admin_menu':
return '<p>' . t('The administration menu module provides a dropdown menu arranged for one- or two-click access to most administrative tasks and other common destinations (to users with the proper permissions). Use the settings below to customize the appearance of the menu.') . '</p>';
case 'admin/help#admin_menu':
$output = '';
$output .= '<p>' . t('The administration menu module provides a dropdown menu arranged for one- or two-click access to most administrative tasks and other common destinations (to users with the proper permissions). Administration menu also displays the number of anonymous and authenticated users, and allows modules to add their own custom menu items. Integration with the menu varies from module to module; the contributed module <a href="@drupal">Devel</a>, for instance, makes strong use of the administration menu module to provide quick access to development tools.', array('@drupal' => 'http://drupal.org/project/devel')) . '</p>';
$output .= '<p>' . t('The administration menu <a href="@settings">settings page</a> allows you to modify some elements of the menu\'s behavior and appearance. Since the appearance of the menu is dependent on your site theme, substantial customizations require modifications to your site\'s theme and CSS files. See the advanced module README.txt file for more information on theme and CSS customizations.', array('@settings' => url('admin/config/administration/admin_menu'))) . '</p>';
$output .= '<p>' . t('The menu items displayed in the administration menu depend upon the actual permissions of the viewer. First, the administration menu is only displayed to users in roles with the <em>Access administration menu</em> (admin_menu module) permission. Second, a user must be a member of a role with the <em>Access administration pages</em> (system module) permission to view administrative links. And, third, only currently permitted links are displayed; for example, if a user is not a member of a role with the permissions <em>Administer permissions</em> (user module) and <em>Administer users</em> (user module), the <em>User management</em> menu item is not displayed.') . '</p>';
return $output;
}
}
/**
* Implements hook_permission().
*/
function admin_menu_permission() {
return array(
'access administration menu' => array(
'title' => t('Access administration menu'),
'description' => t('Display the administration menu at the top of each page.'),
),
'flush caches' => array(
'title' => t('Flush caches'),
'description' => t('Access links to flush caches in the administration menu.'),
),
'display drupal links' => array(
'title' => t('Display Drupal links'),
'description' => t('Provide Drupal.org links in the administration menu.'),
),
);
}
/**
* Implements hook_theme().
*/
function admin_menu_theme() {
return array(
'admin_menu_links' => array(
'render element' => 'elements',
),
'admin_menu_icon' => array(
'variables' => array('src' => NULL, 'alt' => NULL),
'file' => 'admin_menu.inc',
),
);
}
/**
* Implements hook_menu().
*/
function admin_menu_menu() {
// AJAX callback.
// @see http://drupal.org/project/js
$items['js/admin_menu/cache'] = array(
'page callback' => 'admin_menu_js_cache',
'delivery callback' => 'admin_menu_deliver',
'access arguments' => array('access administration menu'),
'type' => MENU_CALLBACK,
);
// Module settings.
$items['admin/config/administration'] = array(
'title' => 'Administration',
'description' => 'Administration tools.',
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),
);
$items['admin/config/administration/admin_menu'] = array(
'title' => 'Administration menu',
'description' => 'Adjust administration menu settings.',
'page callback' => 'drupal_get_form',
'page arguments' => array('admin_menu_theme_settings'),
'access arguments' => array('administer site configuration'),
'file' => 'admin_menu.inc',
);
// Menu link callbacks.
$items['admin_menu/toggle-modules'] = array(
'page callback' => 'admin_menu_toggle_modules',
'access arguments' => array('administer modules'),
'type' => MENU_CALLBACK,
'file' => 'admin_menu.inc',
);
$items['admin_menu/flush-cache'] = array(
'page callback' => 'admin_menu_flush_cache',
'access arguments' => array('flush caches'),
'type' => MENU_CALLBACK,
'file' => 'admin_menu.inc',
);
return $items;
}
/**
* Implements hook_menu_alter().
*/
function admin_menu_menu_alter(&$items) {
// Flush client-side caches whenever the menu is rebuilt.
admin_menu_flush_caches();
}
/**
* Implements hook_menu_link_insert().
*/
function admin_menu_menu_link_insert($link) {
// Flush all of our caches to pick up the link.
admin_menu_flush_caches();
}
/**
* Implements hook_menu_link_update().
*/
function admin_menu_menu_link_update($link) {
// Flush all of our caches to pick up the link.
admin_menu_flush_caches();
}
/**
* Implements hook_menu_link_delete().
*/
function admin_menu_menu_link_delete($link) {
// Flush all of our caches to pick up the link.
admin_menu_flush_caches();
}
/**
* Implements hook_system_info_alter().
*
* Indicate that the 'page_bottom' region (in which the administration menu
* is displayed) is an overlay supplemental region that should be refreshed
* whenever its content is updated.
*
* @see toolbar_system_info_alter()
*/
function admin_menu_system_info_alter(&$info, $file, $type) {
if ($type == 'theme') {
$info['overlay_supplemental_regions'][] = 'page_bottom';
}
}
/**
* Implements hook_page_build().
*/
function admin_menu_page_build(&$page) {
if (!user_access('access administration menu') || admin_menu_suppress(FALSE)) {
return;
}
// Performance: Skip this entirely for AJAX requests.
if (strpos($_GET['q'], 'js/') === 0) {
return;
}
global $user, $language;
$path = drupal_get_path('module', 'admin_menu');
$page['page_bottom']['admin_menu'] = array(
'#attached' => array(),
);
$attached = &$page['page_bottom']['admin_menu']['#attached'];
$options = array('every_page' => TRUE);
$attached['css'][$path . '/admin_menu.css'] = $options;
if ($user->uid == 1) {
$attached['css'][$path . '/admin_menu.uid1.css'] = $options;
}
// Previous versions used the 'defer' attribute to increase browser rendering
// performance. At least starting with Firefox 3.6, deferred .js files are
// loaded, but Drupal.behaviors are not contained in the DOM when drupal.js
// executes Drupal.attachBehaviors().
$attached['js'][$path . '/admin_menu.js'] = $options;
// Destination query strings are applied via JS.
$settings['destination'] = drupal_http_build_query(drupal_get_destination());
// Determine whether we need to show all components and disable all caches.
$complete = FALSE;
if (current_path() == 'admin/config/administration/admin_menu' && $_SERVER['REQUEST_METHOD'] == 'GET') {
$complete = TRUE;
}
// If the client supports JavaScript and we have a cached menu for the current
// user, only output the hash for the client-side HTTP cache callback URL.
$cid = 'admin_menu:' . $user->uid . ':' . session_id() . ':' . $language->language;
if (!$complete && !empty($_COOKIE['has_js']) && ($hash = admin_menu_cache_get($cid))) {
$settings['hash'] = $hash;
// The base path to use for cache requests depends on whether clean URLs
// are enabled, whether Drupal runs in a sub-directory, and on the language
// system configuration. url() already provides us the proper path and also
// invokes potentially existing custom_url_rewrite() functions, which may
// add further required components to the URL to provide context. Due to
// those components, and since url('') returns only base_path() when clean
// URLs are disabled, we need to use a replacement token as path. Yuck.
$settings['basePath'] = url('admin_menu');
}
// Otherwise, add the full menu to the page.
else {
$page['page_bottom']['admin_menu']['#markup'] = admin_menu_output($complete);
}
$replacements = module_invoke_all('admin_menu_replacements', $complete);
if (!empty($replacements)) {
$settings['replacements'] = $replacements;
}
if ($setting = variable_get('admin_menu_margin_top', 1)) {
$settings['margin_top'] = $setting;
// @todo Drupal.behaviors.adminMenuMarginTop is obsolete, but
// hook_page_build() does not allow to set a CSS class on the body yet.
// @see http://drupal.org/node/1473548, http://drupal.org/node/1194528
//$page['#attributes']['class'][] = 'admin-menu';
}
if ($setting = variable_get('admin_menu_position_fixed', 1)) {
$settings['position_fixed'] = $setting;
// In fixed positioning, supply a callback function for tableheader.js to
// allow it to determine the top viewport offset.
// @see admin_menu.js, toolbar.js
$attached['js'][] = array(
'data' => array('tableHeaderOffset' => 'Drupal.admin.height'),
'type' => 'setting',
);
}
if ($setting = variable_get('admin_menu_tweak_tabs', 0)) {
$settings['tweak_tabs'] = $setting;
}
if ($_GET['q'] == 'admin/modules' || strpos($_GET['q'], 'admin/modules/list') === 0) {
$settings['tweak_modules'] = variable_get('admin_menu_tweak_modules', 0);
}
if ($_GET['q'] == 'admin/people/permissions' || $_GET['q'] == 'admin/people/permissions/list') {
$settings['tweak_permissions'] = variable_get('admin_menu_tweak_permissions', 0);
}
$attached['js'][] = array(
'data' => array('admin_menu' => $settings),
'type' => 'setting',
);
}
/**
* Suppress display of administration menu.
*
* This function should be called from within another module's page callback
* (preferably using module_invoke()) when the menu should not be displayed.
* This is useful for modules that implement popup pages or other special
* pages where the menu would be distracting or break the layout.
*
* @param $set
* Defaults to TRUE. If called before hook_footer(), the menu will not be
* displayed. If FALSE is passed, the suppression state is returned.
*/
function admin_menu_suppress($set = TRUE) {
static $suppress = FALSE;
// drupal_add_js() must only be invoked once.
if (!empty($set) && $suppress === FALSE) {
$suppress = TRUE;
drupal_add_js(array('admin_menu' => array('suppress' => 1)), 'setting');
}
return $suppress;
}
/**
* Implements hook_js().
*/
function admin_menu_js() {
return array(
'cache' => array(
'callback' => 'admin_menu_js_cache',
'includes' => array('common', 'theme', 'unicode'),
'dependencies' => array('devel', 'filter', 'user'),
),
);
}
/**
* Retrieve a client-side cache hash from cache.
*
* The hash cache is consulted more than once per request; we therefore cache
* the results statically to avoid multiple database requests.
*
* This should only be used for client-side cache hashes. Use cache_menu for
* administration menu content.
*
* @param $cid
* The cache ID of the data to retrieve.
*/
function admin_menu_cache_get($cid) {
$cache = &drupal_static(__FUNCTION__, array());
if (!variable_get('admin_menu_cache_client', TRUE)) {
return FALSE;
}
if (!array_key_exists($cid, $cache)) {
$cache[$cid] = cache_get($cid, 'cache_admin_menu');
if ($cache[$cid] && isset($cache[$cid]->data)) {
$cache[$cid] = $cache[$cid]->data;
}
}
return $cache[$cid];
}
/**
* Store a client-side cache hash in persistent cache.
*
* This should only be used for client-side cache hashes. Use cache_menu for
* administration menu content.
*
* @param $cid
* The cache ID of the data to retrieve.
*/
function admin_menu_cache_set($cid, $data) {
if (variable_get('admin_menu_cache_client', TRUE)) {
cache_set($cid, $data, 'cache_admin_menu');
}
}
/**
* Menu callback; Output administration menu for HTTP caching via AJAX request.
*
* @see admin_menu_deliver()
*/
function admin_menu_js_cache() {
global $conf;
// Suppress Devel module.
$GLOBALS['devel_shutdown'] = FALSE;
// Enforce page caching.
$conf['cache'] = 1;
drupal_page_is_cacheable(TRUE);
// If we have a cache, serve it.
// @see _drupal_bootstrap_page_cache()
$cache = drupal_page_get_cache();
if (is_object($cache)) {
header('X-Drupal-Cache: HIT');
// Restore the metadata cached with the page.
$_GET['q'] = $cache->data['path'];
date_default_timezone_set(drupal_get_user_timezone());
drupal_serve_page_from_cache($cache);
// We are done.
exit;
}
// Otherwise, create a new page response (that will be cached).
header('X-Drupal-Cache: MISS');
// The Expires HTTP header is the heart of the client-side HTTP caching. The
// additional server-side page cache only takes effect when the client
// accesses the callback URL again (e.g., after clearing the browser cache or
// when force-reloading a Drupal page).
$max_age = 3600 * 24 * 365;
drupal_add_http_header('Expires', gmdate(DATE_RFC1123, REQUEST_TIME + $max_age));
drupal_add_http_header('Cache-Control', 'private, max-age=' . $max_age);
// Retrieve and return the rendered menu.
return admin_menu_output();
}
/**
* Delivery callback for client-side HTTP caching.
*
* @see admin_menu_js_cache()
*/
function admin_menu_deliver($page_callback_result) {
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
// Send appropriate language header for browsers.
global $language;
drupal_add_http_header('Content-Language', $language->language);
// The page callback is always admin_menu_js_cache(), which always returns a
// string, and is only accessed when the user actually has access to it.
// Therefore, we do not care for the other possible page callback results.
print $page_callback_result;
// Perform end-of-request tasks. The page cache is created here.
drupal_page_footer();
}
/**
* Implements hook_admin_menu_replacements().
*/
function admin_menu_admin_menu_replacements($complete) {
$items = array();
// If the complete menu is output, then it is uncached and will contain the
// current counts already.
if (!$complete) {
// Check whether the users count component is enabled.
$components = variable_get('admin_menu_components', array());
if (!empty($components['admin_menu.users']) && ($user_count = admin_menu_get_user_count())) {
// Replace the counters in the cached menu output with current counts.
$items['.admin-menu-users a'] = $user_count;
}
}
return $items;
}
/**
* Return count of online anonymous/authenticated users.
*
* @see user_block(), user.module
*/
function admin_menu_get_user_count() {
$interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
$count_anon = admin_menu_session_count($interval, TRUE);
$count_auth = admin_menu_session_count($interval, FALSE);
return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}
/**
* Counts how many users are active on the site.
*
* Counts how many users have sessions which have been active since the
* specified time. Can count either anonymous sessions or authenticated
* sessions.
*
* @param $timestamp
* A Unix timestamp. Users who have been active since this time will be
* counted. The default is 0, which counts all existing sessions.
* @param $anonymous
* TRUE counts only anonymous users. FALSE counts only authenticated users.
*
* @return
* The number of users with sessions.
*
* @todo There are mostly no anonymous sessions anymore. Split this into a
* separate module providing proper user statistics.
*/
function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
$query = db_select('sessions');
$query->addExpression('COUNT(sid)', 'count');
$query->condition('timestamp', $timestamp, '>=');
$query->condition('uid', 0, $anonymous ? '=' : '>');
return $query->execute()->fetchField();
}
/**
* Build the administration menu output.
*
* @param bool $complete
* (optional) Whether to build to the complete menu including all components
* and ignore the cache. Defaults to FALSE. Internally used for the settings
* page.
*/
function admin_menu_output($complete = FALSE) {
global $user, $language;
$cache_server_enabled = !$complete && variable_get('admin_menu_cache_server', TRUE);
$cid = 'admin_menu:' . $user->uid . ':' . session_id() . ':' . $language->language;
// Try to load and output administration menu from server-side cache.
// @todo Duplicates the page cache? Page cache ID contains the hash that is
// generated at the bottom of this function, which is based on $content,
// but logically identical to the $cid. Investigate whether not only the
// cache_menu but also the cache_admin_menu could be dropped; the
// client-side HTTP cache hash check could be based on a cid lookup in
// cache_page instead? (i.e., one cache to rule them all) However,
// cache_page is cleared very often.
if ($cache_server_enabled) {
$cache = cache_get($cid, 'cache_menu');
if ($cache && isset($cache->data)) {
$content = $cache->data;
}
}
// Rebuild the output.
if (!isset($content)) {
// Retrieve enabled components to display and make them available for others.
$components = variable_get('admin_menu_components', array());
$components += array(
'admin_menu.menu' => TRUE,
'admin_menu.icon' => TRUE,
'admin_menu.account' => TRUE,
);
$content['#components'] = $components;
$content['#complete'] = $complete;
// Add site name as CSS class for development/staging theming purposes. We
// leverage the cookie domain instead of HTTP_HOST to account for many (but
// not all) multi-domain setups (e.g. language-based sub-domains).
$classes = 'admin-menu-site' . drupal_strtolower(preg_replace('/[^a-zA-Z0-9-]/', '-', $GLOBALS['cookie_domain']));
// Displace overlay.
// @see Drupal.overlay.create
// @see toolbar_preprocess_toolbar()
if (module_exists('overlay')) {
$classes .= ' overlay-displace-top';
}
// @todo Always output container to harden JS-less support.
$content['#prefix'] = '<div id="admin-menu" class="' . $classes . '"><div id="admin-menu-wrapper">';
$content['#suffix'] = '</div></div>';
// Load menu builder functions.
module_load_include('inc', 'admin_menu');
// @todo Move the below callbacks into hook_admin_menu_build()
// implementations (and $module.admin_menu.inc).
// Add administration menu.
if (!empty($components['admin_menu.menu']) || $complete) {
$content['menu'] = admin_menu_links_menu(admin_menu_tree('management'));
$content['menu']['#theme'] = 'admin_menu_links';
$content['menu']['#wrapper_attributes']['id'] = 'admin-menu-menu';
// Ensure the menu tree is rendered between the icon and user links.
$content['menu']['#weight'] = 0;
}
// Add menu additions.
if (!empty($components['admin_menu.icon']) || $complete) {
$content['icon'] = admin_menu_links_icon();
}
if (!empty($components['admin_menu.account']) || $complete) {
$content['account'] = admin_menu_links_account();
}
if (!empty($components['admin_menu.users']) || $complete) {
$content['users'] = admin_menu_links_users();
}
if (!empty($components['admin_menu.search']) || $complete) {
$content['search'] = admin_menu_links_search();
}
// Allow modules to enhance the menu.
// Uses '_output' suffix for consistency with the alter hook (see below).
foreach (module_implements('admin_menu_output_build') as $module) {
$function = $module . '_admin_menu_output_build';
$function($content);
}
// Allow modules to alter the output.
// The '_output' suffix is required to prevent hook implementation function
// name clashes with the contributed Admin module.
drupal_alter('admin_menu_output', $content);
$content = drupal_render($content);
// Cache the menu for this user.
if ($cache_server_enabled) {
cache_set($cid, $content, 'cache_menu');
}
}
// Store the new hash for this user.
if (!empty($_COOKIE['has_js']) && !$complete) {
admin_menu_cache_set($cid, md5($content));
}
return $content;
}
/**
* Implements hook_admin_menu_output_build().
*/
function admin_menu_admin_menu_output_build(&$content) {
if (!isset($content['menu'])) {
return;
}
// Unassign weights for categories below Configuration.
// An alphabetical order is more natural for a dropdown menu.
if (isset($content['menu']['admin/config'])) {
foreach (element_children($content['menu']['admin/config']) as $key) {
$content['menu']['admin/config'][$key]['#weight_original'] = $content['menu']['admin/config'][$key]['#weight'];
unset($content['menu']['admin/config'][$key]['#weight']);
}
}
// Retrieve the "Add content" link tree.
$link = db_query("SELECT * FROM {menu_links} WHERE router_path = 'node/add' AND module = 'system'")->fetchAssoc();
$conditions = array();
for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
if (!empty($link["p$i"])) {
$conditions["p$i"] = $link["p$i"];
}
}
$tree = menu_build_tree($link['menu_name'], array(
'conditions' => $conditions,
'min_depth' => $link['depth'],
));
$links = admin_menu_links_menu($tree);
if (!empty($links)) {
// If the user has access to the top-level "Content" category, insert the
// "Add content" link tree there.
if (isset($content['menu']['admin/content'])) {
$content['menu']['admin/content'] += $links;
}
// Otherwise make insert "Add content" as top-level category.
else {
$key = key($links);
$links[$key]['#weight'] = -100;
$content['menu'] += $links;
}
}
}
/**
* Implements hook_admin_menu_output_alter().
*/
function admin_menu_admin_menu_output_alter(&$content) {
foreach ($content['menu'] as $key => $link) {
// Move local tasks on 'admin' into icon menu.
if ($key == 'admin/tasks' || $key == 'admin/index') {
$content['icon']['icon'][$key] = $link;
unset($content['menu'][$key]);
}
}
}
/**
* Render a themed list of links.
*
* @param $variables
* - elements: A renderable array of links using the following keys:
* - #attributes: Optional array of attributes for the list item, processed
* via drupal_attributes().
* - #title: Title of the link, passed to l().
* - #href: Optional path of the link, passed to l(). When omitted, the
* element's '#title' is rendered without link.
* - #description: Optional alternative text for the link, passed to l().
* - #options: Optional alternative text for the link, passed to l().
* The array key of each child element itself is passed as path for l().
*/
function theme_admin_menu_links($variables) {
$destination = &drupal_static('admin_menu_destination');
$elements = $variables['elements'];
if (!isset($destination)) {
$destination = drupal_get_destination();
$destination = $destination['destination'];
}
// The majority of items in the menu are sorted already, but since modules
// may add or change arbitrary items anywhere, there is no way around sorting
// everything again. element_sort() is not sufficient here, as it
// intentionally retains the order of elements having the same #weight,
// whereas menu links are supposed to be ordered by #weight and #title.
uasort($elements, 'admin_menu_element_sort');
$elements['#sorted'] = TRUE;
$output = '';
foreach (element_children($elements) as $path) {
// Early-return nothing if user does not have access.
if (isset($elements[$path]['#access']) && !$elements[$path]['#access']) {
continue;
}
$elements[$path] += array(
'#attributes' => array(),
'#options' => array(),
);
// Render children to determine whether this link is expandable.
if (isset($elements[$path]['#type']) || isset($elements[$path]['#theme']) || isset($elements[$path]['#pre_render'])) {
$elements[$path]['#children'] = drupal_render($elements[$path]);
}
else {
$elements[$path]['#children'] = theme('admin_menu_links', array('elements' => $elements[$path]));
if (!empty($elements[$path]['#children'])) {
$elements[$path]['#attributes']['class'][] = 'expandable';
}
if (isset($elements[$path]['#attributes']['class'])) {
$elements[$path]['#attributes']['class'] = $elements[$path]['#attributes']['class'];
}
}
$link = '';
// Handle menu links.
if (isset($elements[$path]['#href'])) {
// Strip destination query string from href attribute and apply a CSS class
// for our JavaScript behavior instead.
if (isset($elements[$path]['#options']['query']['destination']) && $elements[$path]['#options']['query']['destination'] == $destination) {
unset($elements[$path]['#options']['query']['destination']);
$elements[$path]['#options']['attributes']['class'][] = 'admin-menu-destination';
}
$link = l($elements[$path]['#title'], $elements[$path]['#href'], $elements[$path]['#options']);
}
// Handle plain text items, but do not interfere with menu additions.
elseif (!isset($elements[$path]['#type']) && isset($elements[$path]['#title'])) {
if (!empty($elements[$path]['#options']['html'])) {
$title = $elements[$path]['#title'];
}
else {
$title = check_plain($elements[$path]['#title']);
}
$attributes = '';
if (isset($elements[$path]['#options']['attributes'])) {
$attributes = drupal_attributes($elements[$path]['#options']['attributes']);
}
$link = '<span' . $attributes . '>' . $title . '</span>';
}
$output .= '<li' . drupal_attributes($elements[$path]['#attributes']) . '>';
$output .= $link . $elements[$path]['#children'];
$output .= '</li>';
}
// @todo #attributes probably required for UL, but already used for LI.
// @todo Use $element['#children'] here instead.
if ($output) {
$elements['#wrapper_attributes']['class'][] = 'dropdown';
$attributes = drupal_attributes($elements['#wrapper_attributes']);
$output = "\n" . '<ul' . $attributes . '>' . $output . '</ul>';
}
return $output;
}
/**
* Function used by uasort to sort structured arrays by #weight AND #title.
*/
function admin_menu_element_sort($a, $b) {
// @see element_sort()
$a_weight = isset($a['#weight']) ? $a['#weight'] : 0;
$b_weight = isset($b['#weight']) ? $b['#weight'] : 0;
if ($a_weight == $b_weight) {
// @see element_sort_by_title()
$a_title = isset($a['#title']) ? $a['#title'] : '';
$b_title = isset($b['#title']) ? $b['#title'] : '';
return strnatcasecmp($a_title, $b_title);
}
return ($a_weight < $b_weight) ? -1 : 1;
}
/**
* Implements hook_translated_menu_link_alter().
*
* Here is where we make changes to links that need dynamic information such
* as the current page path or the number of users.
*/
function admin_menu_translated_menu_link_alter(&$item, $map) {
global $user, $base_url;
static $access_all;
if ($item['menu_name'] != 'admin_menu') {
return;
}
// Check whether additional development output is enabled.
if (!isset($access_all)) {
$access_all = variable_get('admin_menu_show_all', 0) && module_exists('devel');
}
// Prepare links that would not be displayed normally.
if ($access_all && !$item['access']) {
$item['access'] = TRUE;
// Prepare for http://drupal.org/node/266596
if (!isset($item['localized_options'])) {
_menu_item_localize($item, $map, TRUE);
}
}
// Don't waste cycles altering items that are not visible
if (!$item['access']) {
return;
}
// Add developer information to all links, if enabled.
if ($extra = variable_get('admin_menu_display', 0)) {
$item['title'] .= ' ' . $extra[0] . ': ' . $item[$extra];
}
}
/**
* Implements hook_flush_caches().
*
* Flushes client-side caches.
*
* @param int $uid
* (optional) A user ID to limit the cache flush to.
*/
function admin_menu_flush_caches($uid = NULL) {
// A call to menu_rebuild() will trigger potentially thousands of calls into
// menu_link_save(), for which admin_menu has to implement the corresponding
// CRUD hooks, in order to take up any menu link changes, since any menu link
// change could affect the admin menu (which essentially is an aggregate) and
// since there is no other way to get notified about stale caches. The cache
// only needs to be flushed once though, so we prevent a ton of needless
// subsequent calls with this static.
// @see http://drupal.org/node/918538
$was_flushed = &drupal_static(__FUNCTION__, array());
// $uid can be NULL. PHP automatically converts that into '' (empty string),
// which is different to uid 0 (zero).
if (isset($was_flushed[$uid])) {
return;
}
$was_flushed[$uid] = TRUE;
$cid = 'admin_menu:';
if (isset($uid)) {
$cid .= $uid . ':';
}
// Flush cached output of admin_menu.
cache_clear_all($cid, 'cache_menu', TRUE);
// Flush client-side cache hashes.
drupal_static_reset('admin_menu_cache_get');
// db_table_exists() required for SimpleTest.
if (db_table_exists('cache_admin_menu')) {
cache_clear_all(isset($uid) ? $cid : '*', 'cache_admin_menu', TRUE);
}
}
/**
* Implements hook_form_alter().
*/
function admin_menu_form_alter(&$form, &$form_state, $form_id) {
$global_flush_ids = array(
'admin_menu_theme_settings' => 1,
// Update links for clean/non-clean URLs.
'system_clean_url_settings' => 1,
// Incorporate changed user permissions.
'user_admin_permissions' => 1,
// Removing a role potentially means less permissions.
'user_admin_role_delete_confirm' => 1,
// User name and roles may be changed on the user account form.
'user_profile_form' => 1,
);
if (isset($global_flush_ids[$form_id])) {
$form['#submit'][] = 'admin_menu_form_alter_flush_cache_submit';
// Optionally limit the cache flush to a certain user ID.
$form_state['admin_menu_uid'] = NULL;
if ($form_id == 'user_profile_form') {
$form_state['admin_menu_uid'] = $form_state['user']->uid;
}
}
// UX: Add a confirmation to the permissions form to ask the user whether to
// auto-enable the 'access administration menu' permission along with
// 'access administration pages'.
if ($form_id == 'user_admin_permissions') {
$form['#attached']['js'][] = drupal_get_path('module', 'admin_menu') . '/admin_menu.admin.js';
}
}
/**
* Form submission handler to flush Administration menu caches.
*/
function admin_menu_form_alter_flush_cache_submit($form, &$form_state) {
admin_menu_flush_caches($form_state['admin_menu_uid']);
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Extends Devel module with Administration menu developer settings.
*/
function admin_menu_form_devel_admin_settings_alter(&$form, &$form_state) {
form_load_include($form_state, 'inc', 'admin_menu');
_admin_menu_form_devel_admin_settings_alter($form, $form_state);
}

View File

@@ -0,0 +1,9 @@
/**
* @file
* Administration menu color override for uid1.
*/
#admin-menu li.admin-menu-account > a {
background: #911 url(images/bkg-red.png) bottom left repeat-x;
}

View File

@@ -0,0 +1,145 @@
/**
* @file
* Toolbar style for Administration menu.
*
* Important: We cannot re-use toolbar.png from Toolbar module, since we cannot
* reliably determine the path to it.
*
* @todo Separate shortcut functionality into own module/widget.
*/
/* Adjust margin/height */
html body.admin-menu {
margin-top: 29px !important;
}
html body.admin-menu-with-shortcuts {
margin-top: 65px !important;
}
/* Displace the core Toolbar, if concurrently output. */
body div#toolbar.toolbar {
top: 30px;
}
/**
* Base styles.
*
* We use a keyword for the toolbar font size to make it display consistently
* across different themes, while still allowing browsers to resize the text.
*/
#admin-menu {
font: normal small "Lucida Grande", Verdana, sans-serif;
-moz-box-shadow: 0 -10px 20px 13px #000;
-webkit-box-shadow: 0 -10px 20px 13px #000;
box-shadow: 0 -10px 20px 13px #000;
right: 0;
width: auto;
}
#admin-menu-wrapper {
font-size: .846em;
padding: 5px 10px 0;
}
#admin-menu .dropdown a {
color: #fafafa;
}
/* Remove border from all lists and actions */
#admin-menu .dropdown .admin-menu-action a {
border-left: 0;
}
#admin-menu .dropdown .admin-menu-icon > a {
padding: 2px 10px 3px;
}
/**
* Administration menu.
*/
#admin-menu .dropdown .admin-menu-icon > a span {
vertical-align: text-bottom;
width: 11px;
height: 14px;
display: block;
background: url(toolbar.png) no-repeat 0 -45px;
text-indent: -9999px;
}
#admin-menu > div > .dropdown > li > a {
border-right: 0;
margin-bottom: 4px;
padding: 2px 10px 3px;
}
#admin-menu .dropdown .admin-menu-toolbar-category > a,
#admin-menu .dropdown .admin-menu-action > a {
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
#admin-menu .dropdown .admin-menu-toolbar-category > a.active-trail {
text-shadow: #333 0 1px 0;
background: url(toolbar.png) 0 0 repeat-x;
}
#admin-menu .dropdown .admin-menu-toolbar-category > a:hover {
background-color: #444;
}
#admin-menu .dropdown .admin-menu-tab a {
border-right: 0;
}
#admin-menu .dropdown li li.expandable ul {
margin: -22px 0 0 160px;
}
/**
* Shortcuts toggle.
*/
#admin-menu .shortcut-toggle {
cursor: pointer;
background: url(toolbar.png) 0 -20px no-repeat;
display: block;
float: right;
margin: 0 0 0 1.3em;
text-indent: -9999px;
overflow: hidden;
width: 25px;
height: 25px;
}
#admin-menu .shortcut-toggle:focus,
#admin-menu .shortcut-toggle:hover {
background-position: -50px -20px;
}
#admin-menu .shortcut-toggle.active {
background-position: -25px -20px;
}
#admin-menu .shortcut-toggle.active:focus,
#admin-menu .shortcut-toggle.active:hover {
background-position: -75px -20px;
}
/**
* Shortcuts widget.
*/
#admin-menu .shortcut-toolbar {
background-color: #666;
clear: both;
display: none;
margin: 0 -10px;
overflow: hidden;
/* Align with icon; @see shortcut.css */
padding-left: 5px;
}
#admin-menu .shortcut-toolbar.active {
display: block;
}
/* Override theme list style; @see shortcut.css */
#admin-menu .shortcut-toolbar ul {
margin: 0;
}
/* @see toolbar.css */
#admin-menu .shortcut-toolbar li {
float: left;
list-style-image: none;
list-style-type: none;
}
#admin-menu .shortcut-toolbar a {
display: block;
}

View File

@@ -0,0 +1,12 @@
name = Administration menu Toolbar style
description = A better Toolbar.
package = Administration
core = 7.x
dependencies[] = admin_menu
; Information added by drupal.org packaging script on 2013-01-31
version = "7.x-3.0-rc4"
core = "7.x"
project = "admin_menu"
datestamp = "1359651687"

View File

@@ -0,0 +1,37 @@
<?php
/**
* @file
* Installation functionality for Administration menu toolbar module.
*/
/**
* Implements hook_install().
*/
function admin_menu_toolbar_install() {
// Required to load JS/CSS in hook_init() after admin_menu.
db_update('system')
->fields(array('weight' => 101))
->condition('type', 'module')
->condition('name', 'admin_menu_toolbar')
->execute();
}
/**
* Set module weight to a value higher than admin_menu.
*
* At this point, admin_menu should have a weight of 100. To account for
* customized weights, we increase the weight relatively.
*
* @see admin_menu_toolbar_install()
*/
function admin_menu_toolbar_update_6300() {
$weight = db_query("SELECT weight FROM {system} WHERE type = 'module' AND name = 'admin_menu'")->fetchField();
$weight++;
db_update('system')
->fields(array('weight' => $weight))
->condition('type', 'module')
->condition('name', 'admin_menu_toolbar')
->execute();
}

View File

@@ -0,0 +1,56 @@
(function($) {
Drupal.admin = Drupal.admin || {};
Drupal.admin.behaviors = Drupal.admin.behaviors || {};
/**
* @ingroup admin_behaviors
* @{
*/
/**
* Apply active trail highlighting based on current path.
*
* @todo Not limited to toolbar; move into core?
*/
Drupal.admin.behaviors.toolbarActiveTrail = function (context, settings, $adminMenu) {
if (settings.admin_menu.toolbar && settings.admin_menu.toolbar.activeTrail) {
$adminMenu.find('> div > ul > li > a[href="' + settings.admin_menu.toolbar.activeTrail + '"]').addClass('active-trail');
}
};
/**
* Toggles the shortcuts bar.
*/
Drupal.admin.behaviors.shortcutToggle = function (context, settings, $adminMenu) {
var $shortcuts = $adminMenu.find('.shortcut-toolbar');
if (!$shortcuts.length) {
return;
}
var storage = window.localStorage || false;
var storageKey = 'Drupal.admin_menu.shortcut';
var $body = $(context).find('body');
var $toggle = $adminMenu.find('.shortcut-toggle');
$toggle.click(function () {
var enable = !$shortcuts.hasClass('active');
$shortcuts.toggleClass('active', enable);
$toggle.toggleClass('active', enable);
if (settings.admin_menu.margin_top) {
$body.toggleClass('admin-menu-with-shortcuts', enable);
}
// Persist toggle state across requests.
storage && enable ? storage.setItem(storageKey, 1) : storage.removeItem(storageKey);
this.blur();
return false;
});
if (!storage || storage.getItem(storageKey)) {
$toggle.trigger('click');
}
};
/**
* @} End of "ingroup admin_behaviors".
*/
})(jQuery);

View File

@@ -0,0 +1,118 @@
<?php
/**
* @file
* Renders Administration menu like Toolbar (core) module.
*
* @todo Separate shortcut functionality into own module/widget.
*/
/**
* Implements hook_form_FORMID_alter().
*/
function admin_menu_toolbar_form_admin_menu_theme_settings_alter(&$form) {
// Add the shortcut links as component on behalf of Shortcut module.
$form['plugins']['admin_menu_components']['#options']['shortcut.links'] = t('Shortcuts');
// The shortcut bar consists of two elements, so we target their class names
// instead of cluttering the markup with additional IDs.
$form['plugins']['admin_menu_components']['shortcut.links']['#attributes']['rel'] = '.shortcut-toggle, .shortcut-toolbar';
}
/**
* Implementation of hook_page_build().
*/
function admin_menu_toolbar_page_build(&$page) {
if (!isset($page['page_bottom']['admin_menu'])) {
return;
}
$path = drupal_get_path('module', 'admin_menu_toolbar');
$attached = &$page['page_bottom']['admin_menu']['#attached'];
$options = array('every_page' => TRUE);
$attached['css'][$path . '/admin_menu_toolbar.css'] = $options;
$attached['js'][$path . '/admin_menu_toolbar.js'] = $options;
// @todo Stop-gap fix until cached rendering is resolved.
// @see http://drupal.org/node/1567622
if (module_exists('shortcut')) {
$attached['css'][drupal_get_path('module', 'shortcut') . '/shortcut.css'] = $options;
}
$settings = array();
// Add current path to support menu item highlighting.
// @todo Compile real active trail here?
$args = explode('/', $_GET['q']);
if ($args[0] == 'admin' && !empty($args[1])) {
$settings['activeTrail'] = url($args[0] . '/' . $args[1]);
}
elseif (drupal_is_front_page()) {
$settings['activeTrail'] = url('<front>');
}
$attached['js'][] = array(
'data' => array('admin_menu' => array('toolbar' => $settings)),
'type' => 'setting',
);
}
/**
* Implements hook_admin_menu_output_build().
*/
function admin_menu_toolbar_admin_menu_output_build(&$content) {
if (empty($content['#components']['shortcut.links']) && !$content['#complete']) {
return;
}
// Add shortcuts toggle.
$content['shortcut-toggle'] = array(
'#access' => module_exists('shortcut'),
'#weight' => -200,
'#type' => 'link',
'#title' => t('Show shortcuts'),
'#href' => '',
'#options' => array(
'attributes' => array('class' => 'shortcut-toggle'),
),
);
// Add shortcuts bar.
$content['shortcut'] = array(
'#access' => module_exists('shortcut'),
'#weight' => 200,
'#prefix' => '<div class="shortcut-toolbar">',
'#suffix' => '</div>',
);
$content['shortcut']['shortcuts'] = array(
// Shortcut module's CSS relies on Toolbar module's markup.
// @see http://drupal.org/node/1217038
'#prefix' => '<div id="toolbar">',
'#suffix' => '</div>',
// @todo Links may contain .active-trail classes.
'#pre_render' => array('shortcut_toolbar_pre_render'),
);
}
/**
* Implements hook_admin_menu_output_alter().
*/
function admin_menu_toolbar_admin_menu_output_alter(&$content) {
// Add a class to top-level items for styling.
if (isset($content['menu'])) {
foreach (element_children($content['menu']) as $link) {
$content['menu'][$link]['#attributes']['class'][] = 'admin-menu-toolbar-category';
}
}
// Alter icon.
if (isset($content['icon'])) {
unset($content['icon']['icon']['#theme']);
$content['icon']['icon']['#title'] = '<span>' . t('Home') . '</span>';
$content['icon']['icon']['#attributes']['class'][] = 'admin-menu-toolbar-category';
}
// Alter user account link.
if (isset($content['account'])) {
$content['account']['account']['#title'] = t('Hello <strong>@username</strong>', array('@username' => $content['account']['account']['#title']));
$content['account']['account']['#options']['html'] = TRUE;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 629 B

View File

@@ -0,0 +1,520 @@
<?php
/**
* @file
* Tests for the Administration menu module.
*/
/**
* Base class for all administration menu web test cases.
*/
class AdminMenuWebTestCase extends DrupalWebTestCase {
protected $profile = 'testing';
protected $basePermissions = array(
'system' => 'access administration pages',
'admin_menu' => 'access administration menu',
);
function setUp() {
// Enable admin menu module and any other modules.
$modules = func_get_args();
$modules = isset($modules[0]) ? $modules[0] : $modules;
$modules[] = 'admin_menu';
parent::setUp($modules);
// Disable client-side caching.
variable_set('admin_menu_cache_client', FALSE);
// Disable Clean URLs to ensure drupal.org testbot compatibility.
variable_set('clean_url', 0);
}
/**
* Check that an element exists in HTML markup.
*
* @param $xpath
* An XPath expression.
* @param array $arguments
* (optional) An associative array of XPath replacement tokens to pass to
* DrupalWebTestCase::buildXPathQuery().
* @param $message
* The message to display along with the assertion.
* @param $group
* The type of assertion - examples are "Browser", "PHP".
*
* @return
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertElementByXPath($xpath, array $arguments = array(), $message, $group = 'Other') {
$elements = $this->xpath($xpath, $arguments);
return $this->assertTrue(!empty($elements[0]), $message, $group);
}
/**
* Check that an element does not exist in HTML markup.
*
* @param $xpath
* An XPath expression.
* @param array $arguments
* (optional) An associative array of XPath replacement tokens to pass to
* DrupalWebTestCase::buildXPathQuery().
* @param $message
* The message to display along with the assertion.
* @param $group
* The type of assertion - examples are "Browser", "PHP".
*
* @return
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertNoElementByXPath($xpath, array $arguments = array(), $message, $group = 'Other') {
$elements = $this->xpath($xpath, $arguments);
return $this->assertTrue(empty($elements), $message, $group);
}
/**
* Asserts that links appear in the menu in a specified trail.
*
* @param array $trail
* A list of menu link titles to assert in the menu.
*/
protected function assertLinkTrailByTitle(array $trail) {
$xpath = array();
$args = array();
$message = '';
foreach ($trail as $i => $title) {
$xpath[] = '/li/a[text()=:title' . $i . ']';
$args[':title' . $i] = $title;
$message .= ($i ? ' » ' : '') . check_plain($title);
}
$xpath = '//div[@id="admin-menu"]/div/ul' . implode('/parent::li/ul', $xpath);
$this->assertElementByXPath($xpath, $args, $message . ' link found.');
}
/**
* Asserts that no link appears in the menu for a specified trail.
*
* @param array $trail
* A list of menu link titles to assert in the menu.
*/
protected function assertNoLinkTrailByTitle(array $trail) {
$xpath = array();
$args = array();
$message = '';
foreach ($trail as $i => $title) {
$xpath[] = '/li/a[text()=:title' . $i . ']';
$args[':title' . $i] = $title;
$message .= ($i ? ' » ' : '') . check_plain($title);
}
$xpath = '//div[@id="admin-menu"]/div/ul' . implode('/parent::li/ul', $xpath);
$this->assertNoElementByXPath($xpath, $args, $message . ' link not found.');
}
}
/**
* Tests menu links depending on user permissions.
*/
class AdminMenuPermissionsTestCase extends AdminMenuWebTestCase {
public static function getInfo() {
return array(
'name' => 'Menu link access permissions',
'description' => 'Tests appearance of menu links depending on user permissions.',
'group' => 'Administration menu',
);
}
function setUp() {
parent::setUp(array('node'));
}
/**
* Test that the links are added to the page (no JS testing).
*/
function testPermissions() {
module_enable(array('contact'));
$this->resetAll();
// Anonymous users should not see the menu.
$this->drupalGet('');
$this->assertNoElementByXPath('//div[@id="admin-menu"]', array(), t('Administration menu not found.'));
// Create a user who
// - can access content overview
// - cannot access drupal.org links
// - cannot administer Contact module
$permissions = $this->basePermissions + array(
'access content overview',
);
$admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user);
// Check that the user can see the admin links, but not the drupal links.
$this->assertElementByXPath('//div[@id="admin-menu"]', array(), 'Administration menu found.');
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path)]', array(':path' => 'admin/content'), 'Content link found.');
$this->assertNoElementByXPath('//div[@id="admin-menu"]//a[@href=:path]', array(':path' => 'http://drupal.org'), 'Icon » Drupal.org link not found.');
$this->assertNoElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path)]', array(':path' => 'admin/structure/contact'), 'Structure » Contact link not found.');
// Create a user "reversed" to the above; i.e., who
// - cannot access content overview
// - can access drupal.org links
// - can administer Contact module
$permissions = $this->basePermissions + array(
'display drupal links',
'administer contact forms',
);
$admin_user2 = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user2);
$this->assertElementByXPath('//div[@id="admin-menu"]', array(), 'Administration menu found.');
$this->assertNoElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path)]', array(':path' => 'admin/content'), 'Content link not found.');
$this->assertElementByXPath('//div[@id="admin-menu"]//a[@href=:path]', array(':path' => 'http://drupal.org'), 'Icon » Drupal.org link found.');
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path)]', array(':path' => 'admin/structure/contact'), 'Structure » Contact link found.');
}
/**
* Tests handling of links pointing to category/overview pages.
*/
function testCategories() {
// Create a user with minimum permissions.
$admin_user = $this->drupalCreateUser($this->basePermissions);
$this->drupalLogin($admin_user);
// Verify that no category links appear.
$this->assertNoLinkTrailByTitle(array(t('Structure')));
$this->assertNoLinkTrailByTitle(array(t('Configuration')));
// Create a user with access to one configuration category.
$permissions = $this->basePermissions + array(
'administer users',
);
$admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user);
// Verify that only expected category links appear.
$this->assertNoLinkTrailByTitle(array(t('Structure')));
$this->assertLinkTrailByTitle(array(t('People')));
$this->assertLinkTrailByTitle(array(t('Configuration')));
$this->assertLinkTrailByTitle(array(t('Configuration'), t('People')));
// Random picks are sufficient.
$this->assertNoLinkTrailByTitle(array(t('Configuration'), t('Media')));
$this->assertNoLinkTrailByTitle(array(t('Configuration'), t('System')));
}
/**
* Tests that user role and permission changes are properly taken up.
*/
function testPermissionChanges() {
// Create a user who is able to change permissions.
$permissions = $this->basePermissions + array(
'administer permissions',
);
$admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user);
// Extract the user role ID that was created for above permissions.
$rid = key(array_diff_key($admin_user->roles, array(DRUPAL_AUTHENTICATED_RID => 0)));
// Verify that Configuration does not appear.
$this->assertNoLinkTrailByTitle(array(t('Configuration')));
// Grant the 'administer site configuration' permission to ourselves.
$edit = array(
$rid . '[administer site configuration]' => TRUE,
);
$this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
// Verify that Configuration appears.
$this->assertLinkTrailByTitle(array(t('Configuration')));
// Verify that Structure » Content types does not appear.
$this->assertNoLinkTrailByTitle(array(t('Structure'), t('Content types')));
// Create a new role.
$edit = array(
'name' => 'test',
);
$this->drupalPost('admin/people/permissions/roles', $edit, t('Add role'));
// It should be safe to assume that the new role gets the next ID.
$test_rid = $rid + 1;
// Grant the 'administer content types' permission for the role.
$edit = array(
$test_rid . '[administer content types]' => TRUE,
);
$this->drupalPost('admin/people/permissions/' . $test_rid, $edit, t('Save permissions'));
// Verify that Structure » Content types does not appear.
$this->assertNoLinkTrailByTitle(array(t('Structure'), t('Content types')));
// Assign the role to ourselves.
$edit = array(
'roles[' . $test_rid . ']' => TRUE,
);
$this->drupalPost('user/' . $admin_user->uid . '/edit', $edit, t('Save'));
// Verify that Structure » Content types appears.
$this->assertLinkTrailByTitle(array(t('Structure'), t('Content types')));
// Delete the role.
$this->drupalPost('admin/people/permissions/roles/edit/' . $test_rid, array(), t('Delete role'));
$this->drupalPost(NULL, array(), t('Delete'));
// Verify that Structure » Content types does not appear.
$this->assertNoLinkTrailByTitle(array(t('Structure'), t('Content types')));
}
}
/**
* Tests appearance, localization, and escaping of dynamic links.
*/
class AdminMenuDynamicLinksTestCase extends AdminMenuWebTestCase {
public static function getInfo() {
return array(
'name' => 'Dynamic links',
'description' => 'Tests appearance, localization, and escaping of dynamic links.',
'group' => 'Administration menu',
);
}
function setUp() {
parent::setUp(array('node'));
}
/**
* Tests node type links.
*/
function testNode() {
$type = $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Create a content-type with special characters.
$type = $this->drupalCreateContentType(array('type' => 'special', 'name' => 'Cool & Special'));
$permissions = $this->basePermissions + array(
'administer content types',
'create article content',
'create special content',
);
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
// Verify that dynamic links are displayed.
$this->drupalGet('');
$this->assertElementByXPath('//div[@id="admin-menu"]', array(), t('Administration menu found.'));
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path)]', array(':path' => 'admin/structure/types'), "Structure » Content types link found.");
// Verify link title output escaping.
$this->assertNoRaw('Cool & Special');
$this->assertRaw(check_plain('Cool & Special'));
// Verify Manage content type links.
$links = array(
'admin/structure/types/manage/article' => 'Article',
'admin/structure/types/manage/special' => 'Cool & Special',
);
foreach ($links as $path => $title) {
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path) and text()=:title]', array(
':path' => $path,
':title' => $title,
), "Structure » Content types » $title link found.");
}
// Verify Add content links.
$links = array(
'node/add/article' => 'Article',
'node/add/special' => 'Cool & Special',
);
foreach ($links as $path => $title) {
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path) and text()=:title]', array(
':path' => $path,
':title' => $title,
), "Add content » $title link found.");
}
}
/**
* Tests Add content links.
*/
function testNodeAdd() {
$type = $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Verify that "Add content" does not appear for unprivileged users.
$permissions = $this->basePermissions + array(
'access content',
);
$this->web_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->web_user);
$this->assertNoText(t('Add content'));
// Verify "Add content" appears below "Content" for administrative users.
$permissions = $this->basePermissions + array(
'access content overview',
'access content',
'create article content',
);
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
$this->assertLinkTrailByTitle(array(
t('Content'),
t('Add content'),
));
// Verify "Add content" appears on the top-level for regular users.
$permissions = $this->basePermissions + array(
'access content',
'create article content',
);
$this->web_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->web_user);
$this->assertLinkTrailByTitle(array(
t('Add content'),
));
}
}
/**
* Tests appearance of different types of links.
*/
class AdminMenuLinkTypesTestCase extends AdminMenuWebTestCase {
public static function getInfo() {
return array(
'name' => 'Link types',
'description' => 'Tests appearance of different types of links.',
'group' => 'Administration menu',
);
}
function setUp() {
parent::setUp(array('help'));
$permissions = module_invoke_all('permission');
$permissions = array_keys($permissions);
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
}
/**
* Tests appearance of different router item link types.
*/
function testLinkTypes() {
// Verify that MENU_NORMAL_ITEMs appear.
$this->assertLinkTrailByTitle(array(
t('Configuration'),
t('System'),
t('Site information'),
));
// Verify that MENU_LOCAL_TASKs appear.
$this->assertLinkTrailByTitle(array(t('People'), t('Permissions')));
$this->assertLinkTrailByTitle(array(t('Appearance'), t('Settings')));
$this->assertLinkTrailByTitle(array(t('Modules'), t('Uninstall')));
// Verify that MENU_LOCAL_ACTIONs appear.
$this->assertLinkTrailByTitle(array(
t('People'),
t('Add user'),
));
// Verify that MENU_DEFAULT_LOCAL_TASKs do NOT appear.
$this->assertNoLinkTrailByTitle(array(t('Modules'), t('List')));
$this->assertNoLinkTrailByTitle(array(t('People'), t('List')));
$this->assertNoLinkTrailByTitle(array(t('People'), t('Permissions'), t('Permissions')));
$this->assertNoLinkTrailByTitle(array(t('Appearance'), t('List')));
// Verify that MENU_VISIBLE_IN_BREADCRUMB items (exact type) do NOT appear.
$this->assertNoLinkTrailByTitle(array(t('Modules'), t('Uninstall'), t('Uninstall')));
$this->assertNoLinkTrailByTitle(array(t('Help'), 'admin_menu'));
// Verify that special "Index" link appears below icon.
$this->assertElementByXPath('//div[@id="admin-menu"]//a[contains(@href, :path) and text()=:title]', array(
':path' => 'admin/index',
':title' => t('Index'),
), "Icon » Index link found.");
}
}
/**
* Tests customized menu links.
*/
class AdminMenuCustomizedTestCase extends AdminMenuWebTestCase {
public static function getInfo() {
return array(
'name' => 'Customized links',
'description' => 'Tests customized menu links.',
'group' => 'Administration menu',
);
}
function setUp() {
parent::setUp(array('menu'));
$this->admin_user = $this->drupalCreateUser($this->basePermissions + array(
'administer menu',
));
$this->drupalLogin($this->admin_user);
}
/**
* Test disabled custom links.
*/
function testCustomDisabled() {
$type = $this->drupalCreateContentType();
$node = $this->drupalCreateNode(array('type' => $type->type));
$text = $this->randomName();
$xpath = $this->buildXPathQuery('//div[@id=:id]//a[contains(text(), :text)]', array(
':id' => 'admin-menu',
':text' => $text,
));
// Verify that the link does not appear in the menu.
$this->drupalGet('node');
$elements = $this->xpath($xpath);
$this->assertFalse($elements, 'Custom link not found.');
// Add a custom link to the node to the menu.
$edit = array(
'link_path' => 'node/' . $node->nid,
'link_title' => $text,
'parent' => 'management:' . $this->queryMlidByPath('admin'),
);
$this->drupalPost('admin/structure/menu/manage/management/add', $edit, t('Save'));
// Verify that the link appears in the menu.
$this->drupalGet('node');
$elements = $this->xpath($xpath);
$this->assertTrue($elements, 'Custom link found.');
// Disable the link.
$edit = array(
'enabled' => FALSE,
);
$this->drupalPost('admin/structure/menu/item/' . $this->queryMlidByPath('node/' . $node->nid) . '/edit', $edit, t('Save'));
// Verify that the disabled link does not appear in the menu.
$this->drupalGet('node');
$elements = $this->xpath($xpath);
$this->assertFalse($elements, 'Disabled custom link not found.');
}
/**
* Tests external links.
*/
function testCustomExternal() {
// Add a custom link to the node to the menu.
$edit = array(
'link_path' => 'http://example.com',
'link_title' => 'Example',
'parent' => 'management:' . $this->queryMlidByPath('admin'),
);
$this->drupalPost('admin/structure/menu/manage/management/add', $edit, t('Save'));
// Verify that the link appears in the menu.
$this->drupalGet('');
$elements = $this->xpath('//div[@id=:id]//a[@href=:href and contains(text(), :text)]', array(
':id' => 'admin-menu',
':href' => $edit['link_path'],
':text' => $edit['link_title'],
));
$this->assertTrue($elements, 'External link found.');
}
/**
* Returns the menu link ID for a given link path in the management menu.
*/
protected function queryMlidByPath($path) {
return db_query('SELECT mlid FROM {menu_links} WHERE menu_name = :menu AND link_path = :path', array(
':menu' => 'management',
':path' => $path,
))->fetchField();
}
}

View File

@@ -0,0 +1,274 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
Cambridge, MA 02139, 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 Library 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

View File

@@ -0,0 +1,52 @@
/* $Id: README.txt,v 1.1.2.2.2.1 2008/12/13 09:22:36 davyvandenbremt Exp $ */
Description
-----------
Drupal allows you to define a different theme for administration pages (Administer -> Site configuration -> Administration theme). By default this only applies to pages with a path starting with 'admin' and content editing pages.
The Administration theme module adds a few more option to the default configuration page like :
- Use administration theme for batch processing
- Use administration theme for code reviews
- ...
Some of these pages will only appear if they apply to your installation, i.e. you have the module installed which generates these pages.
You also have the option to define a custom set of Drupal paths or aliases to apply the administration theme for.
Requirements
------------
This module requires Drupal 7. A Drupal 5 and 6 version are available.
Installation
------------
1) Copy/upload the admin_theme module folder to the sites/all/modules
directory of your Drupal installation.
2) Enable the Administration theme module in Drupal (administer -> modules).
Configuration
-------------
You can enable/disable the administration theme on the administration theme
configuration page.
Administration theme can be configured at :
Administer -> Site configuration -> Administration theme
Developers
----------
You can add define extra pages where the administration theme should be applied to by implementing the hook_admin_theme_info and hook_admin_theme_check hooks in your modules.
The first one gets all "options" and the second one checks if each of those options should should be applied to a path. Check out admin_theme_admin_theme_info and admin-theme_admin_theme_check for an example implementation.
Author
------
Davy Van Den Bremt <info@davyvandenbremt.be>
http://www.davyvandenbremt.be

View File

@@ -0,0 +1,90 @@
<?php
// $Id: admin_theme.api.php,v 1.1.2.1 2008/12/13 09:47:29 davyvandenbremt Exp $
/**
* @file
* Hooks provided by the Administration theme module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Add more options to the administration theme settings page.
*
* This hook allows modules to add more options to the administration theme
* settings page.
*
* @return
* A linear array of associative arrays. The keys of the linear array are
* the identifiers for the "options" that will be check for in
* hook_admin_theme_check. The associative arrays have keys:
* - "title": The title to display on the checkbox on the administration
* theme settings page.
* - "description": The description to display on the checkbox on the
* administration theme settings page.
*/
function hook_admin_theme_info() {
$options = array();
$options['batch'] = array(
'title' => t('Use administration theme for batch processing'),
'description' => t('Use the administration theme when executing batch operations.'),
);
if (module_exists('coder')) {
$options['coder'] = array(
'title' => t('Use administration theme for code reviews'),
'description' => t('Use the administration theme when viewing Coder code reviews.'),
);
}
if (module_exists('service_attachments')) {
$options['service_attachments'] = array(
'title' => t('Use administration theme for viewing the service attachments form on nodes.'),
'description' => t('Use the administration theme when viewing service attachments on nodes.'),
);
}
if (module_exists('webform')) {
$options['webform_results'] = array(
'title' => t('Use administration theme for viewing webform submissions.'),
'description' => t('Use the administration theme when viewing webform submissions.'),
);
}
if (module_exists('statistics')) {
$options['statistics'] = array(
'title' => t('Use administration theme for viewing pages of the statistics module.'),
'description' => t('Use the administration theme when viewing pages of the statistics module.'),
);
}
return $options;
}
/**
* Check if an option is "on" for the current page.
*
* This hook allows modules to check for each option defined in
* hook_admin_theme_info if the option is "on".
*
* @param
* $option. The option to check.
* @return
* TRUE or FALSE indicating if the administration theme should be used.
*/
function hook_admin_theme_check($option = NULL) {
switch ($option) {
case 'coder':
return arg(0) == 'coder';
case 'batch':
return arg(0) == 'batch';
case 'service_attachments':
return arg(0) == 'node' && arg(2) == 'service_attachments';
case 'webform_results':
return arg(0) == 'node' && arg(2) == 'webform-results';
case 'statistics':
return (arg(0) == 'node' || arg(0) == 'user') && arg(2) == 'track';
}
}
/**
* @} End of "addtogroup hooks".
*/

View File

@@ -0,0 +1,14 @@
; $Id: admin_theme.info,v 1.1.6.5 2010/03/27 06:39:43 davyvandenbremt Exp $
name = Administration theme
description = Enable the administration theme on more pages than possible with Drupal's default administration page.
core = 7.x
package = Administration
files[] = admin_theme.module
files[] = admin_theme.install
configure = admin/appearance
; Information added by drupal.org packaging script on 2010-12-06
version = "7.x-1.0"
core = "7.x"
project = "admin_theme"
datestamp = "1291630844"

View File

@@ -0,0 +1,43 @@
<?php
// $Id: admin_theme.install,v 1.1.2.2.4.4 2009/10/20 18:25:45 davyvandenbremt Exp $
/**
* Implementation of hook_install().
*/
function admin_theme_install() {
// updating module weight to 10 to make it run after system (for user access checks etc)
db_query("UPDATE {system} SET weight = 10 WHERE name = 'admin_theme'");
$link = array('!link' => l(t('Administer > Appearance > Administration theme'), 'admin/appearance'));
drupal_set_message(t("Administration theme module settings are available under !link", $link));
}
/**
* Implementation of hook_uninstall().
*/
function admin_theme_uninstall() {
// cleaning up general admin theme variables
variable_del('admin_theme_path');
variable_del('admin_theme_path_disallow');
// cleaning up module defined admin theme variables
// we need to add admin theme's explicitly because it's not in the list of modules anymore
$admin_theme_options = admin_theme_admin_theme_info();
$options = array();
foreach ($admin_theme_options as $option => $info) {
$info['option'] = $option;
$info['module'] = 'admin_theme';
$options[] = $info;
}
// mergin admin theme's options with other module options
// @fixme does this work if other modules are also uninstalled at the same time?
$list = array_merge(admin_theme_list(), $options);
// deleting the module defined variables
foreach ($list as $info) {
$var = admin_theme_variable_name($info['module'], $info['option']);
variable_del($var);
}
}

View File

@@ -0,0 +1,249 @@
<?php
// $Id: admin_theme.module,v 1.1.2.8.2.12 2010/12/06 10:10:22 davyvandenbremt Exp $
/**
* @file
* Enable the administration theme on more pages then possible with Drupal's default administration page.
*/
/**
* Implementation of hook_perm().
*/
function admin_theme_permission() {
return array(
'access admin theme' => array(
'title' => t('Access administration theme'),
'description' => t('View pages using the administration theme'),
)
);
}
/**
* Get the variable name for a certain option.
*
* @param $module
* String. Module that defines this option.
* @param $params
* String. Name of the option.
* @return
* String. Variable name for the option.
*/
function admin_theme_variable_name($module, $option) {
return 'admin_theme_'. $module .'_'. $option;
}
/**
* Get all module defined options.
*
* @return
* Array. All options.
*/
function admin_theme_list() {
$options = array();
foreach (module_list() as $module) {
$module_options = module_invoke($module, 'admin_theme_info');
if (count($module_options) > 0) {
foreach ($module_options as $option => $info) {
$info['option'] = $option;
$info['module'] = $module;
$options[] = $info;
}
}
}
return $options;
}
/**
* Implementation of hook_form_alter().
*/
function admin_theme_form_system_themes_admin_form_alter(&$form, $form_state) {
// define a fieldset for the page selection
$form['admin_theme']['pages'] = array(
'#type' => 'fieldset',
'#title' => t('Pages'),
'#collapsible' => TRUE,
'#description' => t('Choose which pages should be displayed with the administration theme.')
);
// add the content editing option to the pages fieldset and change the title
$form['admin_theme']['pages']['node_admin_theme'] = $form['admin_theme']['node_admin_theme'];
$form['admin_theme']['pages']['node_admin_theme']['#title'] = t('Content editing');
unset($form['admin_theme']['node_admin_theme']);
// add all options as checkboxes to the admin theme settings form
$list = admin_theme_list();
foreach ($list as $info) {
$var = admin_theme_variable_name($info['module'], $info['option']);
$form['admin_theme']['pages'][$var] = array(
'#type' => 'checkbox',
'#title' => array_key_exists('title', $info) ? $info['title'] : NULL,
'#description' => array_key_exists('description', $info) ? $info['description'] : NULL,
'#default_value' => variable_get($var, '0'),
);
}
// allow the user to define a set of pages where the admin theme should or should not be applied to
$form['admin_theme']['pages']['custom'] = array(
'#type' => 'fieldset',
'#title' => t('Custom'),
'#description' => t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>')),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#weight' => 9,
);
$form['admin_theme']['pages']['custom']['admin_theme_path'] = array(
'#type' => 'textarea',
'#title' => t('Use administration theme on the following pages'),
'#default_value' => variable_get('admin_theme_path', ''),
);
$form['admin_theme']['pages']['custom']['admin_theme_path_disallow'] = array(
'#type' => 'textarea',
'#title' => t('Do not use administration theme on the following pages'),
'#description' => t('If a path appears here, the administration theme is not shown even if all above options apply.'),
'#default_value' => variable_get('admin_theme_path_disallow', ''),
);
$form['#submit'][] = 'admin_theme_form_system_themes_form_alter_submit';
$form['admin_theme']['actions']['#weight'] = 10;
}
/**
* Process system_themes_form additions submissions.
*/
function admin_theme_form_system_themes_form_alter_submit($form, &$form_state) {
// module options
$list = admin_theme_list();
foreach ($list as $info) {
$var = admin_theme_variable_name($info['module'], $info['option']);
if (isset($form_state['values'][$var])) {
variable_set($var, $form_state['values'][$var]);
}
}
// custom page options
variable_set('admin_theme_path', $form_state['values']['admin_theme_path']);
variable_set('admin_theme_path_disallow', $form_state['values']['admin_theme_path_disallow']);
}
/**
* Implementation of hook_custom_theme().
*/
function admin_theme_custom_theme() {
$admin_theme_disallow = FALSE;
$admin_theme = FALSE;
// check if some paths are disallow to get the theme
if (trim(variable_get('admin_theme_path_disallow', '')) != '') {
// pages that are defined by their normal path
$admin_theme_disallow = drupal_match_path($_GET['q'], variable_get('admin_theme_path_disallow', ''));
// pages that are defined with their alias
$alias = drupal_get_path_alias($_GET['q']);
if ($alias != $_GET['q']) {
$admin_theme_disallow = $admin_theme || drupal_match_path($alias, variable_get('admin_theme_path_disallow', ''));
}
}
// we should not show the admin theme if the user has no access or the path is in the disallow list
if (!user_access('access admin theme') || $admin_theme_disallow) {
return;
}
// check if an option is enabled and if it results to TRUE
$list = admin_theme_list();
foreach ($list as $info) {
$var = admin_theme_variable_name($info['module'], $info['option']);
if ((bool)variable_get($var, '0') && module_invoke($info['module'], 'admin_theme', 'check', $info['option'])) {
$admin_theme = TRUE;
}
}
// some custom defined pages should get admin theme
if (trim(variable_get('admin_theme_path', '')) != '') {
// pages that are defined by their normal path
$admin_theme = $admin_theme || drupal_match_path($_GET['q'], variable_get('admin_theme_path', ''));
// pages that are defined with their alias
$alias = drupal_get_path_alias($_GET['q']);
if ($alias != $_GET['q']) {
$admin_theme = $admin_theme || drupal_match_path($alias, variable_get('admin_theme_path', ''));
}
}
// Use the admin theme for the current request (if global admin theme setting is checked).
if ($admin_theme) {
return variable_get('admin_theme');
}
return;
}
/**
* Implementation of hook_admin_theme_info().
*/
function admin_theme_admin_theme_info() {
$options = array();
$options['batch'] = array(
'title' => t('Batch processing'),
'description' => t('Use the administration theme when executing batch operations.'),
);
if (module_exists('img_assist')) {
$options['img_assist'] = array(
'title' => t('Image assist'),
'description' => t('Use the administration theme when viewing the Image assist popup window.'),
);
}
if (module_exists('coder')) {
$options['coder'] = array(
'title' => t('Code reviews'),
'description' => t('Use the administration theme when viewing Coder code reviews.'),
);
}
if (module_exists('devel')) {
$options['devel'] = array(
'title' => t('Devel pages.'),
'description' => t('Use the administration theme when viewing pages of the devel module (hook_elements(), Dev render, Dev load, Session viewer, Theme registery, Variable editor, ...).'),
);
}
if (module_exists('service_attachments')) {
$options['service_attachments'] = array(
'title' => t('Service attachments form on nodes.'),
'description' => t('Use the administration theme when viewing service attachments on nodes.'),
);
}
if (module_exists('webform')) {
$options['webform_results'] = array(
'title' => t('Webform submissions.'),
'description' => t('Use the administration theme when viewing webform submissions.'),
);
}
if (module_exists('statistics')) {
$options['statistics'] = array(
'title' => t('Pages defined by the statistics module.'),
'description' => t('Use the administration theme when viewing pages of the statistics module.'),
);
}
return $options;
}
/**
* Implementation of hook_admin_theme_check().
*/
function admin_theme_admin_theme_check($option = NULL) {
switch ($option) {
case 'img_assist':
return arg(0) == 'img_assist';
case 'coder':
return arg(0) == 'coder';
case 'devel':
return arg(0) == 'devel' || (arg(0) == 'node' && arg(2) == 'devel');
case 'batch':
return arg(0) == 'batch';
case 'service_attachments':
return arg(0) == 'node' && arg(2) == 'service_attachments';
case 'webform_results':
return arg(0) == 'node' && arg(2) == 'webform-results';
case 'statistics':
return (arg(0) == 'node' || arg(0) == 'user') && arg(2) == 'track';
}
}

View File

@@ -0,0 +1,122 @@
# $Id: admin_theme.pot,v 1.1.4.2 2008/12/15 16:08:50 davyvandenbremt Exp $
#
# LANGUAGE translation of Drupal (general)
# Copyright YEAR NAME <EMAIL@ADDRESS>
# Generated from files:
# admin_theme.module,v 1.1.2.9 2008/12/13 09:17:01 davyvandenbremt
# admin_theme.install,v 1.1.2.2 2008/12/08 18:37:44 davyvandenbremt
# admin_theme.info,v 1.1 2008/11/14 21:34:23 davyvandenbremt
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"POT-Creation-Date: 2008-12-15 16:59+0100\n"
"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\n"
"Last-Translator: NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <EMAIL@ADDRESS>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
#: admin_theme.module:61
msgid "Theme"
msgstr ""
#: admin_theme.module:74
msgid "Pages"
msgstr ""
#: admin_theme.module:76
msgid "Choose which pages should be displayed with the administration theme."
msgstr ""
#: admin_theme.module:81
msgid "Content editing"
msgstr ""
#: admin_theme.module:99
msgid "Custom"
msgstr ""
#: admin_theme.module:100
msgid "Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page."
msgstr ""
#: admin_theme.module:107
msgid "Use administration theme on the following pages."
msgstr ""
#: admin_theme.module:112
msgid "Do not use administration theme on the following pages."
msgstr ""
#: admin_theme.module:113
msgid "If a path appears here, the administration theme is not shown even if all above options apply."
msgstr ""
#: admin_theme.module:186
msgid "Batch processing"
msgstr ""
#: admin_theme.module:187
msgid "Use the administration theme when executing batch operations."
msgstr ""
#: admin_theme.module:191
msgid "Code reviews"
msgstr ""
#: admin_theme.module:192
msgid "Use the administration theme when viewing Coder code reviews."
msgstr ""
#: admin_theme.module:197
msgid "Service attachments form on nodes."
msgstr ""
#: admin_theme.module:198
msgid "Use the administration theme when viewing service attachments on nodes."
msgstr ""
#: admin_theme.module:203
msgid "Webform submissions."
msgstr ""
#: admin_theme.module:204
msgid "Use the administration theme when viewing webform submissions."
msgstr ""
#: admin_theme.module:209
msgid "Pages defined by the statistics module."
msgstr ""
#: admin_theme.module:210
msgid "Use the administration theme when viewing pages of the statistics module."
msgstr ""
#: admin_theme.module:13
msgid "access admin theme"
msgstr ""
#: admin_theme.module:0
msgid "admin_theme"
msgstr ""
#: admin_theme.install:8
msgid "Administer > Site configuration > Administration theme"
msgstr ""
#: admin_theme.install:9
msgid "Administration theme module settings are available under !link"
msgstr ""
#: admin_theme.info:0
msgid "Administration theme"
msgstr ""
#: admin_theme.info:0
msgid "Enable the administration theme on more pages then possible with Drupal's default administration page."
msgstr ""

View File

@@ -0,0 +1,122 @@
# $Id: nl.po,v 1.2.2.2.4.1 2008/12/15 16:08:50 davyvandenbremt Exp $
#
# Dutch translation of Drupal (general)
# Copyright YEAR NAME <EMAIL@ADDRESS>
# Generated from files:
# admin_theme.module,v 1.1.2.9 2008/12/13 09:17:01 davyvandenbremt
# admin_theme.install,v 1.1.2.2 2008/12/08 18:37:44 davyvandenbremt
# admin_theme.info,v 1.1 2008/11/14 21:34:23 davyvandenbremt
#
msgid ""
msgstr ""
"Project-Id-Version: Administration Theme\n"
"POT-Creation-Date: 2008-11-29 10:18+0100\n"
"PO-Revision-Date: 2008-11-29 10:27+0100\n"
"Last-Translator: Davy Van Den Bremt <info@davyvandenbremt.be>\n"
"Language-Team: Davy Van Den Bremt <info@davyvandenbremt.be>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-Language: Dutch\n"
#: admin_theme.module:61
msgid "Theme"
msgstr "Template"
#: admin_theme.module:74
msgid "Pages"
msgstr "Pagina's"
#: admin_theme.module:76
msgid "Choose which pages should be displayed with the administration theme."
msgstr "Kies welke pagina's met de beheertemplate getoond moeten worden."
#: admin_theme.module:81
msgid "Content editing"
msgstr "Bewerken van inhoud"
#: admin_theme.module:99
msgid "Custom"
msgstr "Specifiek"
#: admin_theme.module:100
msgid "Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page."
msgstr "Geef één pagina per regel op, als Drupal-paden. Het '*'-teken is een jokerteken. Voorbeeldpaden zijn '%blog' voor de blog-pagina en '%blog-wildcard' voor elke persoonlijke blog. '%front' is de voorpagina."
#: admin_theme.module:107
msgid "Use administration theme on the following pages."
msgstr "Gebruik de beheertemplate voor de volgende pagina's."
#: admin_theme.module:112
msgid "Do not use administration theme on the following pages."
msgstr "Gebruik de beheertemplate niet voor de volgende pagina's."
#: admin_theme.module:113
msgid "If a path appears here, the administration theme is not shown even if all above options apply."
msgstr "Wanneer een pad hier vermeld wordt, word de beheertemplate niet getoond, zelfs als bovenstaande opties van toepassing zijn."
#: admin_theme.module:186
msgid "Batch processing"
msgstr "Batch verwerking"
#: admin_theme.module:187
msgid "Use the administration theme when executing batch operations."
msgstr "Gebruik de beheertemplate tijdens het verwerken van batch handelingen."
#: admin_theme.module:191
msgid "Code reviews"
msgstr "Code revisies"
#: admin_theme.module:192
msgid "Use the administration theme when viewing Coder code reviews."
msgstr "Gebruik de beheertemplate tijdens het bekijken van Coder's code revisies."
#: admin_theme.module:197
msgid "Service attachments form on nodes."
msgstr "Service attachments formulier bij nodes."
#: admin_theme.module:198
msgid "Use the administration theme when viewing service attachments on nodes."
msgstr "Gebruik de beheertemplate tijdens het bekijken van het service attachments formulier bij nodes."
#: admin_theme.module:203
msgid "Webform submissions."
msgstr "Webformulier inzendingen."
#: admin_theme.module:204
msgid "Use the administration theme when viewing webform submissions."
msgstr "Gebruik de beheertemplate tijdens het bekijken van webformulier inzendingen."
#: admin_theme.module:209
msgid "Pages defined by the statistics module."
msgstr "Pagina's van de statistics module"
#: admin_theme.module:210
msgid "Use the administration theme when viewing pages of the statistics module."
msgstr "Gebruik de beheertemplate tijdens het bekijken van pagina's van de statistics module."
#: admin_theme.module:13
msgid "access admin theme"
msgstr "toegang tot beheertemplate"
#: admin_theme.module:0
msgid "admin_theme"
msgstr "admin_theme"
#: admin_theme.install:8
msgid "Administer > Site configuration > Administration theme"
msgstr "Beheren > Site-instellingen > Beheertemplate"
#: admin_theme.install:9
msgid "Administration theme module settings are available under !link"
msgstr "Instellingen voor de Administration theme module zijn beschikbaar onder !link"
#: admin_theme.info:0
msgid "Administration theme"
msgstr "Beheertemplate"
#: admin_theme.info:0
msgid "Enable the administration theme on more pages then possible with Drupal's default administration page."
msgstr "Gebruik de beheertemplate op meer pagina's dan instelbaar met Drupal's standaard beheer pagina."

View File

@@ -0,0 +1,6 @@
; $Id$
name = Administer Users by Role
description = "Allows users with 'administer users' permission and a role (specified in 'Permissions') to edit/delete other users with a specified role. Also provides control over user creation."
core = 7.x
files[] = administerusersbyrole.module

View File

@@ -0,0 +1,98 @@
<?php
/**
* @file
* Allows users with 'administer users' permission and a role (specified in 'Permissions') to edit/delete other users with a specified role. If the user being edited has multiple roles, the user doing the editing must have permission to edit ALL of the user being edited's roles. Also provides control over user creation. Works well in conjunction with <a href='http://drupal.org/project/role_delegation'>role_delegation</a>.
*/
/**
* Implements hook_permission().
*/
function administerusersbyrole_permission() {
$roles = db_query('SELECT name, rid FROM {role} WHERE rid > 1 ORDER BY name')->fetchAll();
$perms = array();
$perms['create users'] = array('title' => 'Create new users');
foreach ($roles as &$role) {
$perms['edit users with role '. $role->rid] = array('title' => 'Edit users that have the role '. $role->name);
$perms['delete users with role '. $role->rid] = array('title' => 'Delete users that have the role '. $role->name);
}
return $perms;
}
/**
* Implements hook_menu_alter().
*/
function administerusersbyrole_menu_alter(&$items) {
$items['user/%user/edit']['access callback'] = '_administerusersbyrole_can_edit_user';
$items['user/%user/cancel']['access callback'] = '_administerusersbyrole_can_delete_user';
$items['admin/people/create']['access arguments'] = array('create users');
}
/**
* Custom access callback for edit user.
*/
function _administerusersbyrole_can_edit_user($account) {
global $user;
if($account->uid == $user->uid)
return TRUE;
if($account->uid == 1)
return FALSE;
elseif(user_access('edit users with role '.DRUPAL_AUTHENTICATED_RID))
return TRUE;
foreach ($account->roles as $rid => $role) {
if($rid == DRUPAL_AUTHENTICATED_RID)
continue;
if(!user_access('edit users with role '. $rid))
return FALSE;
}
return TRUE;
}
/**
* Custom access callback for delete user.
*/
function _administerusersbyrole_can_delete_user($account) {
if ($account->uid == 1) {
return FALSE;
}
$permitted = TRUE;
foreach ($account->roles as $rid => $role) {
$permitted = user_access('delete users with role '. $rid);
if (!$permitted) {
return FALSE;
}
}
return TRUE;
}
/**
* Implements hook_form_user_admin_account_alter().
*/
function administerusersbyrole_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
// Remove edit links if i don't have access to them.
foreach ($form['accounts']['#options'] as $uid => $fields) {
$account = user_load($uid);
if (!_administerusersbyrole_can_edit_user($account)) {
$form['accounts']['#options'][$uid]['operations'] = '';
}
}
}
/**
* Implements hook_form_user_profile_form_alter().
*/
function administerusersbyrole_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
// Hide delete link if i don't have access.
$account = $form['#user'];
if (!_administerusersbyrole_can_delete_user($account)) {
$form['actions']['cancel']['#access'] = FALSE;
}
}

View File

@@ -0,0 +1 @@
http://drupal.org/node/908424#comment-5765302

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 @@
-------------------------------------------------------------------------------
Backup and Migrate 2 for Drupal 7.x
by Ronan Dowling, Gorton Studios - ronan (at) gortonstudios (dot) com
-------------------------------------------------------------------------------
DESCRIPTION:
This module makes the task of backing up your Drupal database and migrating data
from one Drupal install to another easier. It provides a function to backup the
entire database to file or download, and to restore from a previous backup. You
can also schedule the backup operation. Compression of backup files is also
supported.
There are options to exclude the data from certain tables (such as cache or
search index tables) to increase efficiency by ignoring data that does not need
to be backed up or migrated.
The backup files are a list of SQL statements which can be executed with a tool
such as phpMyAdmin or the command-line mysql client.
-------------------------------------------------------------------------------
INSTALLATION:
* Put the module in your Drupal modules directory and enable it in
admin/modules.
* Go to admin/people/permissions and grant permission to any roles that need to be
able to backup or restore the database.
* Configure and use the module at admin/config/system/backup_migrate
OPTIONAL:
* Enable token.module to allow token replacement in backup file names.
* To Backup to Amazon S3:
- Download the S3 library from http://undesigned.org.za/2007/10/22/amazon-s3-php-class
and place the file 'S3.php' in the includes directory in this module.
The stable version (0.4.0 20th Jul 2009) works best with Backup and Migrate.
LIGHTTPD USERS:
Add the following code to your lighttp.conf to secure your backup directories:
$HTTP["url"] =~ "^/sites/default/files/backup_migrate/" {
url.access-deny = ( "" )
}
You may need to adjust the path to reflect the actual path to the files.
IIS 7 USERS:
Add the following code to your web.config code to secure your backup directories:
<rule name="postinst-redirect" stopProcessing="true">
<match url="sites/default/files/backup_migrate" />
<action type="Rewrite" url=""/>
</rule>
You may need to adjust the path to reflect the actual path to the files.
-------------------------------------------------------------------------------
VERY IMPORTANT SECURITY NOTE:
Backup files may contain sensitive data and by default, are saved to your web
server in a directory normally accessible by the public. This could lead to a
very serious security vulnerability. Backup and Migrate attempts to protect
backup files using a .htaccess file, but this is not guaranteed to work on all
environments (and is guaranteed to fail on web servers that are not apache). You
should test to see if your backup files are publicly accessible, and if in doubt
do not save backups to the server, or use the destinations feature to save to a
folder outside of your webroot.
OTHER WARNINGS:
A failed restore can destroy your database and therefore your entire Drupal
installation. ALWAYS TEST BACKUP FILES ON A TEST ENVIRONMENT FIRST. If in doubt
do not use this module.
This module has only been tested with MySQL and does not work with any other dbms.
If you have experiences with Postgres or any other dbms and are willing to help
test and modify the module to work with it, please contact the developer at
ronan (at) gortonstudios (dot) com.
Make sure your php timeout is set high enough to complete a backup or restore
operation. Larger databases require more time. Also, while the module attempts
to keep memory needs to a minimum, a backup or restore will require
significantly more memory then most Drupal operations.
If your backup file contains the 'sessions' table all other users will be logged
out after you run a restore. To avoid this, exclude the sessions table when
creating your backups. Be aware though that you will need to recreate the
sessions table if you use this backup on an empty database.
Do not change the file extension of backup files or the restore function will be
unable to determine the compression type the file and will not function
correctly.
IF A RESTORE FAILS:
Don't panic, the restore file should work with phpMyAdmin's import function, or
with the mysql command line tool. If it does not, then it is likely corrupt; you
may panic now. MAKE SURE THAT THIS MODULE IS NOT YOUR ONLY FORM OF BACKUP.
-------------------------------------------------------------------------------

View File

@@ -0,0 +1,42 @@
.schedule-list-disabled {
filter:alpha(opacity=50);
-moz-opacity: .50;
opacity: .50;
}
.backup-migrate-cache-time {
font-size: 0.85em;
}
.backup-migrate-tables-checkboxes .form-item {
margin: 0;
}
.backup-migrate-tables-checkboxes .form-item label {
width: 15em;
float: left;
overflow: hidden;
white-space: nowrap;
height: 1.75em;
margin: .25em .25em 0 0;
}
.backup-migrate-tables-checkboxes .form-item label.checked {
background-color: #eee;
}
.backup-migrate-tables-checkboxes .form-item label input {
margin-right: .25em;
}
div.backup-migrate-tables-checkboxes {
max-height: 40em;
overflow: auto;
}
div.backup-migrate-description {
font-size: smaller;
}
div.row-error {
color: #FF0000;
font-weight: bold;
}

View File

@@ -0,0 +1,17 @@
name = Backup and Migrate
description = "Backup or migrate the Drupal Database quickly and without unnecessary data."
core = 7.x
files[] = backup_migrate.module
files[] = backup_migrate.install
files[] = includes/destinations.inc
files[] = includes/profiles.inc
files[] = includes/schedules.inc
configure = admin/config/system/backup_migrate
; Information added by packaging script on 2013-11-05
version = "7.x-2.8"
core = "7.x"
project = "backup_migrate"
datestamp = "1383686305"

View File

@@ -0,0 +1,506 @@
<?php
/**
* @file
* Install hooks for Backup and Migrate.
*/
/**
* Implementation of hook_requirements().
*/
function backup_migrate_requirements($phase) {
$requirements = array();
return $requirements;
}
/**
* Implementation of hook_schema().
*/
function backup_migrate_schema() {
$schema['backup_migrate_profiles'] = array(
'fields' => array(
'profile_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a profile.',
),
'name' => array(
'description' => 'The name of the profile.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'filename' => array(
'description' => 'The name of the profile.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'append_timestamp' => array(
'description' => 'Append a timestamp to the filename.',
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0
),
'timestamp_format' => array(
'description' => 'The format of the timestamp.',
'type' => 'varchar',
'length' => 14,
'not null' => TRUE
),
'filters' => array(
'description' => 'The filter settings for the profile.',
'type' => 'text',
'not null' => TRUE,
'serialize' => TRUE,
'serialized default' => 'a:0:{}',
),
),
'primary key' => array('profile_id'),
);
$schema['backup_migrate_destinations'] = array(
'fields' => array(
'destination_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a profile.',
),
'name' => array(
'description' => 'The name of the profile.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'type' => array(
'description' => 'The type of the destination.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE
),
'location' => array(
'description' => 'The the location string of the destination.',
'type' => 'text',
'not null' => TRUE
),
'settings' => array(
'description' => 'Other settings for the destination.',
'type' => 'text',
'not null' => TRUE,
'serialize' => TRUE,
'serialized default' => 'a:0:{}',
),
),
'primary key' => array('destination_id'),
);
$schema['backup_migrate_schedules'] = array(
'fields' => array(
'schedule_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a profile.',
),
'name' => array(
'description' => 'The name of the profile.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'source_id' => array(
'description' => 'The {backup_migrate_destination}.destination_id of the source to backup from.',
'type' => 'varchar',
'length' => 255,
'default' => 'db',
'not null' => TRUE
),
'destination_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The {backup_migrate_destination}.destination_id of the destination to back up to.',
),
'profile_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a profile.',
),
'keep' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The number of backups to keep.',
),
'period' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The number of seconds between backups.',
),
'enabled' => array(
'description' => 'Whether the schedule is enabled.',
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0
),
'cron' => array(
'description' => 'Whether the schedule should be run during cron.',
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0
),
),
'primary key' => array('schedule_id'),
);
return $schema;
}
/**
* Implementation of hook_install().
*/
function backup_migrate_install() {
_backup_migrate_setup_database_defaults();
}
function _backup_migrate_setup_database_defaults() {
if (variable_get("backup_migrate_file_name", NULL)) {
require_once DRUPAL_ROOT . '/'. drupal_get_path('module', 'backup_migrate') .'/includes/crud.inc';
require_once DRUPAL_ROOT . '/'. drupal_get_path('module', 'backup_migrate') .'/backup_migrate.module';
require_once DRUPAL_ROOT . '/'. drupal_get_path('module', 'backup_migrate') .'/includes/profiles.inc';
require_once DRUPAL_ROOT . '/'. drupal_get_path('module', 'backup_migrate') .'/includes/files.inc';
$settings = array(
'profile_id' => 'default',
'filename' => variable_get("backup_migrate_file_name", _backup_migrate_default_filename()),
'append_timestamp' => variable_get("backup_migrate_append_timestamp", FALSE) ? 1 : 0,
'timestamp_format' => variable_get("backup_migrate_timestamp_format", 'Y-m-d\TH-i-s'),
'filters' => array(
'compression' => variable_get("backup_migrate_compression", "none"),
'exclude_tables' => variable_get("backup_migrate_exclude_tables", array()),
'nodata_tables' => variable_get("backup_migrate_nodata_tables", array()),
),
'name' => t('Default Settings'),
);
$profile = backup_migrate_crud_create_item('profile', $settings);
$profile->save();
variable_set("backup_migrate_profile_id", 'default');
// Set up the default schedules.
if (variable_get("backup_migrate_schedule_backup_period", 0)) {
require_once DRUPAL_ROOT . '/'. drupal_get_path('module', 'backup_migrate') .'/includes/schedules.inc';
$schedule = array(
'name' => t('Default Schedule'),
'profile_id' => $profile->get_id(),
'enabled' => 1,
'destination_id' => 'scheduled',
'period' => array('number' => variable_get("backup_migrate_schedule_backup_period", 0), 'type' => 'hours'),
'keep' => variable_get("backup_migrate_schedule_backup_keep", 0),
);
$schedule = backup_migrate_crud_create_item('schedule', $schedule);
$schedule->save();
}
}
}
/**
* Remove variables on uninstall.
*/
function backup_migrate_uninstall() {
db_query("DELETE FROM {variable} WHERE name LIKE 'backup_migrate_%'");
cache_clear_all('variables', 'cache');
}
/**
* Update from 1.x to 2.x.
*/
function backup_migrate_update_2000() {
_backup_migrate_setup_database_defaults();
return array();
}
/**
* Adding filter field for dev release of 2009-01-28
*/
function backup_migrate_update_2001() {
$ret = array();
$schema = drupal_get_schema_unprocessed('backup_migrate', 'backup_migrate_profiles');
// Add the filters field to the db.
if (!db_field_exists('backup_migrate_profiles', 'filters')) {
db_add_field('backup_migrate_profiles', 'filters', array('description' => t('The filter settings for the profile.'),'type' => 'text', 'not null' => TRUE));
}
// Add the source field
if (!db_field_exists('backup_migrate_profiles', 'source_id')) {
db_add_field('backup_migrate_profiles', 'source_id', array('description' => t('The {backup_migrate_destination}.destination_id of the source to backup from.'), 'type' => 'varchar', 'length' => 255, 'default' => 'db', 'not null' => TRUE));
}
// Remove the compression field.
if (db_field_exists('backup_migrate_profiles', 'compression')) {
db_drop_field('backup_migrate_profiles', 'compression');
}
return $ret;
}
/**
* Clearing the cache because there was a menu structure change in the dev of 2009-05-31
*/
function backup_migrate_update_2002() {
// Cache should clear automatically. Nothing to do here.
return array();
}
/**
* Allowing non-int profile ids in schedules 2009-05-31
*/
function backup_migrate_update_2003() {
$ret = array();
$spec = array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a profile.',
);
db_change_field('backup_migrate_schedules', 'profile_id', 'profile_id', $spec);
return $ret;
}
/**
* Allowing non-int profile ids 2009-07-01
*/
function backup_migrate_update_2004() {
$ret = array();
$spec = array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
);
$spec['description'] = 'The primary identifier for a destination.';
db_change_field('backup_migrate_destinations', 'destination_id', 'destination_id', $spec);
$spec['description'] = 'The primary identifier for a profile.';
db_change_field('backup_migrate_profiles', 'profile_id', 'profile_id', $spec);
$spec['description'] = 'The primary identifier for a schedule.';
db_change_field('backup_migrate_schedules', 'schedule_id', 'schedule_id', $spec);
// Drop the user/pass fields as they weren't being used.
if (db_field_exists('backup_migrate_destinations', 'username')) {
db_drop_field('backup_migrate_destinations', 'username');
}
if (db_field_exists('backup_migrate_destinations', 'password')) {
db_drop_field('backup_migrate_destinations', 'password');
}
return $ret;
}
/**
* Change the default database id to something friendlier 2009-08-08
*/
function backup_migrate_update_2005() {
require_once './'. drupal_get_path('module', 'backup_migrate') .'/includes/crud.inc';
require_once './'. drupal_get_path('module', 'backup_migrate') .'/includes/profiles.inc';
$ret = array();
// Change the destination ids of the defined database sources mostly to make using them with drush friendlier.
// Change the db_url:default id to simply 'db'
$ret[] = db_query("UPDATE {backup_migrate_profiles} SET source_id = 'db' WHERE source_id = 'db_url:default'");
$ret[] = db_query("UPDATE {backup_migrate_schedules} SET destination_id = 'db' WHERE destination_id = 'db_url:default'");
// Change the defined db keys from db_url:key to db:key.
$ret[] = db_query("UPDATE {backup_migrate_profiles} SET source_id = REPLACE(source_id, 'db_url:', 'db:')");
$ret[] = db_query("UPDATE {backup_migrate_schedules} SET destination_id = REPLACE(destination_id, 'db_url:', 'db:')");
// Add the source field to the schedule
if (!db_field_exists('backup_migrate_schedules', 'source_id')) {
db_add_field('backup_migrate_schedules', 'source_id', array('description' => t('The db source to backup from.'), 'type' => 'varchar', 'length' => 255, 'default' => 'db', 'not null' => TRUE));
}
// Copy source data from profiles to schedules.
$result = db_query('SELECT p.source_id, s.schedule_id FROM {backup_migrate_schedules} s LEFT JOIN {backup_migrate_profiles} p ON s.profile_id = p.profile_id', array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $schedule) {
if (!$schedule['source_id']) {
$schedule['source_id'] = 'db';
}
$ret[] = db_query("UPDATE {backup_migrate_schedules} SET source_id = '". $schedule['source_id'] ."' WHERE schedule_id = '". $schedule['profile_id'] ."'");
}
if (db_field_exists('backup_migrate_profiles', 'source_id')) {
db_drop_field('backup_migrate_profiles', 'source_id');
}
// Copy the no-data and exclude tables settings into the 'filter' field.
$result = db_query('SELECT * FROM {backup_migrate_profiles}', array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $item) {
if (isset($item['nodata_tables']) && isset($item['exclude_tables'])) {
$profile = backup_migrate_get_profile($item['profile_id']);
$profile->filters['nodata_tables'] = unserialize($item['nodata_tables']);
$profile->filters['exclude_tables'] = unserialize($item['exclude_tables']);
$profile->save();
}
}
if (db_field_exists('backup_migrate_profiles', 'nodata_tables')) {
db_drop_field('backup_migrate_profiles', 'nodata_tables');
}
if (db_field_exists('backup_migrate_profiles', 'exclude_tables')) {
db_drop_field('backup_migrate_profiles', 'exclude_tables');
}
return $ret;
}
/**
* Move the backup and migrate directory to the private directory.
*/
function backup_migrate_update_7200() {
$from = 'public://backup_migrate';
$to = 'private://backup_migrate';
if (drupal_realpath($from) && !drupal_realpath($to)) {
if (!rename($from, $to)) {
drupal_set_message(t('Unable to move the backups directory to your private folder, please check file permissions and move the directory %from to %to', array('%from' => drupal_realpath($from), '%to' => drupal_realpath($to))), 'warning');
}
}
}
/**
* Change the filename field to support 255 characters.
*/
function backup_migrate_update_7202() {
$ret = array();
db_change_field('backup_migrate_profiles', 'filename', 'filename', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE));
return $ret;
}
/**
* Update the schedule last run times to use variables instead of saving with the schedule.
*/
function backup_migrate_update_7203() {
$result = db_query('SELECT * FROM {backup_migrate_schedules}', array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $item) {
if (isset($item['last_run'])) {
variable_set('backup_migrate_schedule_last_run_' . $item['schedule_id'], $item['last_run']);
}
}
if (db_field_exists('backup_migrate_schedules', 'last_run')) {
db_drop_field('backup_migrate_schedules', 'last_run');
}
}
/**
* Disable the NodeSquirrel module if it's installed.
*/
function backup_migrate_update_7204() {
$ret = NULL;
if (module_exists('nodesquirrel')) {
module_disable(array('nodesquirrel'));
$ret = t("The NodeSquirrel module was disabled. NodeSquirrel support is now built into Backup and Migrate.");
}
return $ret;
}
/**
* Increase the length of all ids to 255.
*/
function backup_migrate_update_7205() {
$schema['backup_migrate_profiles'] = array(
'fields' => array(
'profile_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => t('The primary identifier for a profile.'),
),
'filename' => array(
'description' => t('The base pattern (including unreplaced tokens) for the name of the backup file.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
),
);
$schema['backup_migrate_destinations'] = array(
'fields' => array(
'destination_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => t('The primary identifier for a profile.'),
),
),
);
$schema['backup_migrate_schedules'] = array(
'fields' => array(
'schedule_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => t('The primary identifier for a profile.'),
),
'source_id' => array(
'description' => t('The {backup_migrate_destination}.destination_id of the source to backup from.'),
'type' => 'varchar',
'length' => 255,
'default' => 'db',
'not null' => TRUE
),
'destination_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => t('The {backup_migrate_destination}.destination_id of the destination to back up to.'),
),
'profile_id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => t('The primary identifier for a profile.'),
),
),
);
$spec = array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
);
$schema = backup_migrate_schema();
// Update the length of each of the ids
foreach ($schema as $table => $ids) {
foreach ($ids['fields'] as $field => $spec) {
db_change_field($table, $field, $field, $spec);
}
}
}

View File

@@ -0,0 +1,59 @@
(function ($) {
Drupal.backup_migrate = {
callbackURL : "",
autoAttach : function() {
if (Drupal.settings.backup_migrate !== undefined) {
if ($("#edit-save-settings").length && !$("#edit-save-settings").attr("checked")) {
// Disable input and hide its description.
// Set display none instead of using hide(), because hide() doesn't work when parent is hidden.
$('div.backup-migrate-save-options').css('display', 'none');
}
$("#edit-save-settings").bind("click", function() {
if (!$("#edit-save-settings").attr("checked")) {
$("div.backup-migrate-save-options").slideUp('slow');
}
else {
// Save unchecked; enable input.
$("div.backup-migrate-save-options").slideDown('slow');
}
});
$('#backup-migrate-ui-manual-backup-form select[multiple], #backup-migrate-crud-edit-form select[multiple]').each(function() {
$(this).after(
$('<div class="description backup-migrate-checkbox-link"></div>').append(
$('<a href="javascript:null(0);"></a>').text(Drupal.settings.backup_migrate.checkboxLinkText).click(function() {
Drupal.backup_migrate.selectToCheckboxes($(this).parents('.form-item').find('select'));
})
)
);
}
);
}
},
selectToCheckboxes : function($select) {
var field_id = $select.attr('id');
var $checkboxes = $('<div></div>').addClass('backup-migrate-tables-checkboxes');
$('option', $select).each(function(i) {
var self = this;
$box = $('<input type="checkbox" class="backup-migrate-tables-checkbox">').bind('change click', function() {
$select.find('option[value="'+self.value+'"]').attr('selected', this.checked);
if (this.checked) {
$(this).parent().addClass('checked');
}
else {
$(this).parent().removeClass('checked');
}
}).attr('checked', this.selected ? 'checked' : '');
$checkboxes.append($('<div class="form-item"></div>').append($('<label class="option backup-migrate-table-select">'+this.value+'</label>').prepend($box)));
});
$select.parent().find('.backup-migrate-checkbox-link').remove();
$select.before($checkboxes);
$select.hide();
}
}
$(document).ready(Drupal.backup_migrate.autoAttach);
})(jQuery);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,243 @@
<?php
/**
* @file
* Drush commands for backup and migrate.
*/
/**
* Implementation of hook_drush_command().
*/
function backup_migrate_drush_command() {
$items['bam-backup'] = array(
'callback' => 'backup_migrate_drush_backup',
'description' => dt('Backup the site\'s database with Backup and Migrate.'),
'aliases' => array('bb'),
'examples' => array(
'drush bam-backup' => 'Backup the default database to the manual backup directory using the default settings.',
'drush bam-backup db scheduled mysettings' => 'Backup the database to the scheduled directory using a settings profile called "mysettings"',
'drush bam-backup files' => 'Backup the files directory to the manual directory using the default settings. The Backup and Migrate Files module is required for files backups.',
),
'arguments' => array(
'source' => "Optional. The id of the source (usually a database) to backup. Use 'drush bam-sources' to get a list of sources. Defaults to 'db'",
'destination' => "Optional. The id of destination to send the backup file to. Use 'drush bam-destinations' to get a list of destinations. Defaults to 'manual'",
'profile' => "Optional. The id of a settings profile to use. Use 'drush bam-profiles' to get a list of available profiles. Defaults to 'default'",
),
);
$items['bam-restore'] = array(
'callback' => 'backup_migrate_drush_restore',
'description' => dt('Restore the site\'s database with Backup and Migrate.'),
'arguments' => array(
'source' => "Required. The id of the source (usually a database) to restore the backup to. Use 'drush bam-sources' to get a list of sources. Defaults to 'db'",
'destination' => "Required. The id of destination to send the backup file to. Use 'drush bam-destinations' to get a list of destinations. Defaults to 'manual'",
'backup id' => "Required. The id of a backup file restore. Use 'drush bam-backups' to get a list of available backup files.",
),
'options' => array(
'yes' => 'Skip confirmation',
),
);
$items['bam-destinations'] = array(
'callback' => 'backup_migrate_drush_destinations',
'description' => dt('Get a list of available destinations.'),
);
$items['bam-sources'] = array(
'callback' => 'backup_migrate_drush_sources',
'description' => dt('Get a list of available sources.'),
);
$items['bam-profiles'] = array(
'callback' => 'backup_migrate_drush_profiles',
'description' => dt('Get a list of available settings profiles.'),
);
$items['bam-backups'] = array(
'callback' => 'backup_migrate_drush_destination_files',
'description' => dt('Get a list of previously created backup files.'),
'arguments' => array(
'destination' => "Required. The id of destination to list backups from. Use 'drush bam-destinations' to get a list of destinations.",
),
);
return $items;
}
/**
* Implementation of hook_drush_help().
*/
function backup_migrate_drush_help($section) {
switch ($section) {
case 'drush:bam-backup':
return dt("Backup the site's database using default settings.");
case 'drush:bam-restore':
return dt('Restore the site\'s database with Backup and Migrate.');
case 'drush:bam-destinations':
return dt('Get a list of available destinations.');
case 'drush:bam-profiles':
return dt('Get a list of available settings profiles.');
case 'drush:bam-backups':
return dt('Get a list of previously created backup files.');
}
}
/**
* Backup the default database.
*/
function backup_migrate_drush_backup($source_id = 'db', $destination_id = 'manual', $profile_id = 'default') {
backup_migrate_include('profiles', 'destinations');
// Set the message mode to logging.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_destination($source_id)) {
_backup_migrate_message("Could not find the source '@source'. Try using 'drush bam-sources' to get a list of available sources or use 'db' to backup the Drupal database.", array('@source' => $source_id), 'error');
return;
}
if (!backup_migrate_get_destination($destination_id)) {
_backup_migrate_message("Could not find the destination '@destination'. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
$settings = backup_migrate_get_profile($profile_id);
if(!$settings) {
_backup_migrate_message("Could not find the profile '@profile'. Try using 'drush bam-profiles' to get a list of available profiles.", array('@profile' => $profile_id), 'error');
return;
}
_backup_migrate_message('Starting backup...');
$settings->destination_id = $destination_id;
$settings->source_id = $source_id;
backup_migrate_perform_backup($settings);
}
/**
* Restore to the default database.
*/
function backup_migrate_drush_restore($source_id = '', $destination_id = '', $file_id = '') {
drush_print(dt('Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!'));
if (!drush_confirm(dt('Are you sure you want to restore the database?'))) {
return drush_user_abort();
}
backup_migrate_include('profiles', 'destinations');
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_destination($source_id)) {
_backup_migrate_message("Could not find the source '@source'. Try using 'drush bam-sources' to get a list of available sources or use 'db' to backup the Drupal database.", array('@source' => $source_id), 'error');
return;
}
if (!$destination = backup_migrate_get_destination($destination_id)) {
_backup_migrate_message("Could not find the destination '@destination'. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
if (!$file_id || !$file = backup_migrate_destination_get_file($destination_id, $file_id)) {
_backup_migrate_message("Could not find the file '@file'. Try using 'drush bam-backups @destination' to get a list of available backup files in this destination destinations.", array('@destination' => $destination_id, '@file' => $file_id), 'error');
return;
}
_backup_migrate_message('Starting restore...');
$settings = array('source_id' => $source_id);
backup_migrate_perform_restore($destination_id, $file_id, $settings);
}
/**
* Get a list of available destinations.
*/
function backup_migrate_drush_destinations() {
return _backup_migrate_drush_destinations('all');
}
/**
* Get a list of available sources.
*/
function backup_migrate_drush_sources() {
return _backup_migrate_drush_destinations('source');
}
/**
* Get a list of available destinations with the given op.
*/
function _backup_migrate_drush_destinations($op = NULL) {
backup_migrate_include('destinations');
$rows = array(array(dt('ID'), dt('Name'), dt('Operations')));
foreach (backup_migrate_get_destinations($op) as $destination) {
$rows[] = array(
$destination->get_id(),
$destination->get_name(),
implode (', ', $destination->ops()),
);
}
drush_print_table($rows, TRUE, array(32, 32));
}
/**
* Get a list of available profiles.
*/
function backup_migrate_drush_profiles() {
backup_migrate_include('profiles');
$rows = array(array(dt('ID'), dt('Name')));
foreach (backup_migrate_get_profiles() as $profile) {
$rows[] = array(
$profile->get_id(),
$profile->get_name(),
);
}
drush_print_table($rows, TRUE, array(32, 32));
}
/**
* Get a list of files in a given destination
*/
function backup_migrate_drush_destination_files($destination_id = NULL) {
backup_migrate_include('destinations');
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!$destination_id) {
_backup_migrate_message("You must specify an existing destination. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
if (!$destination = backup_migrate_get_destination($destination_id)) {
_backup_migrate_message("Could not find the destination '@destination'. Try using 'drush bam-destinations' to get a list of available destinations.", array('@destination' => $destination_id), 'error');
return;
}
$out = array(array(
dt('Filename'),
dt('Date'),
dt('Age'),
dt('Size'),
));
$files = $destination->list_files();
$i = 0;
foreach ((array)$files as $file) {
// Show only files that can be restored from.
if ($file->is_recognized_type()) {
$info = $file->info();
$out[] = array(
check_plain($info['filename']),
format_date($info['filetime'], 'small'),
format_interval(time() - $info['filetime'], 1),
format_size($info['filesize']),
);
}
}
if (count($out) > 1) {
drush_print_table($out, TRUE);
}
else {
drush_print(dt('There are no backup files to display.'));
}
}
/**
* Send a message to the drush log.
*/
function _backup_migrate_message_drush($message, $replace, $type) {
// Use drush_log to display to the user.
drush_log(strip_tags(dt($message, $replace)), str_replace('status', 'notice', $type));
// Watchdog log the message as well for admins.
_backup_migrate_message_log($message, $replace, $type);
}

View File

@@ -0,0 +1,660 @@
<?php
/**
* @file
* CRUD functions for backup and migrate types (schedules, profiles etc.).
*/
define('BACKUP_MIGRATE_STORAGE_NONE', 0);
define('BACKUP_MIGRATE_STORAGE_DB', 1);
define('BACKUP_MIGRATE_STORAGE_OVERRIDEN', 2);
/**
* Return a list of CRUD types in the module.
*/
function backup_migrate_crud_types() {
$out = array(
'destination' => array(
'class' => 'backup_migrate_destination',
'include' => 'destinations',
),
'profile' => array(
'class' => 'backup_migrate_profile',
'include' => 'profiles',
),
'schedule' => array(
'class' => 'backup_migrate_schedule',
'include' => 'schedules',
),
);
return $out;
}
/**
* Get a generic object of the given type to be used for static-like functions.
*
* I'm not using actual static method calls since they don't work on variables prior to PHP 5.3.0
*/
function backup_migrate_crud_type_load($type) {
$out = NULL;
$types = backup_migrate_crud_types();
if (!empty($types[$type])) {
$info = $types[$type];
if ($info['include']) {
backup_migrate_include($info['include']);
}
$out = new $info['class'];
}
return $out;
}
/**
* Get the menu items handled by the CRUD code.
*/
function backup_migrate_crud_menu() {
$items = array();
foreach (backup_migrate_crud_types() as $type => $info) {
$type = backup_migrate_crud_type_load($type);
$items += (array)$type->get_menu_items();
}
return $items;
}
/**
* Page callback to create a new item.
*/
function backup_migrate_crud_ui_create() {
if ($type = backup_migrate_crud_type_load(arg(BACKUP_MIGRATE_MENU_DEPTH))) {
$item = $type->create(array());
return drupal_get_form('backup_migrate_crud_edit_form', $item);
}
}
/**
* Page callback to list all items.
*/
function backup_migrate_crud_ui_list() {
$out = '';
if ($type = backup_migrate_crud_type_load(arg(BACKUP_MIGRATE_MENU_DEPTH))) {
$out = $type->get_list();
}
return $out;
}
/**
* Page callback to edit an item.
*/
function backup_migrate_crud_ui_edit($item_id = NULL) {
if ($type = backup_migrate_crud_type_load(arg(BACKUP_MIGRATE_MENU_DEPTH))) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_edit_form', $item);
}
drupal_goto(BACKUP_MIGRATE_MENU_PATH. '/' . arg(BACKUP_MIGRATE_MENU_DEPTH));
}
}
/**
* A form callback to edit an item.
*/
function backup_migrate_crud_edit_form($form, $form_state, $item) {
$form = $item->edit_form();
$form['item'] = array(
'#type' => 'value',
'#value' => $item,
);
$form['#validate'][] = 'backup_migrate_crud_edit_form_validate';
$form['#submit'][] = 'backup_migrate_crud_edit_form_submit';
return $form;
}
/**
* Validate the item edit form.
*/
function backup_migrate_crud_edit_form_validate($form, &$form_state) {
$item = $form_state['values']['item'];
$item->edit_form_validate($form, $form_state);
}
/**
* Submit the item edit form.
*/
function backup_migrate_crud_edit_form_submit($form, &$form_state) {
$item = $form_state['values']['item'];
$item->edit_form_submit($form, $form_state);
if (empty($form_state['redirect'])) {
$form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . '/'. $item->type_name;
}
}
/**
* Page callback to delete an item.
*/
function backup_migrate_crud_ui_delete($item_id = NULL) {
if ($type = backup_migrate_crud_type_load(arg(BACKUP_MIGRATE_MENU_DEPTH))) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_delete_confirm_form', $item);
}
drupal_goto('admin/content/backup_migrate/'. arg(BACKUP_MIGRATE_MENU_DEPTH));
}
}
/**
* Ask confirmation for deletion of a item.
*/
function backup_migrate_crud_delete_confirm_form($form, &$form_state, $item) {
$form['item'] = array(
'#type' => 'value',
'#value' => $item,
);
$message = $item->delete_confirm_message();
return confirm_form($form, t('Are you sure?'), BACKUP_MIGRATE_MENU_PATH . '/'. $item->type_name, $message, t('Delete'), t('Cancel'));
}
/**
* Delete a item after confirmation.
*/
function backup_migrate_crud_delete_confirm_form_submit($form, &$form_state) {
if ($form_state['values']['confirm']) {
$item = $form_state['values']['item'];
$item->delete();
}
$form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH . "/". $item->type_name;
}
/**
* Export an item.
*/
function backup_migrate_crud_ui_export($item_id = NULL) {
if ($type = backup_migrate_crud_type_load(arg(BACKUP_MIGRATE_MENU_DEPTH))) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_export_form', $item->export());
}
drupal_goto(BACKUP_MIGRATE_MENU_PATH . '/' . arg(BACKUP_MIGRATE_MENU_DEPTH));
}
}
/**
* Ask confirmation for deletion of a destination.
*/
function backup_migrate_crud_export_form($form, &$form_state, $export) {
$form['export'] = array(
'#title' => t('Exported content'),
'#type' => 'textarea',
'#rows' => min(30, count(explode("\n", $export))),
'#value' => $export,
);
return $form;
}
/**
* Get all items of the given type.
*/
function backup_migrate_crud_get_items($type) {
if ($type = backup_migrate_crud_type_load($type)) {
return $type->all_items();
}
}
/**
* Get an item of the specified type.
*/
function backup_migrate_crud_get_item($type, $id) {
if ($type = backup_migrate_crud_type_load($type)) {
return $type->item($id);
}
}
/**
* Create a new item of the given type.
*/
function backup_migrate_crud_create_item($type, $params) {
if ($type = backup_migrate_crud_type_load($type)) {
return $type->create($params);
}
}
/**
* A base class for items which can be stored in the database, listed, edited, deleted etc.
*/
class backup_migrate_item {
var $db_table = '';
var $type_name = '';
var $storage = FALSE;
var $default_values = array();
var $singular = 'item';
var $plural = 'items';
/**
* Constructor, set the basic info pulled from the db or generated programatically.
*/
function __construct($params = array()) {
$this->from_array((array)$params + (array)$this->get_default_values());
}
/**
* Get the default values for standard parameters.
*/
function get_default_values() {
return $this->default_values;
}
/**
* Save the item to the database.
*/
function save() {
if (!$this->get_id()) {
$this->generate_id();
}
$data = $this->to_array();
drupal_write_record($this->db_table, $data, !empty($this->storage) ? $this->get_primary_key() : array());
}
/**
* Delete the item from the database.
*/
function delete() {
$keys = (array)$this->get_primary_key();
db_query('DELETE FROM {' . $this->db_table . '} WHERE ' . $keys[0] . ' = :id', array(':id' => $this->get_id()));
}
/**
* Load an existing item from an array.
*/
function from_array($params) {
foreach ($params as $key => $value) {
if (method_exists($this, 'set_'. $key)) {
$this->{'set_'. $key}($value);
}
else {
$this->{$key} = $value;
}
}
}
/**
* Return as an array of values.
*/
function to_array() {
$out = array();
// Return fields as specified in the schema.
$schema = $this->get_schema();
if (!empty($schema['fields']) && is_array($schema['fields'])) {
foreach ($schema['fields'] as $field => $info) {
$out[$field] = $this->get($field);
}
}
return $out;
}
/**
* Return as an exported array of values.
*/
function export() {
$out = $this->to_array();
ob_start();
var_export($out);
$out = ob_get_contents();
ob_end_clean();
return $out;
}
/**
* Load an existing item from an database (serialized) array.
*/
function load_row($data) {
$params = array();
$schema = $this->get_schema();
// Load fields as specified in the schema.
foreach ($schema['fields'] as $field => $info) {
$params[$field] = empty($info['serialize']) ? $data[$field] : unserialize($data[$field]);
}
$this->from_array($params);
}
/**
* Decode a loaded db row (unserialize necessary fields).
*/
function decode_db_row($data) {
$params = array();
$schema = $this->get_schema();
// Load fields as specified in the schema.
foreach ($schema['fields'] as $field => $info) {
$params[$field] = empty($info['serialize']) ? $data[$field] : unserialize($data[$field]);
}
return $params;
}
/**
* Return the fields which must be serialized before saving to the db.
*/
function get_serialized_fields() {
$out = array();
$schema = $this->get_schema();
foreach ($schema['fields'] as $field => $info) {
if (!empty($info['serialize'])) {
$out[] = $field;
}
}
return $out;
}
/**
* Get the primary key field title from the schema.
*/
function get_primary_key() {
$schema = $this->get_schema();
return @$schema['primary key'];
}
/**
* Get the schema for the item type.
*/
function get_schema() {
return drupal_get_schema($this->db_table);
}
/**
* Get the primary id for this item (if any is set).
*
* We only handle single field keys since that's all we need.
*/
function get_id() {
$keys = (array)$this->get_primary_key();
return !empty($this->{$keys[0]}) ? (string)$this->{$keys[0]} : '';
}
/**
* Set the primary id for this item (if any is set).
*/
function set_id($id) {
$keys = (array)$this->get_primary_key();
if (!empty($keys[0])) {
return $this->{$keys[0]} = $id;
}
return NULL;
}
/**
* Return a random (very very likely unique) string id for a new item.
*/
function generate_id() {
$this->set_id(md5(uniqid(mt_rand(), true)));
}
/**
* Get the name of the item.
*/
function get_name() {
return @$this->name;
}
/**
* Get the member with the given key.
*/
function get($key) {
if (method_exists($this, 'get_'. $key)) {
return $this->{'get_'. $key}();
}
return @$this->{$key};
}
/* UI Stuff */
/**
* Get the action links for a destination.
*/
function get_action_links() {
$out = array('edit' => '', 'delete' => '');
$item_id = $this->get_id();
if (@$this->storage == BACKUP_MIGRATE_STORAGE_DB || @$this->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$out['edit'] = l(t("edit"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/edit/$item_id");
}
else if (@$this->storage == BACKUP_MIGRATE_STORAGE_NONE) {
$out['edit'] = l(t("override"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/edit/$item_id");
}
if (@$this->storage == BACKUP_MIGRATE_STORAGE_DB) {
$out['delete'] = l(t("delete"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/delete/$item_id");
}
else if (@$this->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$out['delete'] = l(t("revert"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/delete/$item_id");
}
// Export link disabled until we have an import function.
//$out['export'] = l(t("export"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/export/$item_id");
return $out;
}
/**
* Get a table of all items of this type.
*/
function get_list() {
$items = $this->all_items();
$rows = array();
foreach ($items as $item) {
if ($row = $item->get_list_row()) {
$rows[] = $row;
}
}
if (count($rows)) {
$out = theme('table', array('header' => $this->get_list_header(), 'rows' => $rows));
}
else {
$out = t('There are no !items to display.', array('!items' => $this->plural));
}
return $out;
}
/**
* Get the columns needed to list the type.
*/
function get_list_column_info() {
return array(
'actions' => array('title' => t('Operations'), 'html' => TRUE),
);
}
/**
* Get header for a lost of this type.
*/
function get_list_header() {
$out = array();
foreach ($this->get_list_column_info() as $key => $col) {
$out[] = $col['title'];
}
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
$out = array();
foreach ($this->get_list_column_info() as $key => $col) {
$out[$key] = empty($col['html']) ? check_plain($this->get($key)) : $this->get($key);
}
return $out;
}
/**
* Get the rendered action links for a destination.
*/
function get_actions() {
$links = $this->get_action_links();
return implode(" &nbsp; ", $links);
}
/**
* Get the edit form for the item.
*/
function edit_form() {
$form = array();
$form['item'] = array(
'#type' => 'value',
'#value' => $this,
);
$form['id'] = array(
'#type' => 'value',
'#value' => $this->get_id(),
);
$form['actions'] = array('#prefix' => '<div class="container-inline">', '#suffix' => '</div>', '#weight' => 99);
$form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save !type', array('!type' => t($this->singular))));
$form['actions']['cancel'] = array('#markup' => l(t('Cancel'), BACKUP_MIGRATE_MENU_PATH . '/destination'));
return $form;
}
/**
* Validate the edit form for the item.
*/
function edit_form_validate($form, &$form_state) {
}
/**
* Submit the edit form for the item.
*/
function edit_form_submit($form, &$form_state) {
$this->from_array($form_state['values']);
$this->save();
_backup_migrate_message('!type saved', array('!type' => t(ucwords($this->singular))));
}
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function delete_confirm_message() {
return t('Are you sure you want to delete this !type?', array('!type' => t($item->singular)));
}
/* Static Functions */
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
function strings() {
// Help the pot extractor find these strings.
t('List !type');
t('Create !type');
t('Delete !type');
t('Edit !type');
t('Export !type');
}
/**
* Get the menu items for manipulating this type.
*/
function get_menu_items() {
$type = $this->type_name;
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type] = array(
'title' => ucwords($this->plural),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_list', TRUE),
'access arguments' => array('administer backup and migrate'),
'weight' => 2,
'type' => MENU_LOCAL_TASK,
);
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type .'/list'] = array(
'title' => 'List !type',
'title arguments' => array('!type' => t(ucwords($this->plural))),
'weight' => 1,
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type .'/list/add'] = array(
'title' => 'Add !type',
'title arguments' => array('!type' => t(ucwords($this->singular))),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_create', TRUE),
'access arguments' => array('administer backup and migrate'),
'weight' => 2,
'type' => MENU_LOCAL_ACTION,
);
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type .'/list/delete'] = array(
'title' => 'Delete !type',
'title arguments' => array('!type' => t(ucwords($this->singular))),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_delete', TRUE),
'access arguments' => array('administer backup and migrate'),
'type' => MENU_CALLBACK,
);
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type .'/list/edit'] = array(
'title' => 'Edit !type',
'title arguments' => array('!type' => t(ucwords($this->singular))),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_edit', TRUE),
'access arguments' => array('administer backup and migrate'),
'type' => MENU_CALLBACK,
);
$items[BACKUP_MIGRATE_MENU_PATH . '/' . $type .'/list/export'] = array(
'title' => 'Export !type',
'title arguments' => array('!type' => t(ucwords($this->singular))),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_export', TRUE),
'access arguments' => array('administer backup and migrate'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Create a new items with the given input. Doesn't load the parameters, but could use them to determine what type to create.
*/
function create($params = array()) {
$type = get_class($this);
return new $type($params);
}
/**
* Get all of the given items.
*/
function all_items() {
static $cache = array();
// Allow other modules to declare destinations programatically.
$items = array();
foreach (module_implements($this->db_table) as $module) {
$fn = $module . '_' . $this->db_table;
$items += $fn();
}
// Get any items stored as a variable. This allows destinations to be defined in settings.php
$defaults = (array)variable_get($this->db_table .'_defaults', array());
foreach ($defaults as $info) {
if (is_array($info) && $item = $this->create($info)) {
$items[$item->get_id()] = $item;
}
}
// Get the items from the db.
$result = db_query("SELECT * FROM {{$this->db_table}}", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $info) {
$info = $this->decode_db_row($info);
if ($item = $this->create($info)) {
$item->storage = empty($items[$item->get_id()]) ? BACKUP_MIGRATE_STORAGE_DB : BACKUP_MIGRATE_STORAGE_OVERRIDEN;
$items[$item->get_id()] = $item;
}
}
// Allow other modules to alter the items. This should maybe be before the db override code above
// but then the filters are not able to set defaults for missing values. Other modules should just
// be careful not to overwrite the user's UI changes in an unexpected way.
drupal_alter($this->db_table, $items);
return $items;
}
/**
* A particular item.
*/
function item($item_id) {
$items = $this->all_items();
return !empty($items[$item_id]) ? $items[$item_id] : NULL;
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* @file
* Functions to handle the browser upload/download backup destination.
*/
/**
* A destination type for browser upload/download.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser extends backup_migrate_destination {
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
// Return none as this type should not be displayed.
return array();
}
}
/**
* A destination type for browser upload.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser_upload extends backup_migrate_destination_browser {
var $supported_ops = array('restore');
function __construct() {
$params = array();
$params['name'] = "Upload";
$params['destination_id'] = 'upload';
parent::__construct($params);
}
/**
* File load destination callback.
*/
function load_file($file_id) {
backup_migrate_include('files');
if ($file = file_save_upload('backup_migrate_restore_upload')) {
$out = new backup_file(array('filepath' => $file->uri));
backup_migrate_temp_files_add($file->uri);
return $out;
}
return NULL;
}
}
/**
* A destination type for browser download.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_browser_download extends backup_migrate_destination_browser {
var $supported_ops = array('manual backup');
function __construct() {
$params = array();
$params['name'] = "Download";
$params['destination_id'] = 'download';
parent::__construct($params);
}
/**
* File save destination callback.
*/
function save_file($file, $settings) {
backup_migrate_include('files');
$file->transfer();
}
}

View File

@@ -0,0 +1,311 @@
<?php
/**
* @file
* Functions to handle the direct to database destination.
*/
/**
* A destination type for saving to a database server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_db extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'configure', 'source');
var $db_target = 'default';
var $connection = null;
function type_name() {
return t("Database");
}
/**
* Save the info by importing it into the database.
*/
function save_file($file, $settings) {
backup_migrate_include('files');
// Set the source_id to the destination_id in the settings since for a restore, the source_id is the
// database that gets restored to.
$settings->set_source($this->get_id());
// Restore the file to the source database.
$file = backup_migrate_perform_restore($this->get_id(), $file, $settings);
return $file;
}
/**
* Destination configuration callback.
*/
function edit_form() {
$form = parent::edit_form();
$form['scheme']['#title'] = t('Database type');
// $form['scheme']['#options'] = array($GLOBALS['db_type'] => $GLOBALS['db_type']);
$form['scheme']['#description'] = t('The type of the database. Drupal only supports one database type at a time, so this must be the same as the current database type.');
$form['path']['#title'] = t('Database name');
$form['path']['#description'] = t('The name of the database. The database must exist, it will not be created for you.');
$form['user']['#description'] = t('Enter the name of a user who has write access to the database.');
return $form;
}
/**
* Validate the configuration form. Make sure the db info is valid.
*/
function edit_form_validate($form, &$form_state) {
if (!preg_match('/[a-zA-Z0-9_\$]+/', $form_state['values']['path'])) {
form_set_error('path', t('The database name is not valid.'));
}
parent::edit_form_validate($form, $form_state);
}
/**
* Get the form for the settings for this destination.
*
* Return the default tables whose data can be ignored. These tables mostly contain
* info which can be easily reproducted (such as cache or search index)
* but also tables which can become quite bloated but are not necessarily extremely
* important to back up or migrate during development (such ass access log and watchdog)
*/
function backup_settings_default() {
$core = array(
'cache',
'cache_admin_menu',
'cache_browscap',
'cache_content',
'cache_filter',
'cache_calendar_ical',
'cache_location',
'cache_menu',
'cache_page',
'cache_reptag',
'cache_views',
'cache_views_data',
'cache_block',
'cache_update',
'cache_form',
'cache_bootstrap',
'cache_field',
'cache_image',
'cache_path',
'sessions',
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
'watchdog',
'accesslog',
'devel_queries',
'devel_times',
);
$nodata_tables = array_merge($core, module_invoke_all('devel_caches'));
return array(
'nodata_tables' => $nodata_tables,
'exclude_tables' => array(),
'utils_lock_tables' => FALSE,
);
}
/**
* Get the form for the backup settings for this destination.
*/
function backup_settings_form($settings) {
$objects = $this->get_object_names();
$form['#description'] = t("You may omit specific tables, or specific table data from the backup file. Only omit data that you know you will not need such as cache data, or tables from other applications. Excluding tables can break your Drupal install, so <strong>do not change these settings unless you know what you're doing</strong>.");
$form['exclude_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the following tables altogether"),
"#options" => $objects,
"#default_value" => $settings['exclude_tables'],
"#description" => t("The selected tables will not be added to the backup file."),
);
$tables = $this->get_table_names();
$form['nodata_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the data from the following tables"),
"#options" => $tables,
"#default_value" => $settings['nodata_tables'],
"#description" => t("The selected tables will have their structure backed up but not their contents. This is useful for excluding cache data to reduce file size."),
);
$form['utils_lock_tables'] = array(
'#type' => 'checkbox',
'#title' => t('Lock tables during backup'),
'#default_value' => !empty($settings['utils_lock_tables']) ? $settings['utils_lock_tables'] : NULL,
'#description' => t('This can help reduce data corruption, but will make your site unresponsive.'),
);
return $form;
}
/**
* Backup from this source.
*/
function backup_to_file($file, $settings) {
$file->push_type($this->get_file_type_id());
backup_migrate_filters_invoke_all('pre_backup', $this, $file, $settings);
//$this->lock_tables($settings);
// Switch to a different db if specified.
$success = $this->_backup_db_to_file($file, $settings);
//$this->unlock_tables($settings);
backup_migrate_filters_invoke_all('post_backup', $this, $file, $settings, $success);
return $success ? $file : FALSE;
}
/**
* Restore to this source.
*/
function restore_from_file($file, &$settings) {
$num = 0;
$type = $this->get_file_type_id();
// Open the file using the file wrapper. Check that the dump is of the right type (allow .sql for legacy reasons).
if ($file->type_id() !== $this->get_file_type_id() && $file->type_id() !== 'sql') {
_backup_migrate_message("Unable to restore from file %file because a %type file can't be restored to this database.", array("%file" => $file->filepath(), '%type' => $file->type_id()), 'error');
}
else {
backup_migrate_filters_invoke_all('pre_restore', $file, $settings);
// Restore the database.
$num = $this->_restore_db_from_file($file, $settings);
$settings->performed_action = $num ? t('%num SQL commands executed.', array('%num' => $num)) : '';
backup_migrate_filters_invoke_all('post_restore', $file, $settings, $num);
}
return $num;
}
/**
* Get the db connection for the specified db.
*/
function _get_db_connection() {
if (!$this->connection) {
$target = $key = '';
$parts = explode(':', $this->get_id());
// One of the predefined databases (set in settings.php)
if ($parts[0] == 'db') {
$key = empty($parts[1]) ? 'default' : $parts[1];
$target = empty($parts[2]) ? 'default' : $parts[2];
}
// Another db url.
else {
// If the url is specified build it into a connection info array.
if (!empty($this->dest_url)) {
$info = array(
'driver' => empty($this->dest_url['scheme']) ? NULL : $this->dest_url['scheme'],
'host' => empty($this->dest_url['host']) ? NULL : $this->dest_url['host'],
'port' => empty($this->dest_url['port']) ? NULL : $this->dest_url['port'],
'username' => empty($this->dest_url['user']) ? NULL : $this->dest_url['user'],
'password' => empty($this->dest_url['pass']) ? NULL : $this->dest_url['pass'],
'database' => empty($this->dest_url['path']) ? NULL : $this->dest_url['path'],
);
$key = uniqid('backup_migrate_tmp_');
$target = 'default';
Database::addConnectionInfo($key, $target, $info);
}
// No database selected. Assume the default.
else {
$key = $target = 'default';
}
}
if ($target && $key) {
$this->connection = Database::getConnection($target, $key);
}
}
return $this->connection;
}
/**
* Backup the databases to a file.
*/
function _backup_db_to_file($file, $settings) {
// Must be overridden.
}
/**
* Backup the databases to a file.
*/
function _restore_db_from_file($file, $settings) {
// Must be overridden.
}
/**
* Get a list of objects in the database.
*/
function get_object_names() {
// Must be overridden.
$out = $this->_get_table_names();
if (method_exists($this, '_get_view_names')) {
$out += $this->_get_view_names();
}
return $out;
}
/**
* Get a list of tables in the database.
*/
function get_table_names() {
// Must be overridden.
$out = $this->_get_table_names();
return $out;
}
/**
* Get a list of tables in the database.
*/
function _get_table_names() {
// Must be overridden.
return array();
}
/**
* Lock the database in anticipation of a backup.
*/
function lock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$tables = array();
foreach ($this->get_table_names() as $table) {
// There's no need to lock excluded or structure only tables because it doesn't matter if they change.
if (empty($settings->filters['exclude_tables']) || !in_array($table, (array)$settings->filters['exclude_tables'])) {
$tables[] = $table;
}
}
$this->_lock_tables($tables);
}
}
/**
* Lock the list of given tables in the database.
*/
function _lock_tables($tables) {
// Must be overridden.
}
/**
* Unlock any tables that have been locked.
*/
function unlock_tables($settings) {
if ($settings->filters['utils_lock_tables']) {
$this->_unlock_tables();
}
}
/**
* Unlock the list of given tables in the database.
*/
function _unlock_tables($tables) {
// Must be overridden.
}
/**
* Get the file type for to backup this destination to.
*/
function get_file_type_id() {
return 'sql';
}
}

View File

@@ -0,0 +1,474 @@
<?php
backup_migrate_include('destinations.db');
/**
* @file
* Functions to handle the direct to database destination.
*/
/**
* A destination type for saving to a database server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_db_mysql extends backup_migrate_destination_db {
function type_name() {
return t("MySQL Database");
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
return array(
"sql" => array(
"extension" => "sql",
"filemime" => "text/x-sql",
"backup" => TRUE,
"restore" => TRUE,
),
"mysql" => array(
"extension" => "mysql",
"filemime" => "text/x-sql",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Declare any mysql databases defined in the settings.php file as a possible destination.
*/
function destinations() {
$out = array();
global $databases;
foreach ((array)$databases as $db_key => $target) {
foreach ((array)$target as $tgt_key => $info) {
// Only mysql/mysqli supported by this destination.
$key = $db_key . ':' . $tgt_key;
if ($info['driver'] === 'mysql') {
$url = $info['driver'] . '://' . $info['username'] . ':' . $info['password'] . '@' . $info['host'] . (isset($info['port']) ? ':' . $info['port'] : '') . '/' . $info['database'];
if ($destination = backup_migrate_create_destination('mysql', array('url' => $url))) {
// Treat the default database differently because it is probably the only one available.
if ($key == 'default:default') {
$destination->set_id('db');
$destination->set_name(t('Default Database'));
// Dissalow backing up to the default database because that's confusing and potentially dangerous.
$destination->remove_op('scheduled backup');
$destination->remove_op('manual backup');
}
else {
$destination->set_id('db:'. $key);
$destination->set_name($key .": ". $destination->get_display_location());
}
$out[$destination->get_id()] = $destination;
}
}
}
}
return $out;
}
/**
* Get the file type for to backup this destination to.
*/
function get_file_type_id() {
return 'mysql';
}
/**
* Get the form for the backup settings for this destination.
*/
function backup_settings_form($settings) {
$form = parent::backup_settings_form($settings);
$form['use_mysqldump'] = array(
"#type" => "checkbox",
"#title" => t("Use mysqldump command"),
"#default_value" => !empty($settings['use_mysqldump']),
"#description" => t("Use the mysqldump command line tool if available. This can be faster for large databases but will not work on all servers. Also exporting SQL views is not really solid with this option. EXPERIMENTAL"),
);
return $form;
}
/**
* Backup the databases to a file.
*
* Returns a list of sql commands, one command per line.
* That makes it easier to import without loading the whole file into memory.
* The files are a little harder to read, but human-readability is not a priority
*/
function _backup_db_to_file($file, $settings) {
if (!empty($settings->filters['use_mysqldump']) && $this->_backup_db_to_file_mysqldump($file, $settings)) {
return TRUE;
}
$lines = 0;
$exclude = !empty($settings->filters['exclude_tables']) ? $settings->filters['exclude_tables'] : array();
$nodata = !empty($settings->filters['nodata_tables']) ? $settings->filters['nodata_tables'] : array();
if ($file->open(TRUE)) {
$file->write($this->_get_sql_file_header());
$alltables = $this->_get_tables();
$allviews = $this->_get_views();
foreach ($alltables as $table) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($table['name'] && !isset($exclude[$table['name']])) {
$file->write($this->_get_table_structure_sql($table));
$lines++;
if (!in_array($table['name'], $nodata)) {
$lines += $this->_dump_table_data_sql_to_file($file, $table);
}
}
}
foreach ($allviews as $view) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($view['name'] && !isset($exclude[$view['name']])) {
$file->write($this->_get_view_create_sql($view));
}
}
$file->write($this->_get_sql_file_footer());
$file->close();
return $lines;
}
else {
return FALSE;
}
}
/**
* Backup the databases to a file using the mysqldump command.
*/
function _backup_db_to_file_mysqldump($file, $settings) {
$success = FALSE;
$nodata_tables = array();
$alltables = $this->_get_tables();
$command = 'mysqldump --result-file=%file --opt -Q --host=%host --port=%port --user=%user --password=%pass %db';
$args = array(
'%file' => $file->filepath(),
'%host' => $this->dest_url['host'],
'%port' => !empty($this->dest_url['port']) ? $this->dest_url['port'] : '3306',
'%user' => $this->dest_url['user'],
'%pass' => $this->dest_url['pass'],
'%db' => $this->dest_url['path'],
);
// Ignore the excluded and no-data tables.
$db = $this->dest_url['path'];
if (!empty($settings->filters['exclude_tables'])) {
foreach ((array)$settings->filters['exclude_tables'] as $table) {
if (isset($alltables[$table])) {
$command .= ' --ignore-table='. $db .'.'. $table;
}
}
}
if (!empty($settings->filters['nodata_tables'])) {
foreach ((array)$settings->filters['nodata_tables'] as $table) {
if (isset($alltables[$table])) {
$nodata_tables[] = $table;
$command .= ' --ignore-table='. $db .'.'. $table;
}
}
}
$success = backup_migrate_exec($command, $args);
// Get the nodata tables.
if ($success && !empty($nodata_tables)) {
$tables = implode(' ', array_unique($nodata_tables));
$command = "mysqldump --no-data --opt -Q --host=%host --port=%port --user=%user --password=%pass %db $tables >> %file";
$success = backup_migrate_exec($command, $args);
}
return $success;
}
/**
* Backup the databases to a file.
*/
function _restore_db_from_file($file, $settings) {
$num = 0;
if ($file->open() && $conn = $this->_get_db_connection()) {
// Read one line at a time and run the query.
while ($line = $this->_read_sql_command_from_file($file)) {
if (_backup_migrate_check_timeout()) {
return FALSE;
}
if ($line) {
// Prepeare and exexute the statement instead of the api function to avoid substitution of '{' etc.
$stmt = $conn->prepare($line);
$stmt->execute();
$num++;
}
}
// Close the file with fclose/gzclose.
$file->close();
}
else {
drupal_set_message(t("Unable to open file %file to restore database", array("%file" => $file->filepath())), 'error');
$num = FALSE;
}
return $num;
}
/**
* Read a multiline sql command from a file.
*
* Supports the formatting created by mysqldump, but won't handle multiline comments.
*/
function _read_sql_command_from_file($file) {
$out = '';
while ($line = $file->read()) {
$line = trim($line);
// Ignore single line comments.
if (!empty($line) && substr($line, 0, 2) != '--') {
$out .= ' ' . $line;
// If a line ends in ; or */ it is a sql command.
if (substr($out, strlen($out) - 1, 1) == ';' || substr($out, strlen($out) - 2, 2) == '*/') {
return trim($out);
}
}
}
return trim($out);
}
/**
* Get a list of tables in the database.
*/
function _get_table_names() {
$out = array();
foreach ($this->_get_tables() as $table) {
$out[$table['name']] = $table['name'];
}
return $out;
}
/**
* Get a list of views in the database.
*/
function _get_view_names() {
$out = array();
foreach ($this->_get_views() as $view) {
$out[$view['name']] = $view['name'];
}
return $out;
}
/**
* Lock the list of given tables in the database.
*/
function _lock_tables($tables) {
if ($tables) {
$tables_escaped = array();
foreach ($tables as $table) {
$tables_escaped[] = '`'. db_escape_table($table) .'` WRITE';
}
$this->query('LOCK TABLES '. implode(', ', $tables_escaped));
}
}
/**
* Unlock all tables in the database.
*/
function _unlock_tables($settings) {
$this->query('UNLOCK TABLES');
}
/**
* Get a list of tables in the db.
*/
function _get_tables() {
$out = array();
// get auto_increment values and names of all tables
$tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($tables as $table) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$table = array_change_key_case($table);
if (!empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
/**
* Get a list of views in the db.
*/
function _get_views() {
$out = array();
// get auto_increment values and names of all tables
$tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($tables as $table) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$table = array_change_key_case($table);
if (empty($table['engine'])) {
$out[$table['name']] = $table;
}
}
return $out;
}
/**
* Get the sql for the structure of the given table.
*/
function _get_table_structure_sql($table) {
$out = "";
$result = $this->query("SHOW CREATE TABLE `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $create) {
// Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
// See: http://drupal.org/node/1171866
$create = array_change_key_case($create);
$out .= "DROP TABLE IF EXISTS `". $table['name'] ."`;\n";
// Remove newlines and convert " to ` because PDO seems to convert those for some reason.
$out .= strtr($create['create table'], array("\n" => ' ', '"' => '`'));
if ($table['auto_increment']) {
$out .= " AUTO_INCREMENT=". $table['auto_increment'];
}
$out .= ";\n";
}
return $out;
}
/**
* Get the sql for the structure of the given table.
*/
function _get_view_create_sql($view) {
$out = "";
// Switch SQL mode to get rid of "CREATE ALGORITHM..." what requires more permissions + troubles with the DEFINER user
$sql_mode = $this->query("SELECT @@SESSION.sql_mode")->fetchField();
$this->query("SET sql_mode = 'ANSI'");
$result = $this->query("SHOW CREATE VIEW `" . $view['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
$this->query("SET SQL_mode = :mode", array(':mode' => $sql_mode));
foreach ($result as $create) {
$out .= "DROP VIEW IF EXISTS `". $view['name'] ."`;\n";
$out .= "SET sql_mode = 'ANSI';\n";
$out .= strtr($create['Create View'], "\n", " ") . ";\n";
$out .= "SET sql_mode = '$sql_mode';\n";
}
return $out;
}
/**
* Get the sql to insert the data for a given table
*/
function _dump_table_data_sql_to_file($file, $table) {
$rows_per_line = variable_get('backup_migrate_data_rows_per_line', 30);
$bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', 2000);
$lines = 0;
$data = $this->query("SELECT * FROM `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
$rows = $bytes = 0;
// Escape backslashes, PHP code, special chars
$search = array('\\', "'", "\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\\\\', "''", '\0', '\n', '\r', '\Z');
$line = array();
foreach ($data as $row) {
// DB Escape the values.
$items = array();
foreach ($row as $key => $value) {
$items[] = is_null($value) ? "null" : "'". str_replace($search, $replace, $value) ."'";
}
// If there is a row to be added.
if ($items) {
// Start a new line if we need to.
if ($rows == 0) {
$file->write("INSERT INTO `". $table['name'] ."` VALUES ");
$bytes = $rows = 0;
}
// Otherwise add a comma to end the previous entry.
else {
$file->write(",");
}
// Write the data itself.
$sql = implode(',', $items);
$file->write('('. $sql .')');
$bytes += strlen($sql);
$rows++;
// Finish the last line if we've added enough items
if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
$file->write(";\n");
$lines++;
$bytes = $rows = 0;
}
}
}
// Finish any unfinished insert statements.
if ($rows > 0) {
$file->write(";\n");
$lines++;
}
return $lines;
}
/**
* Get the db connection for the specified db.
*/
function _get_db_connection() {
if (!$this->connection) {
$this->connection = parent::_get_db_connection();
// Set the sql mode because the default is ANSI,TRADITIONAL which is not aware of collation or storage engine.
$this->connection->exec("SET sql_mode=''");
}
return $this->connection;
}
/**
* Run a db query on this destination's db.
*/
function query($query, $args = array(), $options = array()) {
if ($conn = $this->_get_db_connection()) {
return $conn->query($query, $args, $options);
}
}
/**
* The header for the top of the sql dump file. These commands set the connection
* character encoding to help prevent encoding conversion issues.
*/
function _get_sql_file_header() {
return "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
SET NAMES utf8;
";
}
/**
* The footer of the sql dump file.
*/
function _get_sql_file_footer() {
return "
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
";
}
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* @file
* Functions to handle the email backup destination.
*/
/**
* A destination for emailing database backups.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_email extends backup_migrate_destination {
var $supported_ops = array('scheduled backup', 'manual backup', 'configure');
/**
* Save to (ie. email the file) to the email destination.
*/
function save_file($file, $settings) {
$size = filesize($file->filepath());
$max = variable_get('backup_migrate_max_email_size', 20971520);
if ($size > $max) {
_backup_migrate_message('Could not email the file @file because it is @size and Backup and Migrate only supports emailing files smaller than @max.', array('@file' => $file->filename(), '@size' => format_size($size), '@max' => format_size($max)), 'error');
return FALSE;
}
$attachment = new stdClass();
$attachment->filename = $file->filename();
$attachment->path = $file->filepath();
_backup_migrate_destination_email_mail_backup($attachment, $this->get_location());
return $file;
}
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
$form = parent::edit_form();
$form['location'] = array(
"#type" => "textfield",
"#title" => t("Email Address"),
"#default_value" => $this->get_location(),
"#required" => TRUE,
"#description" => t('Enter the email address to send the backup files to. Make sure the email server can handle large file attachments.'),
);
return $form;
}
/**
* Validate the configuration form. Make sure the email address is valid.
*/
function settings_form_validate($values) {
if (!valid_email_address($values['location'])) {
form_set_error('[location]', t('The e-mail address %mail is not valid.', array('%mail' => $form_state['values']['location'])));
}
}
}
/**
* @function
* Temporary mail handler class.
*
* Defines a mail class to send a message with an attachment. Eventually Drupal
* core should provide this functionality, at which time this code will be
* removed.
*
* More info on sending email at <http://php.net/function.mail>.
* This function taken from dba.module.
*
* @param $attachment
* An object which contains two variables "path" the path to the file and
* filename and "filename" which is just the filename.
*/
function _backup_migrate_destination_email_mail_backup($attachment, $to) {
// Send mail
$attach = fread(fopen($attachment->path, "r"), filesize($attachment->path));
$mail = new mime_mail();
$mail->from = variable_get('site_mail', ini_get('sendmail_from'));
$mail->headers = 'Errors-To: [EMAIL='. $mail->from .']'. $mail->from .'[/EMAIL]';
$mail->to = $to;
$mail->subject = t('Database backup from !site: !file', array('!site' => variable_get('site_name', 'drupal'), '!file' => $attachment->filename));
$mail->body = t('Database backup attached.') ."\n\n";
$mail->add_attachment("$attach", $attachment->filename, "Content-Transfer-Encoding: base64 /9j/4AAQSkZJRgABAgEASABIAAD/7QT+UGhvdG9zaG", NULL, TRUE);
$mail->send();
}
class mime_mail {
var $parts;
var $to;
var $from;
var $headers;
var $subject;
var $body;
function mime_mail() {
$this->parts = array();
$this->to = "";
$this->from = "";
$this->headers = "";
$this->subject = "";
$this->body = "";
}
function add_attachment($message, $name = "", $ctype = "application/octet-stream", $encode = NULL, $attach = FALSE) {
$this->parts[] = array(
"ctype" => $ctype,
"message" => $message,
"encode" => $encode,
"name" => $name,
"attach" => $attach,
);
}
function build_message($part) {
$message = $part["message"];
$message = chunk_split(base64_encode($message));
$encoding = "base64";
$disposition = $part['attach'] ? "Content-Disposition: attachment; filename=$part[name]\n" : '';
return "Content-Type: ". $part["ctype"] . ($part["name"] ? "; name = \"". $part["name"] ."\"" : "") ."\nContent-Transfer-Encoding: $encoding\n$disposition\n$message\n";
}
function build_multipart() {
$boundary = "b". md5(uniqid(time()));
$multipart = "Content-Type: multipart/mixed; boundary = $boundary\n\nThis is a MIME encoded message.\n\n--$boundary";
for ($i = sizeof($this->parts) - 1; $i >= 0; $i--) {
$multipart .= "\n". $this->build_message($this->parts[$i]) ."--$boundary";
}
return $multipart .= "--\n";
}
function send() {
$mime = "";
if (!empty($this->from)) $mime .= "From: ". $this->from ."\n";
if (!empty($this->headers)) $mime .= $this->headers ."\n";
if (!empty($this->body)) $this->add_attachment($this->body, "", "text/plain");
$mime .= "MIME-Version: 1.0\n". $this->build_multipart();
mail(trim($this->to), $this->subject, "", $mime);
}
}

View File

@@ -0,0 +1,274 @@
<?php
/**
* @file
* A destination type for saving locally to the server.
*/
/**
* A destination type for saving locally to the server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_files extends backup_migrate_destination {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
function type_name() {
return t("Server Directory");
}
/**
* Get the file location.
*/
function get_realpath() {
return drupal_realpath($this->get_location());
}
/**
* File save destination callback.
*/
function _save_file($file, $settings) {
if ($dir = $this->get_location()) {
if ($dir = $this->check_dir($dir)) {
$filepath = rtrim($dir, "/") ."/". $file->filename();
if (file_unmanaged_move($file->filepath(), $filepath)) {
// chmod, chown and chgrp the file if needed.
if ($chmod = $this->settings('chmod')) {
if (!@drupal_chmod($filepath, octdec($chmod))) {
_backup_migrate_message('Unable to set the file mode for: @file', array('@file' => $filepath), 'error');
}
}
if ($chgrp = $this->settings('chgrp')) {
if (!@chgrp($filepath, $chgrp)) {
_backup_migrate_message('Unable to set the file group for: @file', array('@file' => $filepath), 'error');
}
}
return $file;
}
else {
_backup_migrate_message('Unable to save the file to the directory: @dir', array('@dir' => $dir), 'error');
}
}
}
}
/**
* Determine if we can read the given file.
*/
function can_read_file($file_id) {
return $this->op('restore') && is_readable($this->get_filepath($file_id));
}
/**
* File load destination callback.
*/
function load_file($file_id) {
$filepath = $this->get_filepath($file_id);
if (file_exists($filepath)) {
backup_migrate_include('files');
return new backup_file(array('filepath' => $filepath));
}
}
/**
* File list destination callback.
*/
function _list_files() {
$files = array();
if ($dir = $this->get_realpath()) {
if ($handle = @opendir($dir)) {
backup_migrate_include('files');
while (FALSE !== ($file = readdir($handle))) {
$filepath = $dir ."/". $file;
$files[$file] = new backup_file(array('filepath' => $filepath));
}
}
}
return $files;
}
/**
* File delete destination callback.
*/
function _delete_file($file_id) {
$filepath = $this->get_filepath($file_id);
file_unmanaged_delete($filepath);
}
/**
* Get the filepath from the given file id.
*/
function get_filepath($file_id) {
if ($dir = $this->get_realpath()) {
$filepath = rtrim($dir, '/') .'/'. $file_id;
return $filepath;
}
return FALSE;
}
/**
* Get the form for the settings for the files destination.
*/
function edit_form() {
$form = parent::edit_form();
$form['location'] = array(
"#type" => "textfield",
"#title" => t("Directory path"),
"#default_value" => $this->get_location(),
"#required" => TRUE,
"#description" => t('Enter the path to the directory to save the backups to. Use a relative path to pick a path relative to your Drupal root directory. The web server must be able to write to this path.'),
);
$form['settings'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced Settings'),
'#tree' => TRUE,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
if (function_exists('chmod')) {
$form['settings']['chmod'] = array(
'#type' => 'textfield',
'#title' => t('Change file mode (chmod)'),
'#size' => 5,
'#default_value' => $this->settings('chmod'),
'#description' => t('If you enter a value here, backup files will be chmoded with the mode you specify. Specify the mode in octal form (e.g. 644 or 0644) or leave blank to disable this feature.'),
);
}
if (function_exists('chgrp')) {
$form['settings']['chgrp'] = array(
'#type' => 'textfield',
'#title' => t('Change file group (chgrp)'),
'#size' => 5,
'#default_value' => $this->settings('chgrp'),
'#description' => t('If you enter a value here, backup files will be chgrped to the group you specify. Leave blank to disable this feature.'),
);
}
return $form;
}
/**
* Validate the form for the settings for the files destination.
*/
function edit_form_validate($form, &$form_state) {
$values = $form_state['values'];
if (isset($values['settings']['chmod']) && !empty($values['settings']['chmod']) && !preg_match('/0?[0-7]{3}/', $values['settings']['chmod'])) {
form_set_error('chmod', t('You must enter a valid chmod octal value (e.g. 644 or 0644) in the change mode field, or leave it blank.'));
}
parent::edit_form_validate($form, $form_state);
}
/**
* Submit the form for the settings for the files destination.
*/
function edit_form_submit($form, &$form_state) {
// Add a 0 to the start of a 3 digit file mode to make it proper PHP encoded octal.
if (strlen($form_state['values']['settings']['chmod']) == 3) {
$form_state['values']['settings']['chmod'] = '0' . $form_state['values']['settings']['chmod'];
}
parent::edit_form_submit($form, $form_state);
}
/**
* Prepare the destination directory for the backups.
*/
function check_dir($directory) {
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
// Unable to create destination directory.
_backup_migrate_message("Unable to create or write to the save directory '%directory'. Please check the file permissions that directory and try again.", array('%directory' => $directory), "error");
return FALSE;
}
// If the destination directory is within the webroot, then secure it as best we can.
if ($this->dir_in_webroot($directory)) {
$directory = $this->check_web_dir($directory);
}
return $directory;
}
/**
* Check that a web accessible directory has been properly secured, othewise attempt to secure it.
*/
function check_web_dir($directory) {
// If the directory is specified with an absolute path, strip the site root.
$directory = substr(drupal_realpath($directory), strlen(DRUPAL_ROOT . '/'));
file_create_htaccess($directory, TRUE);
// Check the user agent to make sure we're not responding to a request from drupal itself.
// That should prevent infinite loops which could be caused by poormanscron in some circumstances.
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Drupal') !== FALSE) {
return FALSE;
}
// Check to see if the destination is publicly accessible
$test_contents = "this file should not be publicly accessible";
// Create the the text.txt file if it's not already there.
if (!is_file($directory .'/test.txt') || file_get_contents($directory .'/test.txt') != $test_contents) {
if ($fp = fopen($directory .'/test.txt', 'w')) {
@fputs($fp, $test_contents);
fclose($fp);
}
else {
$message = t("Security notice: Backup and Migrate was unable to write a test text file to the destination directory %directory, and is therefore unable to check the security of the backup destination. Backups to the server will be disabled until the destination becomes writable and secure.", array('%directory' => $directory));
drupal_set_message($message, "error");
return FALSE;
}
}
// Attempt to read the test file via http. This may fail for other reasons,
// so it's not a bullet-proof check.
if ($this->test_file_readable_remotely($directory .'/test.txt', $test_contents)) {
$message = t("Security notice: Backup and Migrate will not save backup files to the server because the destination directory is publicly accessible. If you want to save files to the server, please secure the '%directory' directory", array('%directory' => $directory));
drupal_set_message($message, "error");
return FALSE;
}
return $directory;
}
/**
* Check if the given directory is within the webroot and is therefore web accessible.
*/
function dir_in_webroot($directory) {
if (strpos(drupal_realpath($directory), DRUPAL_ROOT) !== FALSE) {
return TRUE;
}
return FALSE;
}
/**
* Check if a file can be read remotely via http.
*/
function test_file_readable_remotely($path, $contents) {
$url = $GLOBALS['base_url'] . '/' . str_replace('\\', '/', $path);
$result = drupal_http_request($url);
if (!empty($result->data) && strpos($result->data, $contents) !== FALSE) {
return TRUE;
}
return FALSE;
}
}
/**
* The manual files directory.
*/
class backup_migrate_destination_files_manual extends backup_migrate_destination_files {
var $supported_ops = array('manual backup', 'restore', 'list files', 'configure', 'delete');
function __construct($params = array()) {
$dir = 'private://backup_migrate/manual';
parent::__construct($params + array('location' => $dir, 'name' => t('Manual Backups Directory')));
}
}
/**
* The scheduled files directory.
*/
class backup_migrate_destination_files_scheduled extends backup_migrate_destination_files {
var $supported_ops = array('scheduled backup', 'restore', 'list files', 'configure', 'delete');
function __construct($params = array()) {
$dir = 'private://backup_migrate/scheduled';
parent::__construct($params + array('location' => $dir, 'name' => t('Scheduled Backups Directory')));
}
}

View File

@@ -0,0 +1,436 @@
<?php
/**
* @file
* Functions to handle the FTP backup destination.
*/
/**
* A destination for sending database backups to an FTP server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_ftp extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
var $ftp = NULL;
/**
* Save to the ftp destination.
*/
function _save_file($file, $settings) {
$ftp = $this->ftp_object();
if (drupal_ftp_file_to_ftp($file->filepath(), $file->filename(), '.', $ftp)) {
return $file;
}
return FALSE;
}
/**
* Load from the ftp destination.
*/
function load_file($file_id) {
backup_migrate_include('files');
$file = new backup_file(array('filename' => $file_id));
$this->ftp_object();
if (drupal_ftp_ftp_to_file($file->filepath(), $file_id, '.', $this->ftp)) {
return $file;
}
return FALSE;
}
/**
* Delete from the ftp destination.
*/
function _delete_file($file_id) {
$this->ftp_object();
drupal_ftp_delete_file($file_id, $this->ftp);
}
function _list_files() {
backup_migrate_include('files');
$files = array();
$this->ftp_object();
$ftp_files = drupal_ftp_file_list('.', $this->ftp);
foreach ($ftp_files as $file) {
$files[$file['filename']] = new backup_file($file);
}
return $files;
}
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
$form = parent::edit_form();
$form['scheme']['#type'] = 'value';
$form['scheme']['#value'] = 'ftp';
$form['port'] = array(
"#type" => "textfield",
"#title" => t("Port"),
"#default_value" => @$this->dest_url['port'] ? $this->dest_url['port'] : '21',
"#weight" => 15,
);
$form['pasv'] = array(
'#type' => 'checkbox',
'#title' => t('Use PASV transfers'),
'#default_value' => $this->get_pasv(),
'#weight' => 50,
);
return $form;
}
function set_pasv($value) {
$this->settings['pasv'] = (bool)$value;
}
function get_pasv() {
return isset($this->settings['pasv']) ? $this->settings['pasv'] : FALSE;
}
function ftp_object() {
if (!$this->ftp) {
$this->dest_url['port'] = empty($this->dest_url['port']) ? '21' : $this->dest_url['port'];
$this->dest_url['pasv'] = $this->get_pasv();
$this->ftp = drupal_ftp_ftp_object($this->dest_url['host'], $this->dest_url['port'], $this->dest_url['user'], $this->dest_url['pass'], $this->dest_url['path'], $this->dest_url['pasv']);
}
return $this->ftp;
}
}
// The FTP code below was taken from the ftp module by Aaron Winborn.
// Inspired by http://www.devarticles.com/c/a/PHP/My-FTP-Wrapper-Class-for-PHP/
// It's been drupalized, however, and most of the bugs from that example have been fixed.
// - winborn 2007-06-22 - 2007-06-28
define('DRUPAL_FTP_FT_DIRECTORY', 0);
define('DRUPAL_FTP_FT_FILE', 1);
/**
* creates a new ftp object. if any elements of ftp_map are missing, they'll be filled with the server defaults.
*/
function drupal_ftp_ftp_object($server, $port, $user, $pass, $dir, $pasv) {
$ftp = new stdClass();
$ftp->__server = $server;
$ftp->__port = $port;
$ftp->__user = $user;
$ftp->__password = $pass;
$ftp->__directory = $dir;
$ftp->__pasv = $pasv;
return $ftp;
}
/**
* The drupal_ftp_connect function
* This function connects to an FTP server and attempts to change into the directory specified by
* the fourth parameter, $directory.
*/
function drupal_ftp_connect(&$ftp) {
if (is_NULL($ftp)) {
$ftp = drupal_ftp_ftp_object();
}
if (empty($ftp->__conn) && !drupal_ftp_connected($ftp)) {
// Attempt to connect to the remote server
$ftp->__conn = @ftp_connect($ftp->__server, $ftp->__port);
if (!$ftp->__conn) {
_backup_migrate_message('FTP Error: Couldn\'t connect to server @server', array('@server' => $ftp->__server), 'error');
return FALSE;
}
// Attempt to login to the remote server
$ftp->__login = @ftp_login($ftp->__conn, $ftp->__user, $ftp->__password);
if (!$ftp->__login) {
_backup_migrate_message('FTP Error: Couldn\'t login as user @ftp_user to @server', array('@ftp_user' => $ftp->__user, '@server' => $ftp->__server), 'error');
return FALSE;
}
// Attempt to change into the working directory
$chdir = @ftp_chdir($ftp->__conn, $ftp->__directory);
if (!$chdir) {
_backup_migrate_message('FTP Error: Couldn\'t change into the @directory directory', array('@directory' => $ftp->__directory), 'error');
return FALSE;
}
// Set PASV - if needed
if ($ftp->__pasv) {
$pasv = @ftp_pasv($ftp->__conn, TRUE);
if (!$pasv) {
_backup_migrate_message('FTP Error: Couldn\'t set PASV mode', array(), 'error');
return FALSE;
}
}
}
// Everything worked OK, return TRUE
return TRUE;
}
/**
* The drupal_ftp_connected function
* This function queries the FTP server with the ftp_systype command to check if the connection is still alive.
* It returns TRUE on success or FALSE on disconnection.
*/
function drupal_ftp_connected(&$ftp) {
// Attempt to call the ftp_systype to see if the connect
// to the FTP server is still alive and kicking
if (is_NULL($ftp)) {
$ftp = drupal_ftp_ftp_object();
return FALSE;
}
if (!@ftp_systype($ftp->__conn)) {
// The connection is dead
return FALSE;
}
else {
// The connection is still alive
return TRUE;
}
}
/**
* This function tries to retrieve the contents of a file from the FTP server.
* Firstly it changes into the $directory directory, and then attempts to download the file $filename.
* The file is saved locally and its contents are returned to the caller of the function.
*/
function drupal_ftp_ftp_to_file($file, $filename, $directory, &$ftp) {
// Change into the remote directory and retrieve the content
// of a file. Once retrieve, return this value to the caller
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
// We are now connected, so let's retrieve the file contents.
// Firstly, we change into the directory
$chdir = @ftp_chdir($ftp->__conn, $directory);
if (!$chdir) {
_backup_migrate_message('FTP Error: Couldn\'t change into directory: @directory', array('@directory' => $directory), 'error');
return FALSE;
}
// We have changed into the directory, let's attempt to get the file
$fp = @fopen($file, 'wb');
$get_file = @ftp_fget($ftp->__conn, $fp, $filename, FTP_BINARY);
fclose($fp);
$fp = NULL;
if (!$get_file) {
_backup_migrate_message('FTP Error: Unable to download file: @filename from @directory', array('@filename' => $filename, '@directory' => $directory), 'error');
return FALSE;
}
return TRUE;
}
/**
* Send a file to an FTP server.
*/
function drupal_ftp_file_to_ftp($file, $ftp_filename, $ftp_directory, &$ftp) {
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
if ($source = drupal_realpath($file)) {
// Now we can try to write to the remote file
$complete_filename = $ftp_directory .'/'. $ftp_filename;
$put_file = @ftp_put($ftp->__conn, $complete_filename, $source, FTP_BINARY);
if (!$put_file) {
_backup_migrate_message('FTP Error: Couldn\'t write to @complete_filename when trying to save file on the ftp server.', array('@complete_filename' => $complete_filename), 'error');
return FALSE;
}
// Everything worked OK
return TRUE;
}
else {
_backup_migrate_message('FTP Error: Couldn\'t find @file.', array('@file'), 'error');
return FALSE;
}
}
/**
* The drupal_ftp_change_directory Function
* This function simply changes into the $directory folder on the FTP server.
* If a connection or permission error occurs then _backup_migrate_message() will contain the error message.
*/
function drupal_ftp_change_directory($directory, &$ftp) {
// Switch to another directory on the web server. If we don't
// have permissions then an error will occur
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
// Try and change into another directory
$chdir = ftp_chdir($ftp->__conn, $directory);
if (!$chdir) {
_backup_migrate_message('FTP Error: Couldn\'t change into directory: @directory', array('@directory', $directory), 'error');
return FALSE;
}
else {
// Changing directories worked OK
return TRUE;
}
}
/**
* The drupal_ftp_file_list Function
* This function will change into the $directory folder and get a list of files and directories contained in that folder.
* This function still needs a lot of work, but should work in most cases.
*/
function drupal_ftp_file_list($directory, &$ftp) {
// This function will attempt to change into the specified
// directory and retrieve a list of files as an associative
// array. This list will include file name, size and date last modified
$file_array = array();
// Can we switch to the desired directory?
if (!drupal_ftp_change_directory($directory, $ftp)) {
return FALSE;
}
// We are in the directory, let's retrieve a list of files
// This is slower than parsing the raw return values, but it is faster.
$file_list = ftp_nlist($ftp->__conn, $directory);
// Save the list of files
if (@is_array($file_list)) {
// Interate through the array
foreach ($file_list as $file) {
$file_array[] = array(
'filename' => $file,
'filesize' => ftp_size($ftp->__conn, $directory ."/". $file),
'filetime' => ftp_mdtm($ftp->__conn, $directory ."/". $file),
);
}
}
sort($file_array);
return $file_array;
}
/**
* The drupal_ftp_create_directory Function
* This function tries to make a new directory called $folder_name on the FTP server.
* If it can create the folder, then the folder is given appropriate rights with the CHMOD command.
*/
function drupal_ftp_create_directory($folder_name, &$ftp) {
// Makes a new folder on the web server via FTP
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
$create_result = @ftp_mkdir($ftp->__conn, $folder_name);
if ($create_result == TRUE) {
// Can we change the files permissions?
$exec_result = @ftp_site($ftp->__conn, 'chmod 0777 '. $folder_name .'/');
if ($exec_result == TRUE) {
return TRUE;
}
else {
_backup_migrate_message('FTP Error: Couldn\'t set owner permissions on @folder.', array('@folder', $folder_name), 'error');
return FALSE;
}
}
else {
_backup_migrate_message('FTP Error: Couldn\'t create new folder @folder.', array('@folder', $folder_name), 'error');
return FALSE;
}
}
/**
* The drupal_ftp_delete_file Function
* This function attempts to delete a file called $filename from the FTP server.
*/
function drupal_ftp_delete_file($filename, &$ftp) {
// Remove the specified file from the FTP server
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
$delete_result = @ftp_delete($ftp->__conn, $filename);
if ($delete_result == TRUE) {
// The file/folder was renamed successfully
return TRUE;
}
else {
// Couldn't delete the selected file
_backup_migrate_message('FTP Error: Couldn\'t delete the selected file: @filename', array('@filename' => $filename), 'error');
return FALSE;
}
}
/**
* The drupal_ftp_delete_folder Function
* This function was one of the hardest to write. It recursively deletes all files and folders from a directory called $folder_name.
*/
function drupal_ftp_delete_folder($folder_name, &$ftp) {
if (!@drupal_ftp_connect($ftp)) {
return FALSE;
}
@ftp_chdir($ftp->__conn, $folder_name);
$location = @ftp_pwd($ftp->__conn);
$directories = array();
$files = array();
$dir_counter = 0;
$file_counter = 0;
$content = @ftp_nlist($ftp->__conn, ".");
for ($i = 0; $i < sizeof($content); $i++) {
// If we can change into this then it's a directory.
// If not, it's a file
if ($content[$i] != "." && $content[$i] != "..") {
if (@ftp_chdir($ftp->__conn, $content[$i])) {
// We have a directory
$directories[] = $content[$i];
$dir_counter++;
@ftp_cdup($ftp->__conn);
}
else {
// We have a file
$files[] = $content[$i];
$file_counter++;
}
}
}
for ($j = 0; $j < $file_counter; $j++) {
@ftp_delete($ftp->__conn, $files[$j]);
}
for ($j = 0; $j < $dir_counter; $j++) {
if ($directories[$j] != "." OR $directories[$j] != "..") {
$location = ftp_pwd($ftp->__conn);
drupal_ftp_delete_folder($directories[$j], $ftp);
@ftp_cdup ($ftp->__conn);
@ftp_rmdir($ftp->__conn, $directories[$j]);
}
}
// Lastly, we change into the directory that we want to delete and see
// if we can cdup. If we can, we delete it.
@ftp_chdir($ftp->__conn, $folder_name);
@ftp_cdup($ftp->__conn);
@ftp_rmdir($ftp->__conn, $folder_name);
// Did the recursive folder/file deletion work?
return TRUE;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,733 @@
<?php
/**
* @file
* Functions to handle the NodeSquirrel backup destination.
*/
define('NODESQUIRREL_SECRET_KEY_PATTERN', '/^[0-9a-f]{32}\:?[0-9a-f]{32}$/');
/**
* The NodeSquirrel settings form page.
*/
function nodesquirrel_settings_page() {
return drupal_get_form('nodesquirrel_settings');
}
/**
* Check that a nodesquirel key is valid.
*/
function nodesquirrel_check_secret_key($secret_key) {
if ($destination = nodesquirrel_get_destination($secret_key)) {
if ($destination->confirm_destination()) {
return $destination;
}
}
return FALSE;
}
/**
* Get the NS destination for the given key.
*/
function nodesquirrel_get_destination($secret_key) {
if ($secret_key) {
backup_migrate_include('destinations');
$destination = backup_migrate_create_destination('nodesquirrel', array('destination_id' => 'nodesquirrel'));
$destination->settings['secret_key'] = $secret_key;
return $destination;
}
return NULL;
}
/**
* Get a helper link to activate a site and create a tree.
*/
function nodesquirrel_get_activate_help_text() {
$activate_link = nodesquirrel_get_activate_link();
return array(
'#type' => 'item',
'#title' => t('Need a Secret Key?'),
'#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
'#description' => t('Don\'t worry if you don\'t have an account yet. You can create one when you get there.'),
);
}
/**
* Get a helper link to activate a site and create a tree.
*/
function nodesquirrel_get_activate_link() {
$activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'http://manage.nodesquirrel.com/activate'), array('query' => array('url' => url('', array('absolute' => TRUE)), 'email' => variable_get('site_mail', ''), 'configure' => url($_GET['q'], array('absolute' => TRUE)))));
return $activate_link;
}
/**
* Get a helper link to activate a site and create a tree.
*/
function nodesquirrel_get_manage_link($destination) {
$url = variable_get('nodesquirrel_manage_url', 'http://manage.nodesquirrel.com') . '/backups/' . $destination->_get_destination();
return l($url, $url);
}
/**
* NodeSquirrel settings form.
*/
function nodesquirrel_settings($form_state) {
_backup_migrate_message_callback('_backup_migrate_message_browser');
$form = array();
$key = variable_get('nodesquirrel_secret_key', '');
$destination = nodesquirrel_check_secret_key($key);
$form['intro'] = array(
'#type' => 'markup',
'#markup' => t('<p>For better protection, back your site up regularly to a location not on your web server. !nodesquirrel is the cloud backup service built by the maintainers of Backup and Migrate. Find out more at <a href="http://nodesquirrel.com">nodesquirrel.com</a></p><p>You can also !add such as FTP or Amazon S3. Additional 3rd party options are available and many are listed on the !bam.', array('!nodesquirrel' => l(t('NodeSquirrel'), 'http://nodesquirrel.com'), '!add' => l(t('add other offsite destinations'), BACKUP_MIGRATE_MENU_PATH . '/destination/list/add'), '!bam' => l(t('Backup and Migrate project page'), 'http://drupal.org/project/backup_migrate'))),
);
$form['nodesquirrel_status'] = array(
'#type' => 'fieldset',
'#title' => t('NodeSquirrel Status'),
);
$form['nodesquirrel_status']['status'] = array(
'#type' => 'item',
'#title' => t('NodeSquirrel Status'),
'#markup' => t('Not Configured'),
);
// Warn the user if the key they entered is invalid.
if ($key && empty($destination)) {
$form['nodesquirrel_status']['status']['#markup'] = t('Your secret key does not seem to be valid. Please check that you entered it correctly or visit !ns to generate a new key.', array('!ns' => nodesquirrel_get_activate_link()));
}
else if (!empty($destination)) {
$form['nodesquirrel_status']['manage'] = array(
'#type' => 'item',
'#title' => t('Management Console'),
'#markup' => nodesquirrel_get_manage_link($destination),
'#description' => t('You can use the NodeSquirrel management console to add and edit your sites, reset your secret key, download and delete backups, and modify your NodeSquirrel account.'),
);
$form['nodesquirrel_status']['status']['#markup'] = t('Ready to Backup');
if (user_access('perform backup')) {
$form['nodesquirrel_status']['status']['#markup'] .= ' ' . l('(' . t('backup now') . ')', BACKUP_MIGRATE_MENU_PATH, array('query' => array('destination_id' => 'nodesquirrel')));
}
}
$form['nodesquirrel_credentials'] = array(
'#type' => 'fieldset',
'#title' => t('NodeSquirrel Credentials'),
);
$form['nodesquirrel_credentials']['nodesquirrel_secret_key'] = array(
'#type' => 'textfield',
'#title' => t('Secret Key'),
'#size' => 80,
'#default_value' => variable_get('nodesquirrel_secret_key', ''),
);
if (empty($destination)) {
$form['nodesquirrel_credentials']['secret_key_help'] = nodesquirrel_get_activate_help_text();
}
$form['nodesquirrel_schedule'] = array(
'#type' => 'fieldset',
'#title' => t('Backup Schedule'),
);
$schedule = variable_get('nodesquirrel_schedule', 60*60*24);
$form['nodesquirrel_schedule']['nodesquirrel_schedule'] = array(
'#type' => 'select',
'#title' => t('Backup to NodeSquirrel'),
'#options' => array(
'' => t('- None - '),
(60*60) => t('Hourly'),
(60*60*24) => t('Daily'),
(60*60*24*7) => t('Weekly'),
),
'#default_value' => variable_get('nodesquirrel_schedule', 60*60*24),
'#description' => t('Set up a schedule to back up your database to NodeSquirrel. You can customize this schedule in the !schedule. Not seeing your automatic backups? Make sure !cron is set to run at the same frequency or higher.', array('!schedule' => l(t('Schedules tab'), BACKUP_MIGRATE_MENU_PATH . '/schedule'), '!cron' => l(t('cron'), 'http://drupal.org/cron'))),
);
// If the schedule has been overriden it must be edited in the schedule tab.
backup_migrate_include('crud');
$item = backup_migrate_crud_get_item('schedule', 'nodesquirrel');
if ($item && $item->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$form['nodesquirrel_schedule']['nodesquirrel_schedule']['#options'] = array('' => $item->get_frequency_description());
$form['nodesquirrel_schedule']['nodesquirrel_schedule']['#disabled'] = TRUE;
$form['nodesquirrel_schedule']['nodesquirrel_schedule']['#description'] = t('Your NodeSquirrel schedule has been overriden and must be edited in the !schedule.', array('!schedule' => l(t('Schedules tab'), BACKUP_MIGRATE_MENU_PATH . '/schedule/list/edit/nodesquirrel')));
}
return system_settings_form($form);
}
/**
* A destination for sending database backups to the NodeSquirel backup service.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_nodesquirrel extends backup_migrate_destination {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
var $cache_files = TRUE;
// Don't generate a metadata file as NodeSquirrel can save metadata natively.
var $save_metadata = FALSE;
/**
* Get the destination name. Provide a default.
*/
function get_name() {
if (empty($this->name)) {
return t('NodeSquirrel');
}
return $this->name;
}
/**
* Save to the NodeSquirrel destination.
*/
function save_file($file, $settings) {
if ($destination = $this->_get_destination()) {
srand((double)microtime()*1000000);
$filename = $file->filename();
$filesize = filesize($file->filepath());
$ticket = $this->_xmlrpc('backups.getUploadTicket', array($destination, $filename, $filesize, $file->file_info));
if ($ticket) {
$url = $ticket['url'];
// If the ticket requires authentication add our username/password to the url.
if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
$parts = parse_url($ticket['url']);
list($parts['user'], $parts['pass']) = $this->get_user_pass();
$url = $this->glue_url($parts, FALSE);
}
$out = $this->_post_file($url, 'POST', $ticket['params'], $file);
if ($out->code == 200) {
// Confirm the upload.
$confirm = $this->_xmlrpc('backups.confirmUpload', array($destination, $filename, $filesize));
if ($confirm['success']) {
// Set a message with a link to the manage console.
$url = variable_get('nodesquirrel_manage_url', 'http://manage.nodesquirrel.com') . '/backups/' . $this->_get_destination();
_backup_migrate_message('Your backup has been saved to your NodeSquirrel account. View it at !account', array('!account' => l($url, $url)));
return $file;
}
else {
_backup_migrate_message('The backup file never made it to the NodeSquirrel backup server. There may have been a network problem. Please try again later');
}
}
else {
$error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
_backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $error), 'error');
}
}
else if ($err = xmlrpc_error()) {
// XMLRPC errors are already handled by the server function below.
}
else {
_backup_migrate_message('The NodeSquirrel server refused the backup but did not specify why. Maybe the server is down.');
}
}
return NULL;
}
/**
* Load from the NodeSquirrel destination.
*/
function load_file($file_id) {
if ($destination = $this->_get_destination()) {
backup_migrate_include('files');
$file = new backup_file(array('filename' => $file_id));
$ticket = $this->_xmlrpc('backups.getDownloadTicket', array($destination, $file_id));
if ($ticket && $url = $ticket['url']) {
// If the ticket requires authentication add our username/password to the url.
if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
$parts = parse_url($ticket['url']);
$parts['user'] = @$this->dest_url['user'];
$parts['pass'] = @$this->dest_url['pass'];
$url = $this->glue_url($parts, FALSE);
}
$out = drupal_http_request($url);
if ($out->code == 200) {
file_put_contents($file->filepath(), $out->data);
return $file;
}
else {
$error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
_backup_migrate_message('The server returned the following error: %err', array('%err' => $error), 'error');
}
}
}
return NULL;
}
/**
* Delete from the NodeSquirrel destination.
*/
function delete_file($file_id) {
if ($destination = $this->_get_destination()) {
$result = $this->_xmlrpc('backups.deleteFile', array($destination, $file_id));
}
}
/**
* List the files in the remote destination.
*/
function _list_files() {
$files = array();
backup_migrate_include('files');
if ($destination = $this->_get_destination()) {
$file_list = $this->_xmlrpc('backups.listFiles', array($destination));
foreach ((array)$file_list as $file) {
$files[$file['filename']] = new backup_file($file);
}
}
return $files;
}
/**
* List the files in the remote destination.
*/
function check_limits() {
if (empty($this->limits)) {
$this->limits = $this->_xmlrpc('backups.getLimits', array($this->_get_destination()));
}
return $this->limits;
}
/**
* Check that a destination is valid.
*/
function confirm_destination() {
return $this->check_limits();
}
/**
* Get the form for the settings for this destination.
*/
function edit_form() {
$form = parent::edit_form();
$form['settings'] = array('#tree' => TRUE);
$activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'http://manage.nodesquirrel.com/activate'), array('query' => array('url' => url('', array('absolute' => TRUE)), 'email' => variable_get('site_mail', ''), 'configure' => url($_GET['q'], array('absolute' => TRUE)))));
// Retrieve the key from the settings or get it from the get string if this is an auto-config action.
$key = $this->settings('secret_key');
if (!empty($_GET['key']) && preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $_GET['key'])) {
$key = $_GET['key'];
}
$form['settings']['secret_key'] = array(
'#type' => 'textfield',
'#title' => t('Secret Key'),
'#default_value' => $key,
);
$form['settings']['location'] = array('#type' => 'value', '#value' => '');
$form['settings']['secret_key_help'] = array(
'#type' => 'item',
'#title' => t('Need a Secret Key?'),
'#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
);
return $form;
}
/**
* Submit the configuration form. Glue the url together and add the old password back if a new one was not specified.
*/
function edit_form_validate($form, &$form_state) {
$key = trim($form_state['values']['settings']['secret_key']);
if ($key) {
if (!preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $key)) {
form_set_error('secret_key', 'The secret key you entered is not the right format. Please make sure you copy it exactly.');
return;
}
$this->settings['secret_key'] = check_plain($key);
$limits = $this->check_limits();
if (!$limits) {
$err = xmlrpc_error();
if (!empty($err->code) && $err->code == '401') {
form_set_error('user', 'Could not login to server. Please check that your secret key is correct.');
}
else {
form_set_error('', 'There was an error retrieving the specified site. Please check that your secret key is correct.');
}
}
}
}
/**
* Submit the configuration form. Glue the url together and add the old password back if a new one was not specified.
*/
function edit_form_submit($form, &$form_state) {
$form_state['values']['secret_key'] = check_plain($form_state['values']['settings']['secret_key']);
parent::edit_form_submit($form, $form_state);
}
/**
* Get the destination id or warn the user that it has not been set.
*/
function _get_destination($warn = TRUE) {
list($id, $key) = $this->get_user_pass();
return $id;
}
/**
* Get the destination id or warn the user that it has not been set.
*/
function _get_private_key($warn = TRUE) {
list($id, $key) = $this->get_user_pass();
return $key;
}
/**
* Break the secret key into the public/private key (user/pass).
*/
function get_user_pass() {
$key = $this->settings('secret_key');
// The username is the first 32 chars.
$user = substr($key, 0, 32);
// The pass is the last 32 chars. There may be a separating character.
$pass = substr($key, strlen($key) - 32);
return array($user, $pass);
}
function get_display_location() {
return t('NodeSquirrel.com');
}
function add_scheme($url) {
return 'http://' . $url;
}
/**
* Get the form for the settings for this destination.
*/
function _xmlrpc($method, $args = array()) {
// Retrieve the severs or read them from a stored variable.
$servers = $this->_get_endpoints();
// Do the actual call.
return $this->__xmlrpc($method, $args, $servers);
}
/**
* Get the form for the settings for this destination.
*/
function __xmlrpc($method, $args, $servers, $retry = 3) {
if ($servers && --$retry > 0) {
// Add the key authentication arguments if we can.
if ($this->_sign_request($args)) {
$url = reset($servers);
// Try each available server in order.
while ($url) {
$url = $this->add_scheme($url);
$out = xmlrpc($url, array($method => $args));
// Check for errors.
$err = xmlrpc_error();
if ($err && $err->is_error) {
switch ($err->code) {
case '500':
case '503':
case '404':
// Some sort of server error. Try the next one.
$url = next($servers);
// If we're at the end of the line then try refetching the urls
if (!$url) {
$servers = $this->_get_endpoints(TRUE, $retry);
return $this->__xmlrpc($method, $args, $servers, $retry);
}
break;
case '300':
// 'Multiple Choices' means that the existing server list needs to be refreshed.
$servers = $this->_get_endpoints(TRUE, $retry);
return $this->__xmlrpc($method, $args, $servers, $retry);
break;
case '401':
case '403':
// Authentication failed.
_backup_migrate_message('Couldn\'t log in to NodeSquirrel. The server error was: %err', array('%err' => $err->message), 'error');
return FALSE;
break;
default:
// Some sort of client error. Don't try the next server because it'll probably say the same thing.
_backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $err->message), 'error');
return FALSE;
break;
}
}
// No error, return the result.
else {
return $out;
}
}
}
}
}
/**
* Genrate a hash with a given secret key, timestamp and random value.
*/
function _get_hash($time, $nonce) {
if ($private_key = $this->_get_private_key()) {
$message = $time . ':' . $nonce . ':' . $private_key;
// Use HMAC-SHA1 to authenticate the call.
$hash = base64_encode(
pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x36), 64))) .
$message))))
);
return $hash;
}
_backup_migrate_message('You must enter a valid private key to use NodeSquirrel.', array(), 'error');
return FALSE;
}
/**
* Genrate a hash with a given secret key, timestamp and random value.
*/
function _sign_request(&$args) {
$nonce = md5(mt_rand());
$time = time();
$hash = $this->_get_hash($time, $nonce);
if ($hash) {
array_unshift($args, $nonce);
array_unshift($args, $time);
array_unshift($args, $hash);
return TRUE;
}
else {
return FALSE;
}
}
/**
* Retrieve the list of servers.
*/
function _get_endpoints($refresh = FALSE, $retry = 3) {
$servers = (array)variable_get('nodesquirrel_endpoint_urls', array());
// No servers saved or a force refreshr required.
if ($refresh || empty($servers)) {
$servers = array_unique(array_merge($servers, variable_get('nodesquirrel_default_endpoint_urls', array('api.nodesquirrel.com/services/xmlrpc'))));
// Call the get endpoints method but use the default or previous servers to avoid infinite loops.
$new_servers = $this->__xmlrpc('backups.getEndpoints', array($this->_get_destination(), 'xmlrpc'), $servers, $retry);
if ($new_servers) {
variable_set('nodesquirrel_endpoint_urls', $new_servers);
$servers = $new_servers;
}
}
return $servers;
}
/**
* Post a file via http.
*
* This looks a lot like a clone of drupal_http_request but it can post a large
* file without reading the whole file into memory.
*/
function _post_file($url, $method = 'GET', $params = array(), $file = NULL, $retry = 3) {
global $db_prefix;
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
$uri = parse_url($url);
if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}
if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}
switch ($uri['scheme']) {
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$host = $uri['host'] . ($port != 80 ? ':'. $port : '');
$fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
break;
case 'https':
// Note: Only works for PHP 4.3 compiled with OpenSSL.
$port = isset($uri['port']) ? $uri['port'] : 443;
$host = $uri['host'] . ($port != 443 ? ':'. $port : '');
$fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
break;
default:
$result->error = 'invalid schema '. $uri['scheme'];
$result->code = -1003;
return $result;
}
// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr);
// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// @see system_requirements()
variable_set('drupal_http_request_fails', TRUE);
return $result;
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?'. $uri['query'];
}
// Prepare the data payload.
$boundary = '---------------------------'. substr(md5(rand(0,32000)),0,10);
$data_footer = "\r\n--$boundary--\r\n";
$data_header = '';
foreach ($params as $key => $value) {
$data_header .="--$boundary\r\n";
$data_header .= "Content-Disposition: form-data; name=\"".$key."\"\r\n";
$data_header .= "\r\n".$value."\r\n";
$data_header .="--$boundary\r\n";
}
// Add the file header to the post payload.
$data_header .="--$boundary\r\n";
$data_header .= "Content-Disposition: form-data; name=\"file\"; filename=\"". $file->filename() ."\"\r\n";
$data_header .= "Content-Type: application/octet-stream;\r\n";
$data_header .= "\r\n";
// Calculate the content length.
$content_length = strlen($data_header . $data_footer) + filesize($file->filepath());
//file_get_contents($file->filepath()));
// Create HTTP request.
$defaults = array(
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the port to prevent from breaking rewrite rules checking the
// host that do not take into account the port number.
'Host' => "Host: $host",
'Content-type' => "Content-type: multipart/form-data, boundary=$boundary",
'User-Agent' => 'User-Agent: NodeSquirrel Client/1.x (+http://www.nodesquirrel.com) (Drupal '. VERSION .'; Backup and Migrate 2.x)',
'Content-Length' => 'Content-Length: '. $content_length
);
// If the server url has a user then attempt to use basic authentication
if (isset($uri['user'])) {
$defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
}
$request = $method .' '. $path ." HTTP/1.0\r\n";
$request .= implode("\r\n", $defaults);
$request .= "\r\n\r\n";
$result->request = $request;
// Write the headers and start of the headers
fwrite($fp, $request);
fwrite($fp, $data_header);
// Copy the file 512k at a time to prevent memory issues.
if ($fp_in = fopen($file->filepath(), 'rb')) {
while (!feof($fp_in)) {
fwrite($fp, fread($fp_in, 1024 * 512));
}
$success = TRUE;
}
@fclose($fp_in);
// Finish the write.
fwrite($fp, $data_footer);
// Fetch response.
$response = '';
while (!feof($fp) && $chunk = fread($fp, 1024)) {
$response .= $chunk;
}
fclose($fp);
// Parse response.
list($split, $result->data) = explode("\r\n\r\n", $response, 2);
$split = preg_split("/\r\n|\n|\r/", $split);
list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
$result->protocol = $protocol;
$result->status_message = $status_message;
$result->headers = array();
// Parse headers.
while ($line = trim(array_shift($split))) {
list($header, $value) = explode(':', $line, 2);
if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$header] .= ','. trim($value);
}
else {
$result->headers[$header] = trim($value);
}
}
$responses = array(
100 => 'Continue', 101 => 'Switching Protocols',
200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['Location'];
if ($retry) {
$result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
$result->redirect_code = $result->code;
}
$result->redirect_url = $location;
break;
default:
$result->error = $status_message;
}
$result->code = $code;
return $result;
}
}

View File

@@ -0,0 +1,185 @@
<?php
/**
* @file
* Functions to handle the s3 backup destination.
*/
/**
* A destination for sending database backups to an s3 server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_destination_s3 extends backup_migrate_destination_remote {
var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
var $s3 = NULL;
var $cache_files = TRUE;
/**
* Save to to the s3 destination.
*/
function _save_file($file, $settings) {
if ($s3 = $this->s3_object()) {
$path = $file->filename();
if ($s3->putObject($s3->inputFile($file->filepath(), FALSE), $this->get_bucket(), $this->remote_path($file->filename()), S3::ACL_PRIVATE)) {
return $file;
}
}
return FALSE;
}
/**
* Load from the s3 destination.
*/
function load_file($file_id) {
backup_migrate_include('files');
$file = new backup_file(array('filename' => $file_id));
if ($s3 = $this->s3_object()) {
$data = $s3->getObject($this->get_bucket(), $this->remote_path($file_id), $file->filepath());
if (!$data->error) {
return $file;
}
}
return NULL;
}
/**
* Delete from the s3 destination.
*/
function _delete_file($file_id) {
if ($s3 = $this->s3_object()) {
$s3->deleteObject($this->get_bucket(), $this->remote_path($file_id));
}
}
/**
* List all files from the s3 destination.
*/
function _list_files() {
backup_migrate_include('files');
$files = array();
if ($s3 = $this->s3_object()) {
$s3_files = $s3->getBucket($this->get_bucket(), $this->get_subdir());
foreach ((array)$s3_files as $id => $file) {
$info = array(
'filename' => $this->local_path($file['name']),
'filesize' => $file['size'],
'filetime' => $file['time'],
);
$files[$info['filename']] = new backup_file($info);
}
}
return $files;
}
/**
* Get the form for the settings for this filter.
*/
function edit_form() {
// Check for the library.
$this->s3_object();
$form = parent::edit_form();
$form['scheme']['#type'] = 'value';
$form['scheme']['#value'] = 'https';
$form['host']['#default_value'] = 's3.amazonaws.com';
$form['path']['#title'] = 'S3 Bucket';
$form['path']['#default_value'] = $this->get_bucket();
$form['path']['#description'] = 'This bucket must already exist. It will not be created for you.';
$form['user']['#title'] = 'Access Key ID';
$form['pass']['#title'] = 'Secret Access Key';
$form['subdir'] = array(
'#type' => 'textfield',
'#title' => t('Subdirectory'),
'#default_value' => $this->get_subdir(),
'#weight' => 25
);
$form['settings']['#weight'] = 50;
return $form;
}
/**
* Submit the form for the settings for the s3 destination.
*/
function edit_form_submit($form, &$form_state) {
// Append the subdir onto the path.
if (!empty($form_state['values']['subdir'])) {
$form_state['values']['path'] .= '/'. trim($form_state['values']['subdir'], '/');
}
parent::edit_form_submit($form, $form_state);
}
/**
* Generate a filepath with the correct prefix.
*/
function remote_path($path) {
if ($subdir = $this->get_subdir()) {
$path = $subdir .'/'. $path;
}
return $path;
}
/**
* Generate a filepath with the correct prefix.
*/
function local_path($path) {
if ($subdir = $this->get_subdir()) {
$path = str_replace($subdir .'/', '', $path);
}
return $path;
}
/**
* Get the bucket which is the first part of the path.
*/
function get_bucket() {
$parts = explode('/', @$this->dest_url['path']);
return $parts[0];
}
/**
* Get the bucket which is the first part of the path.
*/
function get_subdir() {
// Support the older style of subdir saving.
if ($subdir = $this->settings('subdir')) {
return $subdir;
}
$parts = explode('/', @$this->dest_url['path']);
array_shift($parts);
return implode('/', array_filter($parts));
}
function s3_object() {
// Try to use libraries module if available to find the path.
if (function_exists('libraries_get_path')) {
$library_paths[] = libraries_get_path('s3-php5-curl');
}
else {
$library_paths[] = 'sites/all/libraries/s3-php5-curl';
}
$library_paths[] = drupal_get_path('module', 'backup_migrate') . '/includes/s3-php5-curl';
$library_paths[] = drupal_get_path('module', 'backup_migrate') . '/includes';
foreach($library_paths as $path) {
if (file_exists($path . '/S3.php')) {
require_once $path . '/S3.php';
if (!$this->s3 && !empty($this->dest_url['user'])) {
$this->s3 = new S3($this->dest_url['user'], $this->dest_url['pass'], FALSE, $this->dest_url['host']);
}
return $this->s3;
}
}
drupal_set_message(t('To back up to S3 you must download version 0.4 of the PHP S3 library from !link. Extract the S3.php file and add it the directory %dir.',
array('!link' => l('http://undesigned.org.za/2007/10/22/amazon-s3-php-class', 'http://undesigned.org.za/2007/10/22/amazon-s3-php-class'), '%dir' => 'sites/all/libraries/s3-php5-curl')), 'error', FALSE);
return NULL;
}
}

View File

@@ -0,0 +1,457 @@
<?php
/**
* @file
* General file handling code for Backup and Migrate.
*/
define('BACKUP_MIGRATE_FILENAME_MAXLENGTH', 255);
/**
* Add a file to the temporary files list for deletion when we're done.
*/
function backup_migrate_temp_files_add($filepath = NULL) {
static $files = array();
if (!$filepath) {
return $files;
}
else {
$files[] = $filepath;
}
}
/**
* Delete all temporary files.
*/
function _backup_migrate_temp_files_delete() {
// Delete the temp files created during this run.
foreach (backup_migrate_temp_files_add() as $file) {
$file = drupal_realpath($file);
if (file_exists($file) && is_writable($file)) {
unlink($file);
}
}
// Delete temp files abandoned for 6 or more hours.
$dir = file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath();
$expire = time() - variable_get('backup_migrate_cleanup_time', 21600);
if (file_exists($dir) && is_dir($dir) && is_readable($dir) && $handle = opendir($dir)) {
while (FALSE !== ($file = @readdir($handle))) {
// Delete 'backup_migrate_' files in the temp directory that are older than the expire time.
// We should only attempt to delete writable files to prevent errors in shared environments.
// This could still cause issues in shared environments with poorly configured file permissions.
if (strpos($file, 'backup_migrate_') === 0 && is_writable("$dir/$file") && @filectime("$dir/$file") < $expire) {
unlink("$dir/$file");
}
}
closedir($handle);
}
}
/**
* Return a list of backup filetypes.
*/
function _backup_migrate_filetypes() {
backup_migrate_include('filters');
$out = backup_migrate_filters_file_types();
foreach ($out as $key => $info) {
$out[$key]['id'] = empty($info['id']) ? $key : $info['id'];
}
return $out;
}
/**
* Adjust the length of a filename to allow for a string to be appended,
* staying within the maximum filename limit.
*/
function _backup_migrate_filename_append_prepare($filename, $append_str) {
$max_name_len = BACKUP_MIGRATE_FILENAME_MAXLENGTH - drupal_strlen($append_str);
if (drupal_strlen($filename) > $max_name_len) {
$filename = drupal_substr($filename, 0, $max_name_len);
}
return $filename;
}
/**
* Construct a filename using token and some cleaning.
*/
function _backup_migrate_construct_filename($filename, $timestamp='') {
if (module_exists('token')) {
$filename = token_replace($filename);
}
$filename = preg_replace("/[^a-zA-Z0-9\.\-_]/", "", $filename);
$filename = _backup_migrate_filename_append_prepare($filename, $timestamp);
$filename .= '-' . $timestamp;
$filename = trim($filename, '-');
if (drupal_strlen($filename) == 0) {
$filename = 'untitled';
}
return $filename;
}
/**
* Construct a default filename using the site's name.
*/
function _backup_migrate_default_filename() {
if (module_exists('token')) {
return '[site:name]';
}
else {
// Cleaning the string isn't strictly necessary but it looks better in the settings field.
return variable_get('site_name', 'backup_migrate');
}
}
/**
* An output buffer callback which simply throws away the buffer instead of sending it to the browser.
*/
function _backup_migrate_file_dispose_buffer($buffer) {
return "";
}
/**
* A backup file which allows for saving to and reading from the server.
*/
class backup_file {
var $file_info = array();
var $type = array();
var $ext = array();
var $path = "";
var $name = "";
var $handle = NULL;
/**
* Construct a file object given a file path, or create a temp file for writing.
*/
function backup_file($params = array()) {
if (isset($params['filepath']) && file_exists($params['filepath'])) {
$this->set_filepath($params['filepath']);
}
else {
$this->set_file_info($params);
$this->temporary_file();
}
}
/**
* Get the file_id if the file has been saved to a destination.
*/
function file_id() {
// The default file_id is the filename. Destinations can override the file_id if needed.
return isset($this->file_info['file_id']) ? $this->file_info['file_id'] : $this->filename();
}
/**
* Get the current filepath.
*/
function filepath() {
return drupal_realpath($this->path);
}
/**
* Get the final filename.
*/
function filename($name = NULL) {
if ($name) {
$this->name = $name;
}
return $this->name .'.'. $this->extension();
}
/**
* Set the current filepath.
*/
function set_filepath($path) {
$this->path = $path;
$params = array(
'filename' => basename($path),
);
if (file_exists($path)) {
$params['filesize'] = filesize($path);
$params['filetime'] = filemtime($path);
}
$this->set_file_info($params);
}
/**
* Get one or all pieces of info for the file.
*/
function info($key = NULL) {
if ($key) {
return @$this->file_info[$key];
}
return $this->file_info;
}
/**
* Get the file extension.
*/
function extension() {
return implode(".", $this->ext);
}
/**
* Get the file type.
*/
function type() {
return $this->type;
}
/**
* Get the file mimetype.
*/
function mimetype() {
return @$this->type['filemime'] ? $this->type['filemime'] : 'application/octet-stream';
}
/**
* Get the file mimetype.
*/
function type_id() {
return @$this->type['id'];
}
/**
* Can this file be used to backup to.
*/
function can_backup() {
return @$this->type['backup'];
}
/**
* Can this file be used to restore to.
*/
function can_restore() {
return @$this->type['restore'];
}
/**
* Can this file be used to restore to.
*/
function is_recognized_type() {
return @$this->type['restore'] || @$this->type['backup'];
}
/**
* Open a file for reading or writing.
*/
function open($write = FALSE, $binary = FALSE) {
if (!$this->handle) {
$path = $this->filepath();
// Check if the file can be read/written.
if ($write && ((file_exists($path) && !is_writable($path)) || !is_writable(dirname($path)))) {
_backup_migrate_message('The file %path cannot be written to.', array('%path' => $path), 'error');
return FALSE;
}
if (!$write && !is_readable($path)) {
_backup_migrate_message('The file %path cannot be read.', array('%path' => $path), 'error');
return FALSE;
}
// Open the file.
$mode = ($write ? "w" : "r") . ($binary ? "b" : "");
$this->handle = fopen($path, $mode);
return $this->handle;
}
return NULL;
}
/**
* Close a file when we're done reading/writing.
*/
function close() {
fclose($this->handle);
$this->handle = NULL;
}
/**
* Write a line to the file.
*/
function write($data) {
if (!$this->handle) {
$this->handle = $this->open(TRUE);
}
if ($this->handle) {
fwrite($this->handle, $data);
}
}
/**
* Read a line from the file.
*/
function read($size = NULL) {
if (!$this->handle) {
$this->handle = $this->open();
}
if ($this->handle && !feof($this->handle)) {
return $size ? fread($this->handle, $size) : fgets($this->handle);
}
return NULL;
}
/**
* Write data to the file.
*/
function put_contents($data) {
file_put_contents($this->filepath(), $data);
}
/**
* Read data from the file.
*/
function get_contents() {
return file_get_contents($this->filepath());
}
/**
* Transfer file using http to client. Similar to the built in file_transfer,
* but it calls module_invoke_all('exit') so that temp files can be deleted.
*/
function transfer() {
$headers = array(
array('key' => 'Content-Type', 'value' => $this->mimetype()),
array('key' => 'Content-Disposition', 'value' => 'attachment; filename="'. $this->filename() .'"'),
);
// In some circumstances, web-servers will double compress gzipped files.
// This may help aleviate that issue by disabling mod-deflate.
if ($this->mimetype() == 'application/x-gzip') {
$headers[] = 'Content-Encoding: gzip';
}
if ($size = $this->info('filesize')) {
$headers[] = array('key' => 'Content-Length', 'value' => $size);
}
// Suppress the warning you get when the buffer is empty.
@ob_end_clean();
if ($this->open(FALSE, TRUE)) {
foreach ($headers as $header) {
// To prevent HTTP header injection, we delete new lines that are
// not followed by a space or a tab.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
$header['value'] = preg_replace('/\r?\n(?!\t| )/', '', $header['value']);
drupal_add_http_header($header['key'], $header['value']);
}
// Transfer file in 1024 byte chunks to save memory usage.
while ($data = $this->read(1024)) {
print $data;
}
$this->close();
// Ask devel.module not to print it's footer.
$GLOBALS['devel_shutdown'] = FALSE;
}
else {
drupal_not_found();
}
// Start buffering and throw away the results so that errors don't get appended to the file.
ob_start('_backup_migrate_file_dispose_buffer');
backup_migrate_cleanup();
module_invoke_all('exit');
exit();
}
/**
* Push a file extension onto the file and return the previous file path.
*/
function push_type($extension) {
$types = _backup_migrate_filetypes();
if ($type = @$types[$extension]) {
$this->push_filetype($type);
}
$out = $this->filepath();
$this->temporary_file();
return $out;
}
/**
* Push a file extension onto the file and return the previous file path.
*/
function pop_type() {
$out = new backup_file(array('filepath' => $this->filepath()));
$this->pop_filetype();
$this->temporary_file();
return $out;
}
/**
* Set the current file type.
*/
function set_filetype($type) {
$this->type = $type;
$this->ext = array($type['extension']);
}
/**
* Set the current file type.
*/
function push_filetype($type) {
$this->ext[] = $type['extension'];
$this->type = $type;
}
/**
* Pop the current file type.
*/
function pop_filetype() {
array_pop($this->ext);
$this->detect_filetype_from_extension();
}
/**
* Set the file info.
*/
function set_file_info($file_info) {
$this->file_info = $file_info;
$this->ext = explode('.', @$this->file_info['filename']);
// Remove the underscores added to file extensions by Drupal's upload security.
foreach ($this->ext as $key => $val) {
$this->ext[$key] = trim($val, '_');
}
$this->filename(array_shift($this->ext));
$this->detect_filetype_from_extension();
}
/**
* Get the filetype info of the given file, or false if the file is not a valid type.
*/
function detect_filetype_from_extension() {
$ext = end($this->ext);
$this->type = array();
$types = _backup_migrate_filetypes();
foreach ($types as $key => $type) {
if (trim($ext, "_0123456789") === $type['extension']) {
$this->type = $type;
$this->type['id'] = $key;
}
}
}
/**
* Get a temporary file name with path.
*/
function temporary_file() {
$file = drupal_tempnam('temporary://', 'backup_migrate_');
// Add the version without the extension. The tempnam function creates this for us.
backup_migrate_temp_files_add($file);
if ($this->extension()) {
$file .= '.'. $this->extension();
// Add the version with the extension. This is the one we will actually use.
backup_migrate_temp_files_add($file);
}
$this->path = $file;
}
}

View File

@@ -0,0 +1,169 @@
<?php
/**
* @file
* This filter performs tha actual backup or restore operation. Not technically a filter per-se, but it does need to fit in the call chain.
*/
/**
* A filter backup or migrate the specified source.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_backup_restore extends backup_migrate_filter {
var $op_weights = array('backup' => 0, 'restore' => 0);
/**
* Get the default destinations for this filter.
*/
function destinations() {
$out = array();
foreach ($this->_get_destination_types() as $destination) {
if (method_exists($destination, 'destinations')) {
$out += $destination->destinations();
}
}
return $out;
}
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
backup_migrate_include('destinations');
$out = array();
foreach (backup_migrate_get_destinations('source') as $destination) {
$out['destinations'][$destination->get_id()] = $destination->backup_settings_default();
}
return $out;
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form_validate($form, &$form_state) {
foreach ($this->_get_destination_types() as $destination) {
$destination->backup_settings_form_validate($form, $form_state);
}
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function backup_settings_form_submit($form, &$form_state) {
foreach ($this->_get_destination_types() as $destination) {
$destination->backup_settings_form_submit($form, $form_state);
}
}
/**
* Get the default restore settings for this filter.
*/
function restore_settings_default() {
$out = array();
foreach ($this->_get_destination_types() as $destination) {
$out += $destination->restore_settings_default();
}
return $out;
}
/**
* Get the form for the backup settings for this filter.
*/
function backup_settings_form($settings) {
backup_migrate_include('destinations');
$out = array('destinations' => array(
'#tree' => TRUE,
));
foreach (backup_migrate_get_destinations('source') as $destination) {
$destination_settings = (array)(@$settings['destinations'][$destination->get_id()]) + $settings;
if ($form = $destination->backup_settings_form($destination_settings)) {
$out['destinations'][$destination->get_id()] = array(
'#type' => 'fieldset',
'#title' => t('!name Backup Options', array('!name' => $destination->get('name'))),
"#collapsible" => TRUE,
"#collapsed" => TRUE,
'#tree' => TRUE,
'#parents' => array('filters', 'destinations', $destination->get_id()),
) + $form;
}
}
return $out;
}
/**
* Get the form for the restore settings for this filter.
*/
function restore_settings_form($settings) {
$form = array();
foreach ($this->_get_destination_types() as $destination) {
$destination->restore_settings_form($form, $settings);
}
return $form;
}
/**
* Get the file types supported by this destination.
*/
function file_types() {
$types = array();
foreach ($this->_get_destination_types() as $destination) {
$types += $destination->file_types();
}
return $types;
}
/**
* Backup the data from the source specified in the settings.
*/
function backup($file, &$settings) {
if ($source = $settings->get_source()) {
if (!empty($settings->filters['destinations'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['destinations'][$source->get_id()]) + $settings->filters;
}
$file = $source->backup_to_file($file, $settings);
return $file;
}
backup_migrate_backup_fail("Could not run backup because the source '%source' is missing.", array('%source' => $settings->source_id), $settings);
return FALSE;
}
/**
* Restore the data from to source specified in the settings.
*/
function restore($file, &$settings) {
if ($source = $settings->get_source()) {
if (!empty($settings->filters['destinations'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['destinations'][$source->get_id()]) + $settings->filters;
}
$num = $source->restore_from_file($file, $settings);
return $num ? $file : FALSE;
}
backup_migrate_restore_fail("Could not run restore because the source '%source' is missing.", array('%source' => $settings->source_id), $settings);
return FALSE;
}
/**
* Get a list of dummy destinations representing each of the available destination types.
*/
function _get_destination_types() {
backup_migrate_include('destinations');
static $destinations = NULL;
if (!is_array($destinations)) {
$destinations = array();
$types = backup_migrate_get_destination_types();
// If no (valid) node type has been provided, display a node type overview.
foreach ($types as $key => $type) {
// Include the necessary file if specified by the type.
if (!empty($type['file'])) {
require_once './'. $type['file'];
}
$destinations[] = new $type['class'](array());
}
}
return $destinations;
}
}

View File

@@ -0,0 +1,289 @@
<?php
/**
* @file
* A filter for compressing backups with Zip, gzip, and bzip2.
*/
/**
* A filter for compressing backup files.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_compression extends backup_migrate_filter {
var $op_weights = array('backup' => 100, 'restore' => -100);
/**
* This function is called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
return $this->_backup_migrate_file_compress($file, $settings);
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, &$settings) {
return $this->_backup_migrate_file_decompress($file);
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_default() {
$options = $this->_backup_migrate_get_compression_form_item_options();
return array('compression' => isset($options['gzip']) ? 'gzip' : 'none');
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
$form = array();
$compression_options = $this->_backup_migrate_get_compression_form_item_options();
$form['file']['compression'] = array(
"#type" => count($compression_options) > 1 ? "select" : 'value',
"#title" => t("Compression"),
"#options" => $compression_options,
"#default_value" => $settings['compression'],
);
return $form;
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
return array(
"gzip" => array(
"extension" => "gz",
"filemime" => "application/x-gzip",
"backup" => TRUE,
"restore" => TRUE,
),
"bzip" => array(
"extension" => "bz",
"filemime" => "application/x-bzip",
"backup" => TRUE,
"restore" => TRUE,
),
"bzip2" => array(
"extension" => "bz2",
"filemime" => "application/x-bzip",
"backup" => TRUE,
"restore" => TRUE,
),
"zip" => array(
"extension" => "zip",
"filemime" => "application/zip",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Get the compression options as an options array for a form item.
*/
function _backup_migrate_get_compression_form_item_options() {
$compression_options = array("none" => t("No Compression"));
if (@function_exists("gzencode")) {
$compression_options['gzip'] = t("gzip");
}
if (@function_exists("bzcompress")) {
$compression_options['bzip'] = t("bzip2");
}
if (class_exists('ZipArchive')) {
$compression_options['zip'] = t("Zip", array(), array('context' => 'compression format'));
}
return $compression_options;
}
/**
* Encode a file with gzip.
*/
function _backup_migrate_gzip_encode($source, $dest, $level = 9) {
$success = FALSE;
if (@function_exists("gzopen")) {
if (($fp_out = gzopen($dest, 'wb'. $level)) && ($fp_in = fopen($source, 'rb'))) {
while (!feof($fp_in)) {
gzwrite($fp_out, fread($fp_in, 1024 * 512));
}
$success = TRUE;
}
@fclose($fp_in);
@gzclose($fp_out);
}
return $success;
}
/**
* Decode a file with gzip.
*/
function _backup_migrate_gzip_decode($source, $dest) {
$success = FALSE;
if (@function_exists("gzopen")) {
if (($fp_out = fopen($dest, 'wb')) && ($fp_in = gzopen($source, 'rb'))) {
while (!feof($fp_in)) {
fwrite($fp_out, gzread($fp_in, 1024 * 512));
}
$success = TRUE;
}
@gzclose($fp_in);
@fclose($fp_out);
}
return $success;
}
/**
* Encode a file with bzip2.
*/
function _backup_migrate_bzip_encode($source, $dest) {
$success = FALSE;
if (@function_exists("bzopen")) {
if (($fp_out = bzopen($dest, 'w')) && ($fp_in = fopen($source, 'rb'))) {
while (!feof($fp_in)) {
bzwrite($fp_out, fread($fp_in, 1024 * 512));
}
$success = TRUE;
}
else {
$error = TRUE;
}
@fclose($fp_in);
@bzclose($fp_out);
}
return $success;
}
/**
* Decode a file with bzip2.
*/
function _backup_migrate_bzip_decode($source, $dest) {
$success = FALSE;
if (@function_exists("bzopen")) {
if (($fp_out = fopen($dest, 'w')) && ($fp_in = bzopen($source, 'r'))) {
while (!feof($fp_in)) {
fwrite($fp_out, gzread($fp_in, 1024 * 512));
}
$success = TRUE;
}
else {
$error = TRUE;
}
@bzclose($fp_in);
@fclose($fp_out);
}
return $success;
}
/**
* Encode a file with Zip.
*/
function _backup_migrate_zip_encode($source, $dest, $filename) {
$success = FALSE;
if (class_exists('ZipArchive')) {
$zip = new ZipArchive;
$res = $zip->open($dest, constant("ZipArchive::CREATE"));
if ($res === TRUE) {
$zip->addFile($source, $filename);
$success = $zip->close();
}
}
return $success;
}
/**
* Decode a file with Zip.
*/
function _backup_migrate_zip_decode($source, $dest) {
$success = FALSE;
if (class_exists('ZipArchive')) {
$zip = new ZipArchive;
if (($fp_out = fopen($dest, "w")) && ($zip->open($source))) {
$filename = ($zip->getNameIndex(0));
if ($fp_in = $zip->getStream($filename)) {
while (!feof($fp_in)) {
fwrite($fp_out, fread($fp_in, 1024 * 512));
}
$success = TRUE;
}
}
@fclose($fp_in);
@fclose($fp_out);
}
return $success;
}
/**
* Compress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function _backup_migrate_file_compress($file, $settings) {
switch ($settings->filters['compression']) {
case "gzip":
$from = $file->push_type('gzip');
if (!$success = $this->_backup_migrate_gzip_encode($from, $file->filepath(), 9)) {
$file = NULL;
}
break;
case "bzip":
$from = $file->push_type('bzip2');
if (!$success = $this->_backup_migrate_bzip_encode($from, $file->filepath())) {
$file = NULL;
}
break;
case "zip":
$filename = $file->filename();
$from = $file->push_type('zip');
if (!$success = $this->_backup_migrate_zip_encode($from, $file->filepath(), $filename)) {
$file = NULL;
}
break;
}
if (!$file) {
_backup_migrate_message("Could not compress backup file. Try backing up without compression.", array(), 'error');
}
return $file;
}
/**
* Decompress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function _backup_migrate_file_decompress($file) {
$success = FALSE;
switch ($file->type_id()) {
case "gzip":
$from = $file->pop_type();
$success = $this->_backup_migrate_gzip_decode($from->filepath(), $file->filepath());
break;
case "bzip":
case "bzip2":
$from = $file->pop_type();
$success = $this->_backup_migrate_bzip_decode($from->filepath(), $file->filepath());
break;
case "zip":
$from = $file->pop_type();
$success = $this->_backup_migrate_zip_decode($from->filepath(), $file->filepath());
break;
default:
return $file;
break;
}
if (!$success) {
_backup_migrate_message("Could not decompress backup file. Please check that the file is valid.", array(), 'error');
}
return $success ? $file : NULL;
}
}

View File

@@ -0,0 +1,177 @@
<?php
/**
* @file
* A filter for encrypting bckups with AES.
*/
/**
* A filter for encrypting backup files.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_encryption extends backup_migrate_filter {
var $op_weights = array('backup' => 170, 'restore' => -170);
/**
* This function is called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
return $this->file_encrypt($file, $settings);
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, &$settings) {
return $this->file_decrypt($file);
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_default() {
return array('encryption' => 'none');
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
$form = array();
$options = $this->_backup_migrate_get_encryption_form_item_options();
if (count($options) > 1) {
$form['file']['encryption'] = array(
"#type" => "select",
"#title" => t("File Encryption (EXPERIMENTAL)"),
"#options" => $options,
"#default_value" => @$settings['encryption'],
'#description' => t('Encrypted files can only be restored by Backup and Migrate and only on sites with the same encryption key. <strong>This functionality is experimental, and should only be used for testing.</strong>'),
);
}
else {
$form['file']['encryption'] = array(
"#type" => 'item',
"#title" => t("File Encryption"),
"#markup" => t('Install the !link to enable backup file encryption.', array('!link' => l(t('AES Encryption Module'), 'http://drupal.org/project/aes'))),
);
}
return $form;
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
return array(
"aes" => array(
"extension" => "aes",
"filemime" => "application/octet-stream",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Get the compression options as an options array for a form item.
*/
function _backup_migrate_get_encryption_form_item_options() {
$options = array();
$options = array('' => t('No Encryption'));
if (@function_exists("aes_encrypt")) {
$options['aes'] = t("AES Encryption");
}
return $options;
}
/**
* AES encrypt a file.
*/
function aes_encrypt($source, $dest) {
$success = FALSE;
if (function_exists('aes_encrypt')) {
if ($data = $source->get_contents()) {
// Add a marker to the end of the data so we can trim the padding on decrpypt.
$data = pack("a*H2", $data, "80");
if ($data = aes_encrypt($data, FALSE)) {
$dest->put_contents($data);
$success = TRUE;
}
}
}
return $success;
}
/**
* Gzip decode a file.
*/
function aes_decrypt($source, $dest) {
$success = FALSE;
if (function_exists('aes_decrypt')) {
if ($data = $source->get_contents()) {
if ($data = aes_decrypt($data, FALSE)) {
// Trim all the padding zeros plus our non-zero marker.
$data = substr(rtrim($data, "\0"), 0, -1);
$dest->put_contents($data);
$success = TRUE;
}
}
}
return $success;
}
/**
* Compress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function file_encrypt($file, $settings) {
if (!empty($settings->filters['encryption'])) {
switch ($settings->filters['encryption']) {
case "aes":
$from = $file->push_type('aes');
$from = new backup_file(array('filepath' => $from));
if (!$success = $this->aes_encrypt($from, $file)) {
$file = NULL;
}
break;
}
if (!$file) {
_backup_migrate_message("Could not encrypt backup file. Try backing up without encryption.", array(), 'error');
}
}
return $file;
}
/**
* Decompress a file with the given settings.
* Also updates settings to reflect new file mime and file extension.
*/
function file_decrypt($file) {
$success = FALSE;
if ($file) {
switch ($file->type_id()) {
case "aes":
$from = $file->pop_type();
$success = $this->aes_decrypt($from, $file);
break;
default:
return $file;
break;
}
if (!$success) {
if (function_exists('aes_decrypt')) {
_backup_migrate_message("Could not decrpyt backup file. Please check that the file is valid and that the encryption key of the server matches the server that created the backup.", array(), 'error');
}
else {
_backup_migrate_message('You must install the !link to restore encrypted backkups.', array('!link' => l(t('AES Encryption Module'), 'http://drupal.org/project/aes')), 'error');
}
}
}
return $success ? $file : NULL;
}
}

View File

@@ -0,0 +1,290 @@
<?php
/**
* @file
* All of the filter handling code needed for Backup and Migrate.
*/
/**
* Get the available destination types.
*/
function backup_migrate_get_filters($op = NULL) {
static $filters = NULL;
if ($filters === NULL) {
$filters = array();
$definitions = module_invoke_all('backup_migrate_filters');
foreach ($definitions as $definition) {
// Include the necessary file if specified by the filter.
if (!empty($definition['file'])) {
require_once './'. $definition['file'];
}
$filters[] = new $definition['class'];
}
}
$sort = array();
// Sort the filters based on the weight for the given operation.
foreach ($filters as $filter) {
$sort[] = $filter->weight($op);
}
array_multisort($sort, SORT_ASC, SORT_NUMERIC, $filters);
return $filters;
}
/**
* Implementation of hook_backup_migrate_filters().
*
* Get the built in Backup and Migrate filters.
*/
function backup_migrate_backup_migrate_filters() {
return array(
'backup_restore' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.backup_restore.inc',
'class' => 'backup_migrate_filter_backup_restore',
),
'compression' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.compression.inc',
'class' => 'backup_migrate_filter_compression',
),
'encryption' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.encryption.inc',
'class' => 'backup_migrate_filter_encryption',
),
'statusnotify' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.statusnotify.inc',
'class' => 'backup_migrate_filter_statusnotify',
),
'utils' => array(
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/filters.utils.inc',
'class' => 'backup_migrate_filter_utils',
),
);
}
/**
* Invoke the given method on all of the available filters.
*/
function backup_migrate_filters_invoke_all() {
$args = func_get_args();
$op = array_shift($args);
$out = array();
$filters = backup_migrate_get_filters($op);
foreach ($filters as $filter) {
if (method_exists($filter, $op)) {
/* call_user_func_array() ignores the function signature, so we cannot
* use it to pass references. (Call-time pass-by-reference is deprecated
* in PHP5.3.) Work around it, since we have unknown function signatures.
*/
switch (count($args)) {
case 1:
$ret = $filter->$op($args[0]);
break;
case 2:
$ret = $filter->$op($args[0], $args[1]);
break;
default:
// This assumes that no functions with more than 2 arguments expect a
// reference as argument. If so, add another 'case block'.
$ret = call_user_func_array(array($filter, $op), $args);
}
$out = array_merge_recursive($out, (array) $ret);
}
}
return $out;
}
/**
* Filter a backup file before sending it to the destination.
*/
function backup_migrate_filters_backup($file, &$settings) {
$filters = backup_migrate_get_filters('backup');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->backup($file, $settings);
}
}
return $file;
}
/**
* Filter a backup file before sending it to the destination.
*/
function backup_migrate_filters_restore($file, &$settings) {
$filters = backup_migrate_get_filters('restore');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->restore($file, $settings);
}
}
return $file;
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_settings_form($settings, $op) {
$out = backup_migrate_filters_invoke_all($op .'_settings_form', $settings);
$out = backup_migrate_filters_settings_form_set_parents($out);
return $out;
}
/**
* Add a form parent to the filter settings so that the filter values are saved in the right table.
*/
function backup_migrate_filters_settings_form_set_parents($form) {
foreach (element_children($form) as $key) {
if (!isset($form[$key]['#parents'])) {
$form[$key]['#parents'] = array('filters', $key);
$form[$key] = backup_migrate_filters_settings_form_set_parents($form[$key]);
}
}
return $form;
}
/**
* Validate all the filters.
*/
function backup_migrate_filters_settings_form_validate($op, $form, &$form_state) {
//backup_migrate_filters_invoke_all($op .'_settings_form_validate', $form, $form_state);
}
/**
* Submit all of the filters.
*/
function backup_migrate_filters_settings_form_submit($op, $form, &$form_state) {
//backup_migrate_filters_invoke_all($op .'_settings_form_submit', $form, $form_state);
}
/**
* Get the default settings for the filters.
*/
function backup_migrate_filters_settings_default($op) {
return backup_migrate_filters_invoke_all($op .'_settings_default');
}
/**
* Get the file types for all of the filters.
*/
function backup_migrate_filters_file_types() {
return backup_migrate_filters_invoke_all('file_types');
}
/**
* A base class for basing filters on.
*/
class backup_migrate_filter {
var $weight = 0;
var $op_weights = array();
/**
* Get the weight of the filter for the given op.
*/
function weight($op = NULL) {
if ($op && isset($this->op_weights[$op])) {
return $this->op_weights[$op];
}
return $this->weight;
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form_validate($form, &$form_state) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function backup_settings_form_submit($form, &$form_state) {
return $form_state['values'];
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_default() {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_form($settings) {
return array();
}
/**
* Get the form for the settings for this filter.
*/
function restore_settings_form_validate($form, &$form_state) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function restore_settings_form_submit($form, &$form_state) {
return $form_state['values'];
}
/**
* Get a list of file types handled by this filter.
*/
function file_types() {
return array();
}
/**
* Declare any default destinations for this filter.
*/
function destinations() {
return array();
}
/**
* This function is called on a backup file after the backup has been completed.
*/
function backup($file, &$settings) {
return $file;
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, &$settings) {
return $file;
}
/**
* This function is called immediately prior to backup.
*/
function pre_backup($source, $file, $settings) {
}
/**
* This function is called immediately post backup.
*/
function post_backup($source, $file, $settings) {
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* @file
* A filter for compressing bckups with zip, gz bzip etc.
*/
/**
* A filter to send a notification email on success or failure of backup.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_statusnotify extends backup_migrate_filter {
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
return array(
'notify_success_enable' => FALSE,
'notify_failure_enable' => FALSE,
'notify_success_email' => variable_get('site_mail', ''),
'notify_failure_email' => variable_get('site_mail', ''),
);
}
/**
* Get the form for the settings for this filter.
*/
function backup_settings_form($settings) {
$form = array();
$form['advanced']['notify_success_enable'] = array(
"#type" => 'checkbox',
"#title" => t("Send an email if backup succeeds"),
"#default_value" => @$settings['notify_success_enable'],
);
$form['advanced']['notify_success_email'] = array(
"#type" => "textfield",
"#title" => t("Email Address for Success Notices"),
"#default_value" => @$settings['notify_success_email'],
);
$form['advanced']['notify_failure_enable'] = array(
"#type" => 'checkbox',
"#title" => t("Send an email if backup fails"),
"#default_value" => @$settings['notify_failure_enable'],
);
$form['advanced']['notify_failure_email'] = array(
"#type" => "textfield",
"#title" => t("Email Address for Failure Notices"),
"#default_value" => @$settings['notify_failure_email'],
);
return $form;
}
/**
* Send the success email.
*/
function backup_succeed($settings) {
if (@$settings->filters['notify_success_enable'] && $to = @$settings->filters['notify_success_email']) {
$params = array(
'messages' => $this->get_messages(),
);
// Using the default language since this is not specific to a user.
$language = language_default();
drupal_mail('backup_migrate', 'backup_succeed', $settings->filters['notify_success_email'], $language, $params);
}
}
/**
* Send the failure email.
*/
function backup_fail($settings) {
if (@$settings->filters['notify_failure_enable'] && $to = @$settings->filters['notify_failure_email']) {
$params = array(
'messages' => $this->get_messages(),
);
// Using the default language since this is not specific to a user.
$language = language_default();
drupal_mail('backup_migrate', 'backup_fail', $settings->filters['notify_failure_email'], $language, $params);
}
}
/**
* Render the messages and errors for the email.
*/
function get_messages() {
$out = "";
$messages = _backup_migrate_messages();
foreach ($messages as $message) {
$out .= strip_tags(t($message['message'], $message['replace'])) . "\n";
}
return $out;
}
}

View File

@@ -0,0 +1,189 @@
<?php
/**
* @file
* A filter to run some basic utility functions. Basically any useful option not big enough to justify it's own class.
*/
/**
* A filter to send a notification email on success or failure of backup.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_utils extends backup_migrate_filter {
var $saved_devel_query = NULL;
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
return array(
'utils_disable_query_log' => TRUE,
'utils_site_offline' => FALSE,
'utils_description' => '',
);
}
/**
* Get the default restore settings for this filter.
*/
function restore_settings_default() {
return array(
'utils_disable_query_log' => TRUE,
'utils_site_offline' => FALSE,
);
}
/**
* Get the form for the backup settings for this filter.
*/
function backup_settings_form($settings) {
$form = array();
if (module_exists('devel') && variable_get('dev_query', 0)) {
$form['database']['utils_disable_query_log'] = array(
'#type' => 'checkbox',
'#title' => t('Disable query log'),
'#default_value' => !empty($settings['utils_disable_query_log']) ? $settings['utils_disable_query_log'] : NULL,
'#description' => t('Disable the devel module\'s query logging during the backup operation. It will be enabled again after backup is complete. This is very highly recommended.'),
);
}
$form['advanced']['utils_site_offline'] = array(
'#type' => 'checkbox',
'#title' => t('Take site offline'),
'#default_value' => !empty($settings['utils_site_offline']) ? $settings['utils_site_offline'] : NULL,
'#description' => t('Take the site offline during backup and show a maintenance message. Site will be taken back online once the backup is complete.'),
);
$form['advanced']['utils_site_offline_message'] = array(
'#type' => 'textarea',
'#title' => t('Site off-line message'),
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.')
);
$form['advanced']['utils_description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => !empty($settings['utils_description']) ? $settings['utils_description'] : NULL,
'#description' => t('Add a short description to the backup file.'),
);
return $form;
}
/**
* Get the form for the restore settings for this filter.
*/
function restore_settings_form($settings) {
$form = array();
if (module_exists('devel') && variable_get('dev_query', 0)) {
$form['advanced']['utils_disable_query_log'] = array(
'#type' => 'checkbox',
'#title' => t('Disable query log'),
'#default_value' => @$settings['utils_disable_query_log'],
'#description' => t('Disable the devel module\'s query logging during the restore operation. It will be enabled again after restore is complete. This is very highly recommended.'),
);
}
$form['advanced']['utils_site_offline'] = array(
'#type' => 'checkbox',
'#title' => t('Take site offline'),
'#default_value' => !empty($settings['utils_site_offline']) ? $settings['utils_site_offline'] : NULL,
'#description' => t('Take the site offline during restore and show a maintenance message. Site will be taken back online once the restore is complete.'),
);
$form['advanced']['utils_site_offline_message'] = array(
'#type' => 'textarea',
'#title' => t('Site off-line message'),
'#default_value' => !empty($settings['utils_site_offline_message']) ? $settings['utils_site_offline_message'] : variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
'#description' => t('Message to show visitors when the site is in off-line mode.')
);
return $form;
}
function pre_backup($source, $file, $settings) {
$this->take_site_offline($settings);
$this->disable_devel_query($settings);
}
function post_backup($source, $file, $settings) {
$this->enable_devel_query($settings);
$this->take_site_online($settings);
$this->add_file_info($file, $settings);
}
function pre_restore($file, $settings) {
$this->disable_devel_query($settings);
$this->take_site_offline($settings);
}
function post_restore($file, $settings) {
$this->enable_devel_query($settings);
$this->take_site_online($settings);
}
/**
* Disable devel query logging if it's active and the user has chosen to do so.
*/
function disable_devel_query($settings) {
$this->saved_devel_query = variable_get('dev_query', 0);
if (module_exists('devel') && variable_get('dev_query', 0) && !empty($settings->filters['utils_disable_query_log'])) {
variable_set('dev_query', 0);
}
}
/**
* Restore devel query to previous state.
*/
function enable_devel_query($settings) {
if (module_exists('devel')) {
variable_set('dev_query', $this->saved_devel_query);
}
}
/**
* Add the backup metadata to the file.
*/
function add_file_info($file, $settings) {
$file->file_info['description'] = $settings->filters['utils_description'];
$file->file_info['datestamp'] = time();
$file->file_info['generator'] = 'Backup and Migrate (http://drupal.org/project/backup_migrate)';
$file->file_info['generatorversion'] = BACKUP_MIGRATE_VERSION;
$file->file_info['sites'] = array(
'0' => array(
'version' => VERSION,
'name' => variable_get('site_name', ''),
'url' => url('', array('absolute' => TRUE)),
),
);
}
/**
* Take the site offline if configured to do so.
*/
function take_site_offline($settings) {
// Save the current state of the site in case a restore overwrites it.
$this->saved_site_offline = variable_get('maintenance_mode', 0);
if (@$settings->filters['utils_site_offline']) {
$this->saved_site_offline_message = variable_get('maintenance_mode_message', NULL);
if (!empty($settings->filters['utils_site_offline_message'])) {
$this->saved_site_offline_message = variable_get('maintenance_mode_message', NULL);
variable_set('maintenance_mode_message', $settings->filters['utils_site_offline_message']);
}
variable_set('maintenance_mode', 1);
_backup_migrate_message('Site was taken offline.');
}
}
/**
* Take the site online again after backup or restore.
*/
function take_site_online($settings) {
// Take the site back off/online because the restored db may have changed that setting.
variable_set('maintenance_mode', $this->saved_site_offline);
if ($settings->filters['utils_site_offline']) {
if (!empty($this->saved_site_offline_message)) {
variable_set('maintenance_mode_message', $this->saved_site_offline_message);
}
_backup_migrate_message('Site was taken online.');
}
}
}

View File

@@ -0,0 +1,321 @@
<?php
/**
* @file
* All of the settings profiles handling code for Backup and Migrate.
*/
backup_migrate_include('crud');
/**
* Get all the available backup profiles.
*/
function backup_migrate_get_profiles() {
backup_migrate_include('filters');
static $profiles = NULL;
// Get the list of profiles and cache them locally.
if ($profiles === NULL) {
$profiles = backup_migrate_crud_get_items('profile');
}
return $profiles;
}
/**
* Implementation of hook_backup_migrate_profiles_alter().
*
* Add default settings for any plugins which didn't exist when the profile was saved.
*/
function backup_migrate_backup_migrate_profiles_alter(&$profiles) {
foreach ($profiles as $id => $profile) {
// Set the default values for filter setting which don't exist in the profile.
$profiles[$id]->filters = (array)@$profile->filters + (array)backup_migrate_filters_settings_default('backup');
}
}
/**
* Get the profile info for the profile with the given ID, or NULL if none exists.
*/
function backup_migrate_get_profile($profile_id) {
$profiles = backup_migrate_get_profiles();
return @$profiles[$profile_id];
}
/**
* Implementation of hook_backup_migrate_profiles().
*/
function backup_migrate_backup_migrate_profiles() {
$out = array();
// Get the module default profile.
$out['default'] = backup_migrate_crud_create_item('profile', array('name' => t("Default Settings"), 'profile_id' => 'default'));
return $out;
}
/* Utilities */
/**
* Get the available profiles as an options array for a form item.
*/
function _backup_migrate_get_profile_form_item_options() {
$out = array();
foreach ((array)backup_migrate_get_profiles() as $key => $profile) {
$out[$key] = $profile->get('name');
}
return $out;
}
/**
* Get a form to configure the profile.
*/
function _backup_migrate_ui_backup_settings_form($profile) {
drupal_add_js(array('backup_migrate' => array('checkboxLinkText' => t('View as checkboxes'))), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js', array('type' => 'file', 'scope' => 'footer'));
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
backup_migrate_include('files', 'destinations', 'filters');
$form = array();
$form['file'] = array(
"#type" => "fieldset",
"#title" => t("Backup File"),
"#collapsible" => TRUE,
"#collapsed" => FALSE,
"#tree" => FALSE,
);
$form['file']['filename'] = array(
"#type" => "textfield",
"#title" => t("Backup file name"),
"#default_value" => $profile->filename,
);
if (module_exists('token')) {
$form['file']['filename']['#description'] = t('You can use tokens in the file name.');
$form['file']['token_help'] = array(
'#title' => t('Replacement patterns'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['file']['token_help']['help'] = array(
'#theme' => 'token_tree',
'#token_types' => array('current-date', 'site'),
'#global_types' => FALSE,
);
}
$form['file']['append_timestamp'] = array(
"#type" => "checkbox",
"#title" => t("Append a timestamp."),
"#default_value" => $profile->append_timestamp,
);
$form['file']['timestamp_format'] = array(
"#type" => "textfield",
"#title" => t("Timestamp format"),
"#default_value" => $profile->timestamp_format,
"#description" => t('Should be a PHP <a href="!url">date()</a> format string.', array('!url' => 'http://www.php.net/date')),
);
$form['advanced'] = array('#weight' => 10);
$form = array_merge_recursive($form, backup_migrate_filters_settings_form($profile->filters, 'backup'));
// Add the advanced fieldset if there are any fields in it.
if ($form['advanced']) {
$form['advanced']['#type'] = 'fieldset';
$form['advanced']['#title'] = t('Advanced Options');
$form['advanced']['#collapsed'] = true;
$form['advanced']['#collapsible'] = true;
}
$form['#validate'][] = '_backup_migrate_ui_backup_settings_form_validate';
$form['#submit'][] = '_backup_migrate_ui_backup_settings_form_submit';
return $form;
}
/**
* Validate the profile form.
*/
function _backup_migrate_ui_backup_settings_form_validate($form, &$form_state) {
backup_migrate_filters_settings_form_validate('backup', $form, $form_state);
}
/**
* Submit the profile form.
*/
function _backup_migrate_ui_backup_settings_form_submit($form, &$form_state) {
backup_migrate_filters_settings_form_submit('backup', $form, $form_state);
}
/**
* Get the default profile.
*/
function _backup_migrate_profile_default_profile() {
backup_migrate_include('files', 'filters');
return array(
'source_id' => 'db',
'filename' => _backup_migrate_default_filename(),
'append_timestamp' => 1,
'timestamp_format' => 'Y-m-d\TH-i-s',
'filters' => backup_migrate_filters_settings_default('backup'),
);
}
/**
* Get the default profile saved by the user (or the module default if none exists).
*/
function _backup_migrate_profile_saved_default_profile($profile_id = NULL) {
$profile_id = $profile_id ? $profile_id : variable_get("backup_migrate_profile_id", 'default');
$profile = NULL;
if ($profile_id) {
$profile = backup_migrate_get_profile($profile_id);
}
if (!$profile) {
$profile = backup_migrate_get_profile('default');
}
return $profile;
}
/**
* A profile class for crud operations.
*/
class backup_migrate_profile extends backup_migrate_item {
var $db_table = "backup_migrate_profiles";
var $type_name = "profile";
var $singular = 'profile';
var $plural = 'profiles';
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
function strings() {
// Help the pot extractor find these strings.
t('Profile');
t('Profiles');
t('profile');
t('profiles');
}
/**
* Get the default values for standard parameters.
*/
function get_default_values() {
return _backup_migrate_profile_default_profile() + array('name' => t("Untitled Profile"));
}
/**
* Get a table of all items of this type.
*/
function get_list() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
return parent::get_list();
}
/**
* Get the columns needed to list the type.
*/
function get_list_column_info() {
$out = parent::get_list_column_info();
$out = array(
'name' => array('title' => t('Name')),
'source_name' => array('title' => t('Source')),
'filename' => array('title' => t('Filename')),
) + $out;
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
$row = parent::get_list_row();
if (empty($this->enabled)) {
foreach ($row as $key => $field) {
$row[$key] = array('data' => $field, 'class' => 'profile-list-disabled');
}
}
return $row;
}
/**
* Set the source of this setings profile. Takes either a source object or source id.
*/
function set_source($source) {
if (is_object($source)) {
$this->source = $source;
$this->source_id = $source->get_id();
}
else {
$this->source_id = $source;
unset($this->source);
}
}
/**
* Get the source of the profile.
*/
function get_source() {
backup_migrate_include('destinations');
if (!empty($this->source_id) && (empty($this->source) || $this->source->destination_id !== $this->source_id)) {
$this->source = backup_migrate_get_destination($this->source_id);
}
return empty($this->source) ? NULL : $this->source;
}
/**
* Get the name of the source.
*/
function get_source_name() {
if ($source = $this->get_source()) {
return $source->get_name();
}
return t("Missing");
}
/**
* Get the destination of the profile.
*/
function get_destination() {
backup_migrate_include('destinations');
if (!empty($this->destination_id) && (empty($this->destination) || $this->destination->destination_id !== $this->destination_id)) {
$this->destination = backup_migrate_get_destination($this->destination_id);
}
return empty($this->destination) ? NULL : $this->destination;
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
if ($destination = $this->get_destination()) {
return $destination->get_name();
}
return t("Missing");
}
/**
* Get the edit form.
*/
function edit_form() {
$form = parent::edit_form();
$form['name'] = array(
"#type" => "textfield",
"#title" => t("Profile Name"),
'#required' => TRUE,
"#default_value" => $this->get('name'),
);
$form += _backup_migrate_ui_backup_settings_form($this);
return $form;
}
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function delete_confirm_message() {
return t('Are you sure you want to delete the profile %name? Any schedules using this profile will be disabled.', array('%name' => $this->get('name')));
}
}

View File

@@ -0,0 +1,405 @@
<?php
/**
* @file
* All of the schedule handling code needed for Backup and Migrate.
*/
backup_migrate_include('crud');
/**
* Run the preconfigured schedules. Called on cron.
*/
function backup_migrate_schedules_run() {
backup_migrate_include('profiles');
foreach (backup_migrate_get_schedules() as $schedule) {
$schedule->cron();
}
backup_migrate_cleanup();
}
/**
* Get all the available backup schedules.
*/
function backup_migrate_get_schedules() {
static $schedules = NULL;
// Get the list of schedules and cache them locally.
if ($schedules === NULL) {
$schedules = backup_migrate_crud_get_items('schedule');
}
return $schedules;
}
/**
* Get the schedule info for the schedule with the given ID, or NULL if none exists.
*/
function backup_migrate_get_schedule($schedule_id) {
$schedules = backup_migrate_get_schedules();
return @$schedules[$schedule_id];
}
/**
* A schedule class for crud operations.
*/
class backup_migrate_schedule extends backup_migrate_item {
var $db_table = "backup_migrate_schedules";
var $type_name = 'schedule';
var $singular = 'schedule';
var $plural = 'schedules';
var $default_values = array();
/**
* This function is not supposed to be called. It is just here to help the po extractor out.
*/
function strings() {
// Help the pot extractor find these strings.
t('Schedule');
t('Schedules');
t('schedule');
t('schedules');
}
/**
* Get the default values for this item.
*/
function get_default_values() {
return array(
'name' => t("Untitled Schedule"),
'source_id' => 'db',
'enabled' => 1,
'keep' => 0,
'period' => 60 * 60 * 24,
'storage' => BACKUP_MIGRATE_STORAGE_NONE
);
}
/**
* Get the columns needed to list the type.
*/
function get_list_column_info() {
$out = parent::get_list_column_info();
$out = array(
'name' => array('title' => t('Name')),
'destination_name' => array('title' => t('Destination'), 'html' => TRUE),
'profile_name' => array('title' => t('Profile'), 'html' => TRUE),
'frequency_description' => array('title' => t('Frequency')),
'keep_description' => array('title' => t('Keep')),
'enabled_description' => array('title' => t('Enabled')),
'last_run_description' => array('title' => t('Last run')),
) + $out;
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
drupal_add_css(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.css');
$row = parent::get_list_row();
if (!$this->is_enabled()) {
foreach ($row as $key => $field) {
$row[$key] = array('data' => $field, 'class' => 'schedule-list-disabled');
}
}
return $row;
}
/**
* Is the schedule enabled and valid.
*/
function is_enabled() {
$destination = $this->get_destination();
$profile = $this->get_profile();
return (!empty($this->enabled) && !empty($destination) && !empty($profile));
}
/**
* Get the destination object of the schedule.
*/
function get_destination() {
backup_migrate_include('destinations');
return backup_migrate_get_destination($this->get('destination_id'));
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
if ($destination = $this->get_destination()) {
return check_plain($destination->get_name());
}
return '<div class="row-error">'. t("Missing") .'</div>';
}
/**
* Get the destination of the schedule.
*/
function get_profile() {
backup_migrate_include('profiles');
return backup_migrate_get_profile($this->get('profile_id'));
}
/**
* Get the name of the source.
*/
function get_profile_name() {
if ($profile = $this->get_profile()) {
return check_plain($profile->get_name());
}
return '<div class="row-error">'. t("Missing") .'</div>';
}
/**
* Format a frequency in human-readable form.
*/
function get_frequency_description() {
$period = $this->get_frequency_period();
$out = format_plural(($this->period / $period['seconds']), $period['singular'], $period['plural']);
return $out;
}
/**
* Format the number to keep in human-readable form.
*/
function get_keep_description() {
return !empty($this->keep) ? $this->keep : t('All');
}
/**
* Format the enabled status in human-readable form.
*/
function get_enabled_description() {
return !empty($this->enabled) ? t('Enabled') : t('Disabled');
}
/**
* Format the enabled status in human-readable form.
*/
function get_last_run_description() {
$last_run = $this->get('last_run');
return !empty($last_run) ? format_date($last_run, 'small') : t('Never');
}
/**
* Get the number of excluded tables.
*/
function get_exclude_tables_count() {
return count($this->exclude_tables) ? count($this->exclude_tables) : t("No tables excluded");
}
/**
* Get the number of excluded tables.
*/
function get_nodata_tables_count() {
return count($this->nodata_tables) ? count($this->nodata_tables) : t("No data omitted");
}
/**
* Get the edit form.
*/
function edit_form() {
$form = parent::edit_form();
backup_migrate_include('destinations', 'profiles');
$form['enabled'] = array(
"#type" => "checkbox",
"#title" => t("Enabled"),
"#default_value" => $this->get('enabled'),
);
$form['name'] = array(
"#type" => "textfield",
"#title" => t("Schedule Name"),
"#default_value" => $this->get('name'),
);
$form += _backup_migrate_get_source_form($this->get('source_id'));
$form['profile_id'] = array(
"#type" => "select",
"#title" => t("Settings Profile"),
"#options" => _backup_migrate_get_profile_form_item_options(),
"#default_value" => $this->get('profile_id'),
);
$form['profile_id']['#description'] = ' '. l(t("Create new profile"), BACKUP_MIGRATE_MENU_PATH . "/profile/add");
if (!$form['profile_id']['#options']) {
$form['profile_id']['#options'] = array('0' => t('-- None Available --'));
}
$period_options = array();
foreach ($this->frequency_periods() as $type => $period) {
$period_options[$type] = $period['title'];
}
$default_period = $this->get_frequency_period();
$default_period_num = $this->get('period') / $default_period['seconds'];
$form['period'] = array(
"#type" => "item",
"#title" => t("Backup every"),
"#prefix" => '<div class="container-inline">',
"#suffix" => '</div>',
"#tree" => TRUE,
);
$form['period']['number'] = array(
"#type" => "textfield",
"#size" => 6,
"#default_value" => $default_period_num,
);
$form['period']['type'] = array(
"#type" => "select",
"#options" => $period_options,
"#default_value" => $default_period['type'],
);
$form['keep'] = array(
"#type" => "textfield",
"#size" => 6,
"#title" => t("Number of Backup files to keep"),
"#description" => t("The number of backup files to keep before deleting old ones. Use 0 to never delete backups. <strong>Other files in the destination directory will get deleted if you specify a limit.</strong>"),
"#default_value" => $this->get('keep'),
);
$destination_options = _backup_migrate_get_destination_form_item_options('scheduled backup');
$form['destination_id'] = array(
"#type" => "select",
"#title" => t("Destination"),
"#description" => t("Choose where the backup file will be saved. Backup files contain sensitive data, so be careful where you save them."),
"#options" => $destination_options,
"#default_value" => $this->get('destination_id'),
);
$form['destination_id']['#description'] .= ' '. l(t("Create new destination"), BACKUP_MIGRATE_MENU_PATH . "/destination/add");
return $form;
}
/**
* Submit the edit form.
*/
function edit_form_validate($form, &$form_state) {
if (!is_numeric($form_state['values']['period']['number']) || $form_state['values']['period']['number'] <= 0) {
form_set_error('period][number', t('Backup period must be a number greater than 0.'));
}
if (!is_numeric($form_state['values']['keep']) || $form_state['values']['keep'] < 0) {
form_set_error('keep', t('Number to keep must be an integer greater than or equal to 0.'));
}
parent::edit_form_validate($form, $form_state);
}
/**
* Submit the edit form.
*/
function edit_form_submit($form, &$form_state) {
$periods = $this->frequency_periods();
$period = $periods[$form_state['values']['period']['type']];
$form_state['values']['period'] = $form_state['values']['period']['number'] * $period['seconds'];
parent::edit_form_submit($form, $form_state);
}
/**
* Get the period of the frequency (ie: seconds, minutes etc.)
*/
function get_frequency_period() {
foreach (array_reverse($this->frequency_periods()) as $period) {
if ($period['seconds'] && ($this->period % $period['seconds']) === 0) {
return $period;
}
}
}
/**
* Get a list of available backup periods. Only returns time periods which have a
* (reasonably) consistent number of seconds (ie: no months).
*/
function frequency_periods() {
return array(
'seconds' => array('type' => 'seconds', 'seconds' => 1, 'title' => t('Seconds'), 'singular' => t('Once a second'), 'plural' => t('Every @count seconds')),
'minutes' => array('type' => 'minutes', 'seconds' => 60, 'title' => t('Minutes'), 'singular' => t('Once a minute'), 'plural' => t('Every @count minutes')),
'hours' => array('type' => 'hours', 'seconds' => 3600, 'title' => t('Hours'), 'singular' => t('Once an hour'), 'plural' => t('Every @count hours')),
'days' => array('type' => 'days', 'seconds' => 86400, 'title' => t('Days'), 'singular' => t('Once a day'), 'plural' => t('Every @count days')),
'weeks' => array('type' => 'weeks', 'seconds' => 604800, 'title' => t('Weeks'), 'singular' => t('Once a week'), 'plural' => t('Every @count weeks')),
);
}
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function delete_confirm_message() {
return t('Are you sure you want to delete the profile %name? Any schedules using this profile will be disabled.', array('%name' => $this->get('name')));
}
/**
* Perform the cron action. Run the backup if enough time has elapsed.
*/
function cron() {
$now = time();
// Add a small negative buffer (1% of the entire period) to the time to account for slight difference in cron run length.
$wait_time = $this->period - ($this->period * variable_get('backup_migrate_schedule_buffer', 0.01));
if ($this->is_enabled() && ($now - $this->get('last_run')) >= $wait_time) {
if ($settings = $this->get_profile()) {
$settings->destination_id = $this->destination_id;
$settings->source_id = $this->source_id;
$this->update_last_run($now);
backup_migrate_perform_backup($settings);
$this->remove_expired_backups();
}
else {
backup_migrate_backup_fail("Schedule '%schedule' could not be run because requires a profile which is missing.", array('%schedule' => $schedule->get_name()), $settings);
}
}
}
/**
* Set the last run time of a schedule to the given timestamp, or now if none specified.
*/
function update_last_run($timestamp = NULL) {
if ($timestamp === NULL) {
$timestamp = time();
}
variable_set('backup_migrate_schedule_last_run_' . $this->get('id'), $timestamp);
}
/**
* Set the last run time of a schedule to the given timestamp, or now if none specified.
*/
function get_last_run($timestamp = NULL) {
return variable_get('backup_migrate_schedule_last_run_' . $this->get('id'), 0);
}
/**
* Remove older backups keeping only the number specified by the aministrator.
*/
function remove_expired_backups() {
$files = array();
backup_migrate_include('destinations');
$num_to_keep = $this->keep;
// If num to keep is not 0 (0 is infinity).
if ($num_to_keep && ($destination = $this->get_destination())) {
$i = 0;
if ($destination->op('delete') && $destination_files = $destination->list_files()) {
// Sort the files by modified time.
foreach ($destination_files as $file) {
if ($file->is_recognized_type() && $destination->can_delete_file($file->file_id())) {
$files[str_pad($file->info('filetime'), 10, "0", STR_PAD_LEFT) ."-". $i++] = $file;
}
}
// If we are beyond our limit, remove as many as we need.
$num_files = count($files);
if ($num_files > $num_to_keep) {
$num_to_delete = $num_files - $num_to_keep;
// Sort by date.
ksort($files);
// Delete from the start of the list (earliest).
for ($i = 0; $i < $num_to_delete; $i++) {
$file = array_shift($files);
$destination->delete_file($file->file_id());
}
}
}
}
}
}

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,16 @@
h1. COBALT
Thank you for downloading Cobalt. Cobalt is a way to control Drupal 6 made in the image of "Quicksilver":http://docs.blacktree.com/quicksilver/what_is_quicksilver for Mac. So far it's confirmed to work in Safari/Webkit and Firefox 3. In Firefox, and other potentially compatible browsers, Google Gears have to be installed for quicksilver to work. This is due to Cobalt's need to store data locally for fast access.
h2. INSTRUCTIONS
Cobalt is invoked through pressing [Alt+space] or [Ctrl+space]. Then you only have to start typing to quickly get what you want. Use the arrow up/down to select one of the suggestions and [Alt+left/right] to switch between the the pages. Cobalt will learn from your choices so the amount of selecting and paging will decrease over time. If you are satisfied with the default action (Go to for menu items) you can just press enter to execute it. If you want to do something else (maybe you would like to assign a shortcut) just press [tab] and select one of the actions using the arrow keys or typing part of the action name. The press enter to execute the selected action.
The Cobalt Nodes module also provides convenient context entries like "Edit current node", that, just like any other entry, you can assign shortcuts to. Then you can assign shortcuts like [Ctrl+e], [Ctrl+v] and [Ctrl+Shift+d] to edit, view or delete the node whose page you're currently on.
h2. INSTALLATION
Cobalt consists of four modules. The Cobalt module contains Cobalt itself and access to the menu system, including the devel modules menu items (do you use clear cache often? Assign it a shortcut like [Ctrl+Shift+c] and life *will* get easier.). The three other modules: Cobalt Nodes, Cobalt Taxonomy and Cobalt Users provides access to exactly the stuff their names imply with sensible actions like view, edit and delete.
We now have modules in place that supports lookup for menus, nodes, users and taxonomy. Nodes and users have view, edit and delete actions that can be accessed by tabbing to the right cell and pressing the up and down arrow keys.

View File

@@ -0,0 +1,16 @@
name = Cobalt
description = Cobalt is a javascript implementation of Quicksilver for Drupal
package = Cobalt
core = 7.x
dependencies[] = menu
files[] = cobalt.module
files[] = cobalt_admin.inc.php
files[] = cobalt_update.inc.php
; Information added by drupal.org packaging script on 2012-05-18
version = "7.x-1.0-beta5"
core = "7.x"
project = "cobalt"
datestamp = "1337350855"

Some files were not shown because too many files have changed in this diff Show More