First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,2 @@
This directory should be used to place downloaded and custom libraries (such as
JavaScript libraries) which are used by contributed or custom modules.

View file

@ -0,0 +1,37 @@
Modules extend your site functionality beyond Drupal core.
WHAT TO PLACE IN THIS DIRECTORY?
--------------------------------
Placing downloaded and custom modules in this directory separates downloaded and
custom modules from Drupal core's modules. This allows Drupal core to be updated
without overwriting these files.
DOWNLOAD ADDITIONAL MODULES
---------------------------
Contributed modules from the Drupal community may be downloaded at
https://www.drupal.org/project/project_module.
ORGANIZING MODULES IN THIS DIRECTORY
------------------------------------
You may create subdirectories in this directory, to organize your added modules,
without breaking the site. Some common subdirectories include "contrib" for
contributed modules, and "custom" for custom modules. Note that if you move a
module to a subdirectory after it has been enabled, you may need to clear the
Drupal cache so it can be found. (Alternatively, you can disable the module
before moving it and then re-enable it after the move.)
MULTISITE CONFIGURATION
-----------------------
In multisite configurations, modules found in this directory are available to
all sites. Alternatively, the sites/your_site_name/modules directory pattern
may be used to restrict modules to a specific site instance.
MORE INFORMATION
----------------
Refer to the "Developing for Drupal" section of the README.txt in the Drupal
root directory for further information on extending Drupal with custom modules.

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,89 @@
-------------------------------------------------------------------------------
Backup and Migrate 3 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, code and uploaded
files and of migrating data from one Drupal install to another easier.
Database backup files are a list of SQL statements which can be executed with a
tool such as phpMyAdmin or the command-line mysql client. File and code
backup files are tarballs which can be restored by extracting them to the
desired directory.
-------------------------------------------------------------------------------
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,67 @@
.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 {
width: 15em;
float: left;
overflow: hidden;
white-space: nowrap;
height: 1.75em;
margin: .25em .25em 0 0;
}
.backup-migrate-tables-checkboxes .form-item label input {
margin-right: .5em;
}
div.backup-migrate-tables-checkboxes {
height: 20em;
overflow: auto;
}
div.backup-migrate-tags,
div.backup-migrate-description,
div.backup-migrate-date
{
font-size: smaller;
}
span.backup-migrate-label {
font-weight: bold;
}
table.backup-migrate-listing td {
vertical-align: top;
}
div.row-error {
color: #FF0000;
font-weight: bold;
}
.backup-migrate-listing {
margin-bottom: 2em;
}
.backup-migrate-actions {
text-align: right;
}
html.js #backup-migrate-ui-manual-quick-backup-form fieldset.collapsed,
.backup-migrate-inline {
margin-bottom: 1em;
}
.backup-migrate-form-dependent {
padding-left: 2em;
padding-bottom: 1em;
}
.backup-migrate-form-dependent .form-item {
margin-top: 0;
}
.backup-migrate-footer-message {
margin-bottom: 1em;
}

View file

@ -0,0 +1,16 @@
name = Backup and Migrate
description = "Backup the Drupal database and files or migrate them to another environment."
core = 7.x
files[] = includes/destinations.inc
files[] = includes/profiles.inc
files[] = includes/schedules.inc
configure = admin/config/system/backup_migrate
; Information added by Drupal.org packaging script on 2017-10-18
version = "7.x-3.3"
core = "7.x"
project = "backup_migrate"
datestamp = "1508339653"

View file

@ -0,0 +1,664 @@
<?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(
'export' => array(
'key' => 'machine_name',
'key name' => 'Profile ID',
'admin_title' => 'name',
'primary key' => 'profile_id',
'identifier' => 'item', // Exports will be defined as $preset
'default hook' => 'exportables_backup_migrate_profiles', // Function hook name.
'api' => array(
'owner' => 'backup_migrate',
'api' => 'backup_migrate_exportables', // Base name for api include files.
'minimum_version' => 1,
'current_version' => 1,
),
),
'fields' => array(
'profile_id' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'Primary ID field for the table. Not used for anything except internal lookups.',
'no export' => TRUE, // Do not export database-only keys.
),
'machine_name' => 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(
'export' => array(
'key' => 'machine_name',
'key name' => 'Destination ID',
'admin_title' => 'name',
'primary key' => 'destination_id',
'identifier' => 'item', // Exports will be defined as $preset
'default hook' => 'exportables_backup_migrate_destinations', // Function hook name.
'api' => array(
'owner' => 'backup_migrate',
'api' => 'backup_migrate_exportables', // Base name for api include files.
'minimum_version' => 1,
'current_version' => 1,
),
),
'fields' => array(
'destination_id' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'Primary ID field for the table. Not used for anything except internal lookups.',
'no export' => TRUE, // Do not export database-only keys.
),
'machine_name' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a destination.',
),
'name' => array(
'description' => 'The name of the destination.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'subtype' => 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_sources'] = array(
'export' => array(
'key' => 'machine_name',
'key name' => 'Source ID',
'admin_title' => 'name',
'primary key' => 'source_id',
'identifier' => 'item', // Exports will be defined as $preset
'default hook' => 'exportables_backup_migrate_sources', // Function hook name.
'api' => array(
'owner' => 'backup_migrate',
'api' => 'backup_migrate_exportables', // Base name for api include files.
'minimum_version' => 1,
'current_version' => 1,
),
),
'fields' => array(
'source_id' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'Primary ID field for the table. Not used for anything except internal lookups.',
'no export' => TRUE, // Do not export database-only keys.
),
'machine_name' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
'description' => 'The primary identifier for a source.',
),
'name' => array(
'description' => 'The name of the source.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'subtype' => array(
'description' => 'The type of the source.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE
),
'location' => array(
'description' => 'The the location string of the source.',
'type' => 'text',
'not null' => TRUE
),
'settings' => array(
'description' => 'Other settings for the source.',
'type' => 'text',
'not null' => TRUE,
'serialize' => TRUE,
'serialized default' => 'a:0:{}',
),
),
'primary key' => array('source_id'),
);
$schema['backup_migrate_schedules'] = array(
'export' => array(
'key' => 'machine_name',
'key name' => 'Source ID',
'admin_title' => 'name',
'primary key' => 'schedule_id',
'identifier' => 'item', // Exports will be defined as $preset
'default hook' => 'exportables_backup_migrate_schedules', // Function hook name.
'api' => array(
'owner' => 'backup_migrate',
'api' => 'backup_migrate_exportables', // Base name for api include files.
'minimum_version' => 1,
'current_version' => 1,
),
),
'fields' => array(
'schedule_id' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'Primary ID field for the table. Not used for anything except internal lookups.',
'no export' => TRUE, // Do not export database-only keys.
),
'machine_name' => 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.',
),
'copy_destination_id' => array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => '0',
'description' => 'A second {backup_migrate_destination}.destination_id of the destination to copy the backup 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' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => 'builtin',
),
'cron_schedule' => array(
'description' => 'The cron schedule to run on.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0 4 * * *',
),
),
'primary key' => array('schedule_id'),
);
return $schema;
}
/**
* Implementation of hook_install().
*/
function backup_migrate_install() {
}
/**
* Remove variables on uninstall.
*/
function backup_migrate_uninstall() {
db_query("DELETE FROM {variable} WHERE name LIKE 'backup_migrate_%'");
db_query("DELETE FROM {variable} WHERE name LIKE 'nodesquirrel_%'");
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');
}
}
/**
* Uninstall backup migrate files if it's installed
*/
function backup_migrate_update_7300() {
if (module_exists('backup_migrate_files')) {
module_disable(array('backup_migrate_files'));
$ret[] = array(
'success' => true,
'query' => 'Disabled the Backup and Migrate Files module',
);
}
if (module_exists('nodesquirrel')) {
module_disable(array('nodesquirrel'));
$ret[] = array(
'success' => true,
'query' => 'Disabled the NodeSquirrel module',
);
}
// Add sources to the schema.
$schema['backup_migrate_sources'] = array(
'fields' => array(
'source_id' => array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => '0',
'description' => t('The primary identifier for a source.'),
),
'name' => array(
'description' => t('The name of the source.'),
'type' => 'varchar',
'length' => 255,
'not null' => TRUE
),
'type' => array(
'description' => t('The type of the source.'),
'type' => 'varchar',
'length' => 32,
'not null' => TRUE
),
'location' => array(
'description' => t('The the location string of the source.'),
'type' => 'text',
'not null' => TRUE
),
'settings' => array(
'description' => t('Other settings for the source.'),
'type' => 'text',
'not null' => TRUE,
'serialize' => TRUE,
'serialized default' => 'a:0:{}',
),
),
'primary key' => array('source_id'),
);
if (!db_table_exists('backup_migrate_sources')) {
db_create_table('backup_migrate_sources', $schema['backup_migrate_sources']);
}
// Move custom destinations to sources.
$result = db_query("SELECT * FROM {backup_migrate_destinations} WHERE type in ('filesource', 'db')", array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $item) {
$item['source_id'] = $item['destination_id'];
drupal_write_record('backup_migrate_source', $item);
}
// Change 'destination' settings to 'source' settings
$result = db_query('SELECT * FROM {backup_migrate_profiles}', array(), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $item) {
$item['filters'] = unserialize($item['filters']);
$item['filters']['sources'] = $item['filters']['destinations'];
unset($item['filters']['destinations']);
drupal_write_record('backup_migrate_profiles', $item, array('profile_id'));
}
}
/**
* Switch the cron switch to text.
*/
function backup_migrate_update_7301() {
db_change_field('backup_migrate_schedules', 'cron', 'cron', array('type' => 'varchar', 'length' => 32, 'not null' => TRUE, 'default' => 'builtin'));
db_add_field('backup_migrate_schedules', 'cron_schedule', array('description' => 'The cron schedule to run on.', 'type' => 'varchar', 'length' => 255, 'default' => '0 4 * * *', 'not null' => TRUE));
}
/**
* Add a second destination to schedules.
*/
function backup_migrate_update_7302() {
db_add_field('backup_migrate_schedules', 'copy_destination_id',
array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => '0',
'description' => 'A second {backup_migrate_destination}.destination_id of the destination to copy the backup to.',
)
);
}
/**
* Add a serial id field to all tables to allow them to be ctools exportable.
*/
function backup_migrate_update_7303() {
foreach (array('backup_migrate_sources' => 'source_id', 'backup_migrate_destinations' => 'destination_id', 'backup_migrate_schedules' => 'schedule_id', 'backup_migrate_profiles' => 'profile_id') as $table => $id) {
// Take the primary key status from the machine name so it can be renamed
// A serial field must be defined as a key, so make a temporary index.
// See: https://www.drupal.org/node/190027
db_add_index($table, 'temp', array($id));
db_drop_primary_key($table);
// Drop our temporary index.
db_drop_index($table, 'temp');
// Switch the name of the id to 'machine_name' to be more ctools standard
db_change_field($table, $id, 'machine_name', array('type' => 'varchar', 'length' => 32, 'not null' => TRUE));
// Add a serial ID
db_add_field($table, $id,
array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'Primary ID field for the table. Not used for anything except internal lookups.',
'no export' => TRUE, // Do not export database-only keys.
),
array('primary key' => array($id))
);
}
foreach (array('backup_migrate_sources', 'backup_migrate_destinations') as $table) {
db_change_field($table, 'type', 'subtype', array('type' => 'varchar', 'length' => 32, 'not null' => TRUE));
}
}
/**
* Update all schedules to use the built in cron if none is specified.
*/
function backup_migrate_update_7304() {
db_query("UPDATE {backup_migrate_schedules} SET cron = 'builtin' WHERE cron = '0'");
}
/**
* Fix schema mismatch after upgrade.
*/
function backup_migrate_update_7305() {
foreach (array('backup_migrate_profiles', 'backup_migrate_destinations', 'backup_migrate_sources', 'backup_migrate_schedules') as $table) {
db_change_field($table, 'machine_name', 'machine_name', array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '0',
));
}
db_change_field('backup_migrate_schedules', 'cron', 'cron', array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => 'builtin',
));
}

View file

@ -0,0 +1,114 @@
(function($) {
Drupal.behaviors.backupMigrate = {
attach: function(context) {
if (Drupal.settings.backup_migrate !== undefined) {
if (Drupal.settings.backup_migrate.dependents !== undefined) {
for (key in Drupal.settings.backup_migrate.dependents) {
info = Drupal.settings.backup_migrate.dependents[key];
dependent = $('#edit-' + info['dependent']);
for (key in info['dependencies']) {
$('[name="' + key + '"]').each(function() {
var dependentval = info['dependencies'][key];
var dependency = $(this);
(function(dependent, dependency) {
var checkval = function(inval) {
if (dependency.attr('type') == 'radio') {
var val = $('[name="' + dependency.attr('name') + '"]:checked').val();
return val == inval;
}
else if (dependency.attr('type') == 'checkbox') {
return dependency.is(':checked') && inval == dependency.val();
}
else {
return dependency.val() == inval;
}
return false;
};
if (!checkval(dependentval)) {
// Hide doesn't work inside collapsed fieldsets.
dependent.css('display', 'none');
}
dependency.bind('load change click keypress focus', function() {
if (checkval(dependentval)) {
dependent.slideDown();
}
else {
dependent.slideUp();
}
}).load();
})(dependent, dependency);
});
}
}
for (key in Drupal.settings.backup_migrate.destination_selectors) {
var info = Drupal.settings.backup_migrate.destination_selectors[key];
(function(info) {
var selector = $('#' + info['destination_selector']);
var copy = $('#' + info['copy'])
var copy_selector = $('#' + info['copy_destination_selector']);
var copy_selector_options = {};
// Store a copy of the secondary selector options.
copy_selector.find('optgroup').each(function() {
var label = $(this).attr('label');
copy_selector_options[label] = [];
$(this).find('option').each(function() {
copy_selector_options[label].push(this);
});
$(this).remove();
})
// Assign an action to the main selector to modify the secondary selector
selector.each(function() {
$(this).bind('load change click keypress focus', function() {
var group = $(this).find('option[value=' + $(this).val() + ']').parents('optgroup').attr('label');
if (group) {
copy.parent().find('.backup-migrate-destination-copy-label').text(info['labels'][group]);
copy_selector.empty();
for (var key in copy_selector_options) {
if (key != group) {
copy_selector.append(copy_selector_options[key]);
}
}
}
}).load();
});
})(info);
}
// Add the convert to checkboxes functionality to all multiselects.
$('#backup-migrate-ui-manual-backup-form select[multiple], #backup-migrate-crud-edit-form select[multiple]').each(function() {
var self = this;
$(self).after(
$('<div class="description backup-migrate-checkbox-link"></div>').append(
$('<a>'+ Drupal.settings.backup_migrate.checkboxLinkText +'</a>').click(function() {
var $select = $(self);
var $checkboxes = $('<div></div>').addClass('backup-migrate-tables-checkboxes');
$('option', $select).each(function(i) {
$checkboxes.append(
$('<div class="form-item"></div>').append(
$('<label class="option backup-migrate-table-select">' + this.value + '</label>').prepend(
$('<input type="checkbox" class="backup-migrate-tables-checkbox" name="'+ $select.attr('name') +'"'+ (this.selected ? 'checked="checked"' : '') +' value="'+ this.value +'"/>')
.bind('click change load', function() {
if (this.checked) {
$(this).parent().addClass('checked');
}
else {
$(this).parent().removeClass('checked');
}
}).load()
)
)
);
});
$select.parent().find('.backup-migrate-checkbox-link').remove();
$select.before($checkboxes);
$select.hide();
})
)
);
});
}
}
}
}
})(jQuery);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,277 @@
<?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 databse 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' => "Optional. 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', 'sources');
// Set the message mode to logging.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_source($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 = '') {
backup_migrate_include('profiles', 'destinations', 'sources');
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if (!backup_migrate_get_source($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;
}
else 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;
}
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 perform the restore?'))) {
return drush_user_abort();
}
_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_sources('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 destinations with the given op.
*/
function _backup_migrate_drush_sources($op = NULL) {
backup_migrate_include('sources');
$rows = array(array(dt('ID'), dt('Name'), dt('Operations')));
foreach (backup_migrate_get_sources($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');
$destinations = array();
// Set the message mode to drush output.
_backup_migrate_message_callback('_backup_migrate_message_drush');
if ($destination_id && !$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;
}
// Single destination required.
if ($destination) {
$destinations = array($destination);
}
// List all destinations
else {
$destinations = backup_migrate_get_destinations('list files');
}
// Load all the files.
$rows = $sort = array();
foreach ($destinations as $destination) {
$destination->file_cache_clear();
$dest_files = $destination->list_files();
foreach ($dest_files as $id => $file) {
$info = $file->info();
$rows[] = array(
check_plain($info['filename']),
$destination->get_id(),
format_date($info['filetime'], 'small'),
format_interval(time() - $info['filetime'], 1),
format_size($info['filesize']),
);
$sort[] = $info['filetime'];
}
}
$headers = array(array(
dt('Filename'),
dt('Destination'),
dt('Date'),
dt('Age'),
dt('Size'),
));
if (count($rows)) {
array_multisort($sort, SORT_DESC, $rows);
drush_print_table(array_merge($headers, $rows), 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) {
// If this is an error use drush_set_error to notify the end user and set the exit status
if ($type == 'error') {
drush_set_error(strip_tags(dt($message, $replace)));
}
else {
// 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,988 @@
<?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(
'schedule' => array(
'class' => 'backup_migrate_schedule',
'include' => 'schedules',
),
'source' => array(
'class' => 'backup_migrate_source',
'include' => 'sources',
),
'destination' => array(
'class' => 'backup_migrate_destination',
'include' => 'destinations',
),
'profile' => array(
'class' => 'backup_migrate_profile',
'include' => 'profiles',
),
);
return $out;
}
/**
* Get the info for a particular crud type.
*/
function backup_migrate_crud_type_info($type) {
$types = backup_migrate_crud_types();
if (isset($types[$type])) {
return $types[$type];
}
return NULL;
}
/**
* Get a list of avaiable classes of each crud type.
*/
function backup_migrate_crud_subtypes($type) {
$out = array();
if ($info = backup_migrate_crud_type_info($type)) {
// Include the function that contains the type base.
if (!empty($info['include'])) {
backup_migrate_include($info['include']);
}
// Allow modules (including this one) to declare backup and migrate subtypes.
// We don't use module_invoke_all so we can avoid the side-effects of array_merge_recursive.
$out = array();
foreach (module_implements('backup_migrate_' . $type . '_subtypes') as $module) {
$function = $module . '_backup_migrate_' . $type . '_subtypes';
$result = $function();
if (isset($result) && is_array($result)) {
foreach ($result as $key => $val) {
$out[$key] = $val;
}
}
}
}
return $out;
}
/**
* Get the info for a particular crud subtype.
*/
function backup_migrate_crud_subtype_info($type, $subtype) {
$types = backup_migrate_crud_subtypes($type);
if (isset($types[$subtype])) {
return $types[$subtype];
}
return NULL;
}
/**
* 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, $subtype = NULL) {
$out = $info = NULL;
if ($subtype) {
$info = backup_migrate_crud_subtype_info($type, $subtype);
}
else {
$info = backup_migrate_crud_type_info($type);
}
if (!empty($info)) {
if (!empty($info['include'])) {
backup_migrate_include($info['include']);
}
if (!empty($info['file'])) {
include_once './'. (isset($info['path']) ? $info['path'] : '') . $info['file'];
}
if (class_exists($info['class'])) {
$out = new $info['class'];
$out = $out->create(array('subtype' => $subtype));
}
}
return $out;
}
/**
* Page callback to create a new item.
*/
function backup_migrate_crud_create($type, $subtype = NULL) {
if ($item = backup_migrate_crud_type_load($type, $subtype)) {
return $item;
}
return NULL;
}
/**
* Get the menu items handled by the CRUD code.
*/
function backup_migrate_crud_menu() {
$items = array();
foreach (backup_migrate_crud_types() as $type => $info) {
$item = backup_migrate_crud_type_load($type);
$items += (array)$item->get_menu_items();
foreach (backup_migrate_crud_subtypes($type) as $subtype => $info) {
$subitem = backup_migrate_crud_type_load($type, $subtype);
$items += (array)$subitem->get_menu_items();
}
}
return $items;
}
/**
* Page callback to create a new item.
*/
function backup_migrate_crud_ui_create($type, $subtype = NULL) {
if ($item = backup_migrate_crud_create($type, $subtype)) {
return drupal_get_form('backup_migrate_crud_edit_form', $item);
}
return drupal_not_found();
}
/**
* Page callback to list all items.
*/
function backup_migrate_crud_ui_list($type) {
$out = '';
if ($type = backup_migrate_crud_type_load($type)) {
$out = $type->get_list();
}
return $out;
}
/**
* Page callback to list all items.
*/
function backup_migrate_crud_ui_list_all() {
$out = array();
foreach (backup_migrate_crud_types() as $type => $info) {
$type = backup_migrate_crud_type_load($type);
$out[] = theme('backup_migrate_group', array('title' => t($type->title_plural), 'body' => $type->get_list()));
}
return implode('', $out);
}
/**
* Page callback to edit an item.
*/
function backup_migrate_crud_ui_edit($type, $item_id = NULL) {
if ($type = backup_migrate_crud_type_load($type)) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_edit_form', $item);
}
drupal_goto($type->get_settings_path());
}
}
/**
* Does a crud item with the given name exist.
*
* Callback for the 'machine_name' form type.
*/
function backup_migrate_crud_item_exists($machine_name, $element, $form_state) {
return $form_state['values']['item']->item_exists($machine_name);
}
/**
* 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'] = $item->get_settings_path();
}
}
/**
* Page callback to delete an item.
*/
function backup_migrate_crud_ui_delete($type, $item_id = NULL) {
if ($type = backup_migrate_crud_type_load($type)) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_delete_confirm_form', $item);
}
drupal_goto($type->get_settings_path());
}
}
/**
* 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,
);
if ($item->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$message = $item->revert_confirm_message();
return confirm_form($form, t('Are you sure?'), $item->get_settings_path(), $message, t('Revert'), t('Cancel'));
} else {
$message = $item->delete_confirm_message();
return confirm_form($form, t('Are you sure?'), $item->get_settings_path(), $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'] = $item->get_settings_path();
}
/**
* Export an item.
*/
function backup_migrate_crud_ui_export($type, $item_id = NULL) {
if ($type = backup_migrate_crud_type_load($type)) {
if ($item_id && $item = $type->item($item_id)) {
return drupal_get_form('backup_migrate_crud_export_form', $item->export());
}
drupal_goto($type->get_settings_path());
}
}
/**
* 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;
}
/**
* Page callback to import an item.
*/
function backup_migrate_crud_ui_import() {
return drupal_get_form('backup_migrate_crud_import_form');
}
/**
* Ask confirmation for deletion of a item.
*/
function backup_migrate_crud_import_form($form, &$form_state) {
$form['code'] = array(
'#type' => 'textarea',
'#title' => t('Paste Exported Code Here'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import'),
);
return $form;
}
/**
* Validate handler to import a view
*/
function backup_migrate_crud_import_form_validate($form, &$form_state) {
$item = backup_migrate_crud_create_from_import($form_state['values']['code']);
if ($item) {
$form_state['values']['item'] = $item;
}
else {
form_set_error('code', t('Unable to import item.'));
}
}
/**
* import a item after confirmation.
*/
function backup_migrate_crud_import_form_submit($form, &$form_state) {
$item = $form_state['values']['item'];
$item->save();
_backup_migrate_message('Your !type was imported', array('!type' => t($item->singular)));
$form_state['redirect'] = $item->get_settings_path();
}
/**
* Create an object from the exported object.
*/
function backup_migrate_crud_create_from_import($code) {
$item = NULL;
$code = 'return ' . $code . ';';
ob_start();
$values = eval($code);
ob_end_clean();
if ($values) {
if (!empty($values['type_name']) && $type = backup_migrate_crud_type_load($values['type_name'])) {
$item = $type->create($values);
// Make sure the item's ID doesn't already exist.
$item->unique_id();
}
}
return $item;
}
/**
* 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 $show_in_list = TRUE;
var $settings_path = '/settings/';
var $db_table = '';
var $type_name = '';
var $storage = FALSE;
var $default_values = array();
var $singular = 'item';
var $plural = 'items';
var $title_plural = 'Items';
var $title_singular = 'Item';
/**
* 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('item');
t('items');
t('Items');
t('Item');
// Help the pot extractor find these strings.
t('List !type');
t('Create !type');
t('Delete !type');
t('Edit !type');
t('Export !type');
}
/**
* Constructor, set the basic info pulled from the db or generated programatically.
*/
function __construct($params = array()) {
$this->from_array($this->_merge_defaults((array)$params, (array)$this->get_default_values()));
}
/**
* Merge parameters with the given defaults.
*
* Works like array_merge_recursive, but it doesn't turn scalar values into arrays.
*/
function _merge_defaults($params, $defaults) {
foreach ($defaults as $key => $val) {
if (!isset($params[$key])) {
$params[$key] = $val;
}
else if (is_array($params[$key])) {
$params[$key] = $this->_merge_defaults($params[$key], $val);
}
}
return $params;
}
/**
* 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->unique_id();
}
$record = $this->to_array();
drupal_write_record($this->db_table, $record, !empty($this->storage) ? $this->get_primary_key() : array());
}
/**
* Delete the item from the database.
*/
function delete() {
$keys = (array)$this->get_machine_name_field();
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();
$out['type_name'] = $this->type_name;
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 machine name field name from the schema.
*/
function get_machine_name_field() {
$schema = $this->get_schema();
if (isset($schema['export']['key'])) {
return $schema['export']['key'];
}
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_machine_name_field();
return !empty($keys[0]) && !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_machine_name_field();
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() {
$id = md5(uniqid(mt_rand(), true));
// Find the shortest possible unique id from (min 4 chars).
for ($i = 4; $i < 32; $i++) {
$new_id = substr($id, 0, $i);
if (!$this->item($new_id)) {
return $new_id;
}
}
// If we get here, then all 28 increasingly complex ids were already taken so we'll try again.
// this could theoretially lead to an infinite loop, but the odds are incredibly low.
return $this->generate_id();
}
/**
* Make sure this item has a unique id. Should only be called for new items or the item will collide with itself.
*/
function unique_id() {
$id = $this->get_id();
// Unset the autoincrement field so it can be regenerated.
foreach ((array)$this->get_primary_key() as $key) {
$this->{$key} = NULL;
}
// If the item doesn't have an ID or if it's id is already taken, generate random one.
if (!$id || $this->item($id)) {
$this->set_id($this->generate_id());
}
}
/**
* 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();
$item_id = $this->get_id();
$path = $this->get_settings_path();
if (@$this->storage == BACKUP_MIGRATE_STORAGE_DB || @$this->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$out['edit'] = l(t("edit"), $path . "/edit/$item_id");
}
else if (@$this->storage == BACKUP_MIGRATE_STORAGE_NONE) {
$out['edit'] = l(t("override"), $path . "/edit/$item_id");
}
if (@$this->storage == BACKUP_MIGRATE_STORAGE_DB) {
$out['delete'] = l(t("delete"), $path . "/delete/$item_id");
}
else if (@$this->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
$out['delete'] = l(t("revert"), $path . "/delete/$item_id");
}
$out['export'] = l(t("export"), $path . "/export/$item_id");
return $out;
}
/**
* Get a table of all items of this type.
*/
function get_list() {
$items = $this->all_items();
$rows = array();
foreach ((array)$items as $item) {
if ($item->show_in_list()) {
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));
}
if (user_access('administer backup and migrate')) {
$out .= ' '. l(t('Create a new !item', array('!item' => $this->singular)), $this->get_settings_path() .'/add');
}
return $out;
}
/**
* Get the columns needed to list the type.
*/
function show_in_list() {
return $this->show_in_list;
}
/**
* Get the columns needed to list the type.
*/
function get_settings_path() {
return BACKUP_MIGRATE_MENU_PATH . $this->settings_path . $this->type_name;
}
/**
* 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);
if (isset($col['class'])) {
$out[$key] = array('data' => $out[$key], 'class' => $col['class']);
}
}
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,
);
$name = $this->get('name');
$form['name'] = array(
"#type" => "textfield",
"#title" => t("!type name", array('!type' => $this->title_singular)),
"#default_value" => empty($name) ? t('Untitled !type', array('!type' => $this->title_singular)) : $name,
"#required" => TRUE,
);
$form['id'] = array(
'#type' => 'value',
'#value' => $this->get_id(),
);
$form['machine_name'] = array(
'#type' => 'machine_name',
'#default_value' => $this->get_id(),
'#maxlength' => 255,
'#machine_name' => array(
'source' => array('name'),
'exists' => 'backup_migrate_crud_item_exists',
),
);
$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('#value' => l(t('Cancel'), $this->get_settings_path()));
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('Your !type was saved', array('!type' => t($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 the !type %name?', array('!type' => t($this->singular), '%name' => $this->get('name')));
}
/**
* Get the message to send to the user when confirming the deletion of the item.
*/
function revert_confirm_message() {
return t('Are you sure you want to revert the !type %name back to the default settings?', array('!type' => t($this->singular), '%name' => $this->get('name')));
}
/* Static Functions */
/**
* Get the menu items for manipulating this type.
*/
function get_menu_items() {
$path = $this->get_settings_path();
$type = $this->type_name;
$items[$path] = array(
'title' => $this->title_plural,
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_list', TRUE, $this->type_name),
'access arguments' => array('administer backup and migrate'),
'weight' => 2,
'type' => MENU_LOCAL_TASK,
);
$items[$path .'/list'] = array(
'title' => 'List !type',
'title arguments' => array('!type' => t($this->title_plural)),
'weight' => 1,
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items[$path .'/add'] = array(
'title' => 'Add !type',
'title arguments' => array('!type' => t($this->title_singular)),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_create', TRUE, $this->type_name),
'access arguments' => array('administer backup and migrate'),
'weight' => 2,
'type' => MENU_LOCAL_ACTION,
);
$items[$path .'/delete'] = array(
'title' => 'Delete !type',
'title arguments' => array('!type' => t($this->title_singular)),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_delete', TRUE, $this->type_name),
'access arguments' => array('administer backup and migrate'),
'type' => MENU_CALLBACK,
);
$items[$path .'/edit'] = array(
'title' => 'Edit !type',
'title arguments' => array('!type' => t($this->title_singular)),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_edit', TRUE, $this->type_name),
'access arguments' => array('administer backup and migrate'),
'type' => MENU_CALLBACK,
);
$items[$path .'/export'] = array(
'title' => 'Export !type',
'title arguments' => array('!type' => t($this->title_singular)),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('crud', 'backup_migrate_crud_ui_export', TRUE, $this->type_name),
'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() {
$items = array();
// 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 declare destinations programatically.
$default_items = module_invoke_all($this->db_table);
// Get CTools exported versions.
if (function_exists('ctools_include')) {
ctools_include('export');
$defaults = ctools_export_load_object($this->db_table);
foreach ($defaults as $info) {
$info = (array)$info;
if (!empty($info) && $item = $this->create($info)) {
$default_items[$item->get_id()] = $item;
}
}
}
// Get any items stored as a variable again to correctly mark overrides.
$defaults = (array)variable_get($this->db_table . '_defaults', array());
foreach ($defaults as $info) {
if (is_array($info) && $item = $this->create($info)) {
$default_items[] = $item;
}
}
// Add the default items to the array or set the storage flag if they've already been overridden.
foreach ($default_items as $item) {
if (isset($items[$item->get_id()])) {
$items[$item->get_id()]->storage = BACKUP_MIGRATE_STORAGE_OVERRIDEN;
}
else {
$item->storage = BACKUP_MIGRATE_STORAGE_NONE;
$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;
}
/**
* A particular item.
*/
function item_exists($item_id) {
$items = $this->all_items();
return !empty($items[$item_id]);
}
}

View file

@ -0,0 +1,76 @@
<?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['machine_name'] = 'upload';
parent::__construct($params);
}
/**
* File load destination callback.
*/
function load_file($file_id) {
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');
// Browser downloads must always be the last destination as they must end the current process when they are done.
var $weight = 1000;
function __construct() {
$params = array();
$params['name'] = "Download";
$params['machine_name'] = 'download';
parent::__construct($params);
}
/**
* File save destination callback.
*/
function save_file($file, $settings) {
backup_migrate_include('files');
$file->transfer();
}
}

View file

@ -0,0 +1,318 @@
<?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 default settings for this object.
*
* @return array
* 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 as access log and watchdog).
*/
function backup_settings_default() {
$all_tables = $this->_get_table_names();
// Basic modules that should be excluded.
$basic = array(
// Default core tables.
'accesslog',
'sessions',
'watchdog',
// Search module.
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
// Devel module.
'devel_queries',
'devel_times',
);
// Identify all cache tables.
$cache = array('cache');
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'cache_') === 0) {
$cache[] = $table_name;
}
}
// Simpletest can create a lot of tables that do not need to be backed up,
// but all of them start with the string 'simpletest' so they can be easily
// excluded.
$simpletest = array();
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'simpletest') === 0) {
$simpletest[] = $table_name;
}
}
return array(
'nodata_tables' => array_merge($basic, $cache, module_invoke_all('devel_caches')),
'exclude_tables' => $simpletest,
'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,477 @@
<?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()) {
$first2 = substr($line, 0, 2);
$first3 = substr($line, 0, 3);
// Ignore single line comments. This function doesn't support multiline comments or inline comments.
if ($first2 != '--' && ($first2 != '/*' || $first3 == '/*!')) {
$out .= ' ' . trim($line);
// If a line ends in ; or */ it is a sql command.
if (substr($out, strlen($out) - 1, 1) == ';') {
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', 'remote 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 sever 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 __construct() {
$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,318 @@
<?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', 'local 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 ($this->confirm_destination() && $dir = $this->get_location()) {
$filepath = rtrim($dir, "/") ."/". $file->filename();
// Copy the file if there are multiple destinations.
if (count($settings->get_destinations()) > 1) {
file_unmanaged_copy($file->filepath(), $filepath);
}
// Otherwise we can move it and save a delete.
else {
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;
}
}
/**
* 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));
}
}
/**
* Get the file object for the given file.
*/
function get_file($file_id) {
$files = $this->list_files();
if (isset($files[$file_id])) {
isset($files[$file_id]);
}
return NULL;
}
/**
* 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))) {
if (substr($file, 0, 1) !== '.') {
$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);
}
/**
* Check that a destination is valid.
*/
function confirm_destination() {
if ($dir = $this->get_location()) {
return $this->check_dir($dir);
}
return FALSE;
}
/**
* 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 of 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) {
// Check if the file has already been tested.
if (is_file($directory .'/tested.txt')) {
return $directory;
}
else {
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;
}
// Directory tested OK, so we mark it as tested.
if ($fp = fopen($directory .'/tested.txt', 'w')) {
$contents = t('The presence of this file indicates that this directory has been tested as safe to use as a destination for Backup and Migrate. If you change the permissions of this directory or change your web server settings, please delete this file so that the directory can be checked again.');
@fputs($fp, $contents);
fclose($fp);
}
return $directory;
}
}
/**
* Check if the given directory is within the webroot and is therefore web accessible.
*/
function dir_in_webroot($directory) {
$real_dir = drupal_realpath($directory);
$real_root = drupal_realpath(DRUPAL_ROOT);
if ($real_dir == $real_root || strpos($real_dir, $real_root . '/') === 0) {
return TRUE;
}
return FALSE;
}
/**
* Check if a file can be read remotely via http.
*/
function test_file_readable_remotely($directory, $contents) {
$real_dir = drupal_realpath($directory);
$real_root = drupal_realpath(DRUPAL_ROOT);
if ($real_dir && $real_root) {
// Get the root relative path.
$path = substr($real_dir, strlen($real_root));
$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,435 @@
<?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', 'remote 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 = (array)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 (!$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,976 @@
<?php
/**
* @file
* Functions to handle the NodeSquirrel backup destination.
*/
define('NODESQUIRREL_SECRET_KEY_PATTERN', '/^[0-9a-f]{32}\:?[0-9a-f]{32}$/');
/**
* Check that a nodesquirel key is valid.
*/
function backup_migrate_nodesquirrel_check_secret_key($secret_key) {
if ($destination = backup_migrate_nodesquirrel_get_destination($secret_key)) {
if ($destination->confirm_destination()) {
return $destination;
}
}
return FALSE;
}
/**
* Get the NS destination for the given key.
*/
function backup_migrate_nodesquirrel_get_destination($secret_key) {
if ($secret_key) {
backup_migrate_include('destinations');
$destination = backup_migrate_create_destination('nodesquirrel', array('machine_name' => 'nodesquirrel'));
$destination->settings['secret_key'] = $secret_key;
return $destination;
}
return NULL;
}
/**
* Get a helper link to activate a site and create a tree.
*/
function backup_migrate_nodesquirrel_get_activate_help_text() {
$activate_link = backup_migrate_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 backup_migrate_nodesquirrel_get_activate_link() {
$activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'https://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 backup_migrate_nodesquirrel_get_manage_link($destination) {
$url = variable_get('nodesquirrel_manage_url', 'https://manage.nodesquirrel.com') . '/backups/' . $destination->_get_destination();
return l($url, $url);
}
/**
* Get a helper link to activate a site and create a tree.
*/
function backup_migrate_nodesquirrel_get_plan_link() {
$url = variable_get('nodesquirrel_manage_url', 'https://manage.nodesquirrel.com') . '/plan';
return l($url, $url);
}
/**
* Get the path to the nodesquirrel settings tab.
*/
function backup_migrate_nodesquirrel_settings_path() {
$path = BACKUP_MIGRATE_MENU_PATH . '/settings/destinations/nodesquirrel/edit';
return $path;
}
/**
* NodeSquirrel settings page callback.
*/
function backup_migrate_nodesquirrel_settings() {
return drupal_get_form('backup_migrate_nodesquirrel_settings_form');
}
/**
* NodeSquirrel settings form.
*/
function backup_migrate_nodesquirrel_credentials_settings_form($key = '', $status) {
$collapse = !empty($status);
$form['nodesquirrel_credentials'] = array(
'#type' => 'fieldset',
'#title' => t('NodeSquirrel Credentials'),
'#collapsible' => $collapse,
'#collapsed' => $collapse,
);
$form['nodesquirrel_credentials']['nodesquirrel_secret_key'] = array(
'#type' => 'textfield',
'#title' => t('Secret Key'),
'#size' => 80,
'#default_value' => $key,
);
if (empty($key)) {
$form['nodesquirrel_credentials']['secret_key_help'] = backup_migrate_nodesquirrel_get_activate_help_text();
}
return $form;
}
/**
* Return a form element with some help text describing NodeSquirrel.
*/
function backup_migrate_nodesquirrel_info_form() {
$form = array();
$form['nodesquirrel_info'] = array(
'#type' => 'fieldset',
'#title' => t('What is NodeSquirrel?'),
);
$form['nodesquirrel_info']['intro'] = array(
'#type' => 'markup',
'#markup' => t('<p>NodeSquirrel is the cloud backup service built by the maintainers of Backup and Migrate.</p></p>NodeSquirrel is now free for all Drupal sites, courtesy of Pantheon.</p><p>Create your free account at !signup</p>', array('!nodesquirrel' => l('nodesquirrel.com', 'http://www.nodesquirrel.com'), '!signup' => backup_migrate_nodesquirrel_get_activate_link())),
);
return $form;
}
/**
* Display the NodeSquirrel status on the configuration form.
*/
function backup_migrate_nodesquirrel_status_form($key, $destination, $status) {
$form = array();
$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. Enter your Secret Key below to get started.'),
);
// Warn the user if the key they entered is invalid.
if ($key && empty($status)) {
$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' => backup_migrate_nodesquirrel_get_activate_link()));
}
else if (!empty($destination) && is_array($status)) {
if (!empty($status['lifetime_backups_used']) && !empty($status['lifetime_backups']) && $status['lifetime_backups_used'] >= $status['lifetime_backups']) {
$form['nodesquirrel_status']['status']['#markup'] = t('Your !num backup trial has expired. Visit !link to continue backing up.', array('!num' => $status['lifetime_backups'], '!link' => backup_migrate_nodesquirrel_get_plan_link()));
}
else {
$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);
}
}
if (!empty($status['plan_name'])) {
$form['nodesquirrel_status']['plan_name'] = array(
'#type' => 'item',
'#title' => t('Current Plan'),
'#markup' => check_plain($status['plan_name'])
);
if (!empty($status['lifetime_backups']) && isset($status['lifetime_backups_used'])) {
$remains = $status['lifetime_backups'] - $status['lifetime_backups_used'];
$remains = $remains > 0 ? $remains : t('none');
$form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . t('(@remains remaining of @backups backup trial)', array('@backups' => $status['lifetime_backups'], '@remains' => $remains));
}
if (!empty($status['lifespan']) && isset($status['age']) && $status['lifespan'] > 0) {
$remains = ceil(($status['lifespan'] - $status['age']) / 86400);
if ($remains <= 0) {
$form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . t('(Your !span day trial has expired.)', array('!span' => ceil($status['lifespan'] / 86400)));
}
else {
$form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . format_plural($remains, '(1 day remaining)', '(!span days remaining)', array('!span' => ceil($remains)));
}
}
}
if (isset($status['backups_used'])) {
$form['nodesquirrel_status']['backups_used'] = array(
'#type' => 'item',
'#title' => t('Number of Stored Backups'),
'#markup' => $status['backups_used'] == 0 ? t('None') : number_format($status['backups_used'])
);
}
if (isset($status['last_backup'])) {
$form['nodesquirrel_status']['last_backup'] = array(
'#type' => 'item',
'#title' => t('Last Backup'),
'#markup' => empty($status['last_backup']) ? t('Never') : t('!date (!ago ago)', array('!date' => format_date($status['last_backup'], 'small'), '!ago' => format_interval(time() - $status['last_backup'], 1)))
);
}
if ($status['bytes_per_locker']) {
if (isset($status['bytes_used'])) {
$form['nodesquirrel_status']['space'] = array(
'#type' => 'item',
'#title' => t('Storage Space'),
'#markup' => t('!used used of !total (!remaining remaining)', array('!used' => backup_migrate_format_size($status['bytes_used']), '!total' => backup_migrate_format_size($status['bytes_per_locker']), '!remaining' => backup_migrate_format_size(max(0, $status['bytes_per_locker'] - $status['bytes_used']))))
);
}
else {
$form['nodesquirrel_status']['space'] = array(
'#type' => 'item',
'#title' => t('Total Storage Space'),
'#markup' => t('!total', array('!total' => backup_migrate_format_size($status['bytes_per_locker'])))
);
}
}
$form['nodesquirrel_status']['manage'] = array(
'#type' => 'item',
'#title' => t('Management Console'),
'#markup' => backup_migrate_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.'),
);
}
return $form;
}
function backup_migrate_nodesquirrel_schedule_settings_form($destination, $status) {
backup_migrate_include('sources', 'schedules', 'profiles');
// If the schedule has been overriden it must be edited in the schedule tab.
$schedule = backup_migrate_crud_get_item('schedule', 'nodesquirrel');
$default = 60*60*24;
$form = array();
$form['nodesquirrel_schedule'] = array(
'#type' => 'fieldset',
'#title' => t('Backup Schedule'),
'#description' => t('Set up a schedule to back up your site to NodeSquirrel. You can customize this schedule or add additional schedules in the !schedule.', array('!schedule' => l(t('Schedules tab'), BACKUP_MIGRATE_MENU_PATH . '/schedule'), '!cron' => l(t('cron'), 'http://drupal.org/cron'))),
);
$key = 'nodesquirrel_schedule';
$form['nodesquirrel_schedule'][$key] = array();
$defaults = array(
'period' => empty($schedule) ? variable_get('nodesquirrel_schedule', 60*60*24) : $schedule->get('period'),
'enabled' => empty($schedule) ? variable_get('nodesquirrel_schedule_enabled', TRUE) : $schedule->get('enabled'),
'source_id' => empty($schedule) ? variable_get('nodesquirrel_schedule_source_id', 'db') : $schedule->get('source_id'),
'keep' => empty($schedule) ? variable_get('nodesquirrel_schedule_keep', BACKUP_MIGRATE_SMART_DELETE) : $schedule->get('keep'),
);
$form['nodesquirrel_schedule'][$key]['nodesquirrel_schedule_enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Automatically backup to NodeSquirrel'),
'#default_value' => $defaults['enabled'],
);
$form['nodesquirrel_schedule'][$key]['settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'nodesquirrel_schedule_enabled' => TRUE,
),
);
$form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule_source_id'] = _backup_migrate_get_source_pulldown($defaults['source_id']);
$options = array(
(60*60) => t('Once an hour'),
(60*60*24) => t('Once a day'),
(60*60*24*7) => t('Once a week'),
);
$period = $defaults['period'];
if (!isset($options[$period])) {
$options[$period] = empty($schedule) ? t('Custom') : $schedule->get('frequency_description');
}
$form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule'] = array(
'#type' => 'select',
'#title' => t('Schedule Frequency'),
'#options' => $options,
'#default_value' => $period,
);
$form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule_keep'] = array(
'#type' => 'checkbox',
'#title' => t('Automatically delete old backups'),
'#return_value' => $defaults['keep'] == BACKUP_MIGRATE_KEEP_ALL ? BACKUP_MIGRATE_SMART_DELETE : $defaults['keep'],
'#default_value' => $defaults['keep'],
);
return $form;
}
/**
* NodeSquirrel settings form.
*/
function backup_migrate_nodesquirrel_settings_form($form_state) {
_backup_migrate_message_callback('_backup_migrate_message_browser');
$form = array();
$key = variable_get('nodesquirrel_secret_key', '');
$status = array();
if ($destination = backup_migrate_nodesquirrel_get_destination($key)) {
$status = $destination->check_limits();
}
$form += backup_migrate_nodesquirrel_info_form();
$form += backup_migrate_nodesquirrel_status_form($key, $destination, $status);
$form += backup_migrate_nodesquirrel_credentials_settings_form($key, $status);
$form += backup_migrate_nodesquirrel_schedule_settings_form($destination, $status);
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', 'remote 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;
}
/**
* Get the menu items for manipulating this type.
*/
function get_menu_items() {
$items = array();
$path = BACKUP_MIGRATE_MENU_PATH . '/nodesquirrel';
$items[$path] = array(
'title' => t('NodeSquirrel'),
'page callback' => 'backup_migrate_menu_callback',
'page arguments' => array('destinations.nodesquirrel', 'backup_migrate_nodesquirrel_settings'),
'access arguments' => array('administer backup and migrate'),
'weight' => 10,
'type' => MENU_LOCAL_TASK,
);
return $items;
}
/**
* Declare any mysql databases defined in the settings.php file as a possible destination.
*/
function destinations() {
$out = array();
$out['nodesquirrel'] = backup_migrate_create_destination('nodesquirrel', array('machine_name' => 'nodesquirrel'));
if ($secret_key = variable_get('nodesquirrel_secret_key', '')) {
$out['nodesquirrel']->settings['secret_key'] = $secret_key;
}
else {
$out['nodesquirrel']->supported_ops = array('manual backup', 'remote backup');
}
return $out;
}
/**
* Returns a form to be completed before saving to the destination can be complete.
*/
function before_backup_form($settings) {
$form = array();
$key = $this->settings('secret_key');
if (empty($key)) {
$form += backup_migrate_nodesquirrel_info_form();
$form += backup_migrate_nodesquirrel_credentials_settings_form();
}
return $form;
}
/**
* Validate the before_backup_form form.
*/
function before_backup_form_validate($settings, $form, $form_state) {
if (isset($form_state['values']['nodesquirrel_secret_key'])) {
$key = trim($form_state['values']['nodesquirrel_secret_key']);
if ($error = $this->vaidate_key($key)) {
form_set_error('secret_key', $error);
}
}
}
/**
* Submit the before_backup_form form.
*/
function before_backup_form_submit($settings, $form, $form_state) {
if (isset($form_state['values']['nodesquirrel_secret_key'])) {
$this->settings['secret_key'] = $form_state['values']['nodesquirrel_secret_key'];
variable_set('nodesquirrel_secret_key', $this->settings['secret_key']);
}
}
/**
* 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.
_backup_migrate_message('Your backup has been saved to your NodeSquirrel account. View it at !account', array('!account' => backup_migrate_nodesquirrel_get_manage_link($this)));
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();
// If this is a new destination but the default NS destination has not been created yet,
// redirect to the NS config screen.
if (!$this->get_id() && !variable_get('nodesquirrel_secret_key', '')) {
drupal_goto(BACKUP_MIGRATE_MENU_PATH . '/nodesquirrel');
}
$form['settings'] = array('#tree' => TRUE);
$activate_link = backup_migrate_nodesquirrel_get_activate_link();
// 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 ($error = $this->vaidate_key($key)) {
form_set_error('secret_key', $error);
}
}
/**
* Validate a secret key. Returns error text if the key is invalid.
*/
function vaidate_key($key) {
$error = FALSE;
if ($key) {
if (!preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $key)) {
return 'The secret key you entered is not the right format. Please make sure you copy it exactly.';
}
$this->settings['secret_key'] = check_plain($key);
$limits = $this->check_limits();
if (!$limits) {
$err = xmlrpc_error();
if (!empty($err->code) && $err->code == '401') {
return 'Could not log in to the NodeSquirrel server. Please check that your secret key is correct.';
}
else {
return 'Your site could not be found on NodeSquirrel. Please check that your secret key is correct.';
}
}
}
else {
return 'You must enter a NodeSquirrel secret key.';
}
return FALSE;
}
/**
* 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 'https://' . $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 secret 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);
if (variable_get('debug_http_request', FALSE)) {
drupal_debug(date('r'));
drupal_debug($request);
drupal_debug($response);
}
// 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,184 @@
<?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', 'remote 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']['#type'] = 'value';
$form['host']['#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']);
}
return $this->s3;
}
}
drupal_set_message(t('Due to drupal.org code hosting policies, the S3 library needed to use an S3 destination is no longer distributed with this module. You must download the library from !link and place it in one of these locations: %locations.', array('%locations' => implode(', ', $library_paths), '!link' => l('http://undesigned.org.za/2007/10/22/amazon-s3-php-class', 'http://undesigned.org.za/2007/10/22/amazon-s3-php-class'))), 'error', FALSE);
return NULL;
}
}

View file

@ -0,0 +1,564 @@
<?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) {
$files = &drupal_static('backup_migrate_temp_files_add', array());
if (!$filepath) {
return $files;
}
else {
$files[] = $filepath;
}
}
/**
* Delete all temporary files.
*/
function _backup_migrate_temp_files_delete() {
if (variable_get('backup_migrate_cleanup_temp_files', TRUE)) {
// Delete the temp files created during this run.
foreach (backup_migrate_temp_files_add() as $file) {
if (file_exists($file) && is_writable($file)) {
_backup_migrate_temp_files_delete_file($file);
}
}
// Delete temp files abandoned for 6 or more hours.
$dir = file_directory_temp();
$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) {
_backup_migrate_temp_files_delete_file("$dir/$file");
}
}
closedir($handle);
}
}
}
/**
* Delete a temporary file or folder
*/
function _backup_migrate_temp_files_delete_file($file) {
if (file_exists($file) && (is_writable($file) || is_link($file))) {
if (!is_link($file) && is_dir($file) && is_readable($file) && $handle = opendir($file)) {
$dir = $file;
while (FALSE !== ($file = @readdir($handle))) {
if ($file != '..' && $file != '.') {
_backup_migrate_temp_files_delete_file("$dir/$file");
}
}
rmdir($dir);
}
else {
unlink($file);
}
}
}
/**
* Move files recursively.
*/
function _backup_migrate_move_files($from, $to) {
if (is_readable($from)) {
if (is_dir($from) && is_readable($from) && $handle = opendir($from)) {
if (!file_exists($to)) {
mkdir($to);
}
while (FALSE !== ($file = @readdir($handle))) {
if ($file != '..' && $file != '.') {
_backup_migrate_move_files("$from/$file", "$to/$file");
}
}
}
else {
rename($from, $to);
}
}
return FALSE;
}
/**
* Create a temporary directory.
*/
function backup_migrate_temp_directory() {
$tmp = realpath(file_directory_temp());
// Check the writability of the temp directory.
if (!is_writable(realpath(file_directory_temp()))) {
_backup_migrate_message('Your temporary directory %tmp is not writable. Backup and migrate needs to be able to create temporary files.', array('%tmp' => $tmp), 'error');
}
// Use a full path so that the files can be deleted during the shutdown function if needed.
$file = $tmp .'/'. uniqid('backup_migrate_');
mkdir($file);
backup_migrate_temp_files_add($file);
return $file;
}
/**
* 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($settings) {
// Get the raw filename from the settings.
$filename = $settings->filename;
// Replace any tokens
if (module_exists('token') && function_exists('token_replace')) {
$filename = token_replace($filename);
}
// Remove illegal characters
$filename = _backup_migrate_clean_filename($filename);
// Generate a timestamp if needed.
$timestamp = '';
if ($settings->append_timestamp && $settings->timestamp_format) {
$timestamp = format_date(time(), 'custom', $settings->timestamp_format);
}
// Trim to length if needed to allow the timestamp to fit into the max filename.
$filename = _backup_migrate_filename_append_prepare($filename, $timestamp);
$filename .= '-' . $timestamp;
$filename = trim($filename, '-');
// If there is no filename, then just call it untitled.
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 _backup_migrate_clean_filename(variable_get('site_name', "backup_migrate"));
}
}
/**
* Clean up a filename to remove unsafe characters.
*/
function _backup_migrate_clean_filename($filename) {
$filename = preg_replace("/[^a-zA-Z0-9\.\-_]/", "", $filename);
return $filename;
}
/**
* 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 __construct($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;
}
$extension_str = '.' . $this->extension();
$this->name = _backup_migrate_filename_append_prepare($this->name, $extension_str);
return $this->name . $extension_str;
}
/**
* Set the current filepath.
*/
function set_filepath($path) {
$this->path = $path;
$params = array(
'filename' => basename($path),
'file_id' => basename($path)
);
if (file_exists($path)) {
$params['filesize'] = filesize($path);
$params['filetime'] = filectime($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 one or all pieces of info for the file.
*/
function info_set($key, $value) {
$this->file_info[$key] = $value;
}
/**
* 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'];
}
function filesize() {
if (empty($this->file_info['filesize'])) {
$this->calculate_filesize();
}
return $this->file_info['filesize'];
}
function calculate_filesize() {
$this->file_info['filesize'] = '';
if (!empty($this->path) && file_exists($this->path)) {
$this->file_info['filesize'] = filesize($this->path);
}
}
/**
* 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[] = array('key' => 'Content-Encoding', 'value' => '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,249 @@
<?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 sources for this filter.
*/
function sources() {
$out = array();
foreach ($this->_get_source_types() as $type) {
if (method_exists($type, 'sources')) {
$out += $type->sources();
}
}
return $out;
}
/**
* Get the default backup settings for this filter.
*/
function backup_settings_default() {
backup_migrate_include('sources');
$out = array();
foreach (backup_migrate_get_sources() as $source) {
$out['sources'][$source->get_id()] = $source->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('sources');
$out = array('sources' => array(
'#tree' => TRUE,
));
foreach (backup_migrate_get_sources() as $source) {
$source_settings = (array)(@$settings['sources'][$source->get_id()]) + $settings;
if ($form = $source->backup_settings_form($source_settings)) {
$out['sources'][$source->get_id()] = array(
'#type' => 'fieldset',
'#title' => t('!name Backup Options', array('!name' => $source->get('name'))),
"#collapsible" => TRUE,
"#collapsed" => TRUE,
'#tree' => TRUE,
'#parents' => array('filters', 'sources', $source->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 before-backup form for the active sources and destinations.
*/
function before_action_form($op, $settings) {
$form = array();
$method = 'before_' . $op . '_form';
if ($source = $settings->get_source()) {
if (method_exists($source, $method)) {
$form += $source->{$method}($settings);
}
}
foreach ($settings->get_destinations() as $destination) {
if (method_exists($destination, $method)) {
$form += $destination->{$method}($settings);
}
}
return $form;
}
/**
* Get the before-backup form for the active sources and destinations.
*/
function before_action_form_validate($op, $settings, $form, $form_state) {
$method = 'before_' . $op . '_form_validate';
foreach ($settings->get_all_locations() as $location) {
if (method_exists($location, $method)) {
$location->{$method}($settings, $form, $form_state);
}
}
}
/**
* Get the before-backup form for the active sources and destinations.
*/
function before_action_form_submit($op, $settings, $form, $form_state) {
$method = 'before_' . $op . '_form_submit';
foreach ($settings->get_all_locations() as $location) {
if (method_exists($location, $method)) {
$location->{$method}($settings, $form, $form_state);
}
}
}
/**
* Get the file types supported by this destination.
*/
function file_types() {
$types = array();
foreach ($this->_get_destination_types() as $destination) {
$types += $destination->file_types();
}
foreach ($this->_get_source_types() as $source) {
$types += $source->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['sources'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['sources'][$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['sources'][$source->get_id()])) {
$settings->filters = (array)($settings->filters['sources'][$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');
$destinations = &drupal_static('backup_migrate_filter_backup_restore::_get_destination_types', NULL);
if (!is_array($destinations)) {
$destinations = array();
$types = backup_migrate_get_destination_subtypes();
// 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;
}
/**
* Get a list of dummy destinations representing each of the available source types.
*/
function _get_source_types() {
backup_migrate_include('sources');
$sources = &drupal_static('backup_migrate_filter_backup_restore::_get_source_types', NULL);
if (!is_array($sources)) {
$sources = array();
$types = backup_migrate_get_source_subtypes();
// 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'];
}
$sources[] = new $type['class'](array());
}
}
return $sources;
}
}

View file

@ -0,0 +1,298 @@
<?php
/**
* @file
* A filter for compressing bckups with zip, gz bzip etc.
*/
/**
* 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, $settings);
}
/**
* 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("BZip");
}
if (class_exists('ZipArchive')) {
$compression_options['zip'] = t("Zip", array(), array('context' => 'compression format'));
}
return $compression_options;
}
/**
* Gzip encode a file.
*/
function _backup_migrate_gzip_encode($source, $dest, $level = 9, $settings) {
$success = FALSE;
// Try command line gzip first.
if (!empty($settings->filters['use_cli'])) {
$success = backup_migrate_exec("gzip -c -$level %input > %dest", array('%input' => $source, '%dest' => $dest, '%level' => $level));
}
if (!$success && @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;
}
/**
* Gzip decode a file.
*/
function _backup_migrate_gzip_decode($source, $dest, $settings) {
$success = FALSE;
if (!empty($settings->filters['use_cli'])) {
$success = backup_migrate_exec("gzip -d -c %input > %dest", array('%input' => $source, '%dest' => $dest));
}
if (!$success && @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;
}
/**
* Bzip encode a file.
*/
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;
}
/**
* Bzip decode a file.
*/
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;
}
/**
* Zip encode a file.
*/
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;
}
/**
* Zip decode a file.
*/
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, $settings)) {
$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, $settings) {
$success = FALSE;
switch ($file->type_id()) {
case "gzip":
$from = $file->pop_type();
$success = $this->_backup_migrate_gzip_decode($from->filepath(), $file->filepath(), $settings);
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"),
"#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.'),
);
}
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,332 @@
<?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) {
$filters = &drupal_static('backup_migrate_get_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) {
backup_migrate_filters_invoke_all('pre_backup', $file, $settings);
$filters = backup_migrate_get_filters('backup');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->backup($file, $settings);
}
}
backup_migrate_filters_invoke_all('post_backup', $file, $settings);
return $file;
}
/**
* Filter a backup file before sending it to the destination.
*/
function backup_migrate_filters_restore($file, &$settings) {
backup_migrate_filters_invoke_all('pre_restore', $file, $settings);
$filters = backup_migrate_get_filters('restore');
foreach ($filters as $filter) {
if ($file) {
$file = $filter->restore($file, $settings);
}
}
backup_migrate_filters_invoke_all('post_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 backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form($settings, $op) {
$out = array();
$out += backup_migrate_filters_invoke_all('before_action_form', $op, $settings);
$out += backup_migrate_filters_invoke_all('before_' . $op .'_form', $settings);
return $out;
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form_validate($settings, $op, $form, &$form_state) {
backup_migrate_filters_invoke_all('before_action_form_validate', $op, $settings, $form, $form_state);
backup_migrate_filters_invoke_all('before_' . $op .'_form_validate', $settings, $form, $form_state);
}
/**
* Get the backup settings for all of the filters.
*/
function backup_migrate_filters_before_action_form_submit($settings, $op, $form, &$form_state) {
backup_migrate_filters_invoke_all('before_action_form_submit', $op, $settings, $form, $form_state);
backup_migrate_filters_invoke_all('before_' . $op .'_form_submit', $settings, $form, $form_state);
}
/**
* 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) {
}
/**
* 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 immediately prior to backup.
*/
function pre_backup($file, $settings) {
}
/**
* This function is called immediately post backup.
*/
function post_backup($file, $settings) {
}
/**
* This function is called on a backup file before importing it.
*/
function restore($file, $settings) {
return $file;
}
/**
* This function is called immediately prior to restore.
*/
function pre_restore($file, $settings) {
}
/**
* This function is called immediately post restore.
*/
function post_restore($file, $settings) {
}
}

View file

@ -0,0 +1,114 @@
<?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_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[notify_success_enable]' => TRUE,
),
);
$form['advanced']['notify_success_email_wrapper']['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_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[notify_failure_enable]' => TRUE,
),
);
$form['advanced']['notify_failure_email_wrapper']['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']) {
$messages = $this->get_messages();
$subject = t('!site backup succeeded', array('!site' => variable_get('site_name', 'Drupal site')));
if ($messages = $this->get_messages()) {
$body = t("The site backup has completed successfully with the following messages:\n!messages", array('!messages' => $messages));
}
else {
$body = t("The site backup has completed successfully.\n");
}
mail($settings->filters['notify_success_email'], $subject, $body);
}
}
/**
* Send the failure email.
*/
function backup_fail($settings) {
if (@$settings->filters['notify_failure_enable'] && $to = @$settings->filters['notify_failure_email']) {
$messages = $this->get_messages();
$subject = t('!site backup failed', array('!site' => variable_get('site_name', 'Drupal site')));
if ($messages = $this->get_messages()) {
$body = t("The site backup has failed with the following messages:\n!messages", array('!messages' => $messages));
}
else {
$body = t("The site backup has failed for an unknown reason.");
}
mail($settings->filters['notify_failure_email'], $subject, $body);
}
}
/**
* 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,239 @@
<?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 run some basic utility functions.
*
* @ingroup backup_migrate_filters
*/
class backup_migrate_filter_utils extends backup_migrate_filter {
var $op_weights = array('pre_backup' => -1000, 'post_backup' => 1000);
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_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[utils_site_offline]' => TRUE,
),
);
$form['advanced']['utils_site_offline_message_wrapper']['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('site_offline_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('Add a note'),
'#default_value' => !empty($settings['utils_description']) ? $settings['utils_description'] : NULL,
'#description' => t('Add a short note to the backup file.'),
);
$form['advanced']['use_cli'] = array(
"#type" => "checkbox",
"#title" => t("Use cli commands"),
"#default_value" => !empty($settings['use_cli']),
"#description" => t("Use the command line tools (mysqldump, tar, gzip etc.) if available. This can be faster for large sites but will not work on all servers. EXPERIMENTAL"),
);
$form['advanced']['ignore_errors'] = array(
"#type" => "checkbox",
"#title" => t("Ignore errors"),
"#default_value" => !empty($settings['ignore_errors']),
"#description" => t("Will attempt to complete backup even if certain recoverable errors occur. This may make the backup files invalid. Enable this if you have unreadable files that you want to ignore during backup."),
);
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_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'filters[utils_site_offline]' => TRUE,
),
);
$form['advanced']['utils_site_offline_message_wrapper']['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('site_offline_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']['use_cli'] = array(
"#type" => "checkbox",
"#title" => t("Use cli commands"),
"#default_value" => !empty($settings['use_cli']),
"#description" => t("Use the command line tools (mysqldump, tar, gzip etc.) if available. This can be faster for large sites but will not work on all servers. EXPERIMENTAL"),
);
// $form['advanced']['ignore_errors'] = array(
// "#type" => "checkbox",
// "#title" => t("Ignore errors"),
// "#default_value" => !empty($settings['ignore_errors']),
// "#description" => t("Will attempt to complete restore even if certain recoverable errors occur. This may could corrupt your site."),
// );
return $form;
}
function pre_backup($file, $settings) {
$this->take_site_offline($settings);
$this->disable_devel_query($settings);
}
function post_backup($file, $settings) {
$this->enable_devel_query($settings);
$this->take_site_online($settings);
if ($file) {
$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['siteurl'] = url('', array('absolute' => TRUE));
$file->file_info['sitename'] = variable_get('site_name', '');
$file->file_info['drupalversion'] = VERSION;
$file->calculate_filesize();
$source = $settings->get('source');
$file->file_info['bam_sourceid'] = $source->get('id');
$file->file_info['bam_sourcetype'] = $source->get('subtype');
$file->file_info['bam_sourcename'] = $source->get('name');
// Add any additional info that has been added to the settings by other plugins.
if (!empty($settings->file_info)) {
$file->file_info += $settings->file_info;
}
}
/**
* Take the site offline if configured to do so.
*/
function take_site_offline($settings) {
// If the site is already offline then don't do anything.
if (!variable_get('maintenance_mode', 0)) {
// Save the current state of the site in case a restore overwrites it.
if (!empty($settings->filters['utils_site_offline'])) {
$this->saved_site_offline = TRUE;
$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.
if (variable_get('maintenance_mode', 0) && !empty($this->saved_site_offline)) {
variable_set('maintenance_mode', 0);
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,543 @@
<?php
/**
* @file
* All of the location handling code needed for Backup and Migrate.
*/
backup_migrate_include('crud');
/**
* Get the available location types.
*/
function backup_migrate_get_location_subtypes() {
backup_migrate_include('crud', 'destinations', 'sources');
return backup_migrate_crud_subtypes('destination') + backup_migrate_crud_subtypes('source');
}
/**
* Implementation of hook_backup_migrate_locations().
*
* Get the built in backup locations and those in the db.
*/
function backup_migrate_backup_migrate_locations() {
$out = array();
// Allow the filter plugins to declare the default locations.
backup_migrate_include('filters');
$out += backup_migrate_filters_invoke_all('locations');
return $out;
}
/**
* Get all the available backup location.
*
* @param $op
* The operation which will be performed on the location. Hooks can use this
* to return only those locations appropriate for the given op.
* Options include:
* 'manual backup' - locations available for manual backup
* 'scheduled backup' - locations available for schedules backup
* 'list files' - locations whose backup files can be listed
* 'restore' - locations whose files can be restored from
* 'all' - all available locations should be returned
*/
function backup_migrate_get_locations($op = 'all') {
$locations = &drupal_static('backup_migrate_get_locations', NULL);
// Get the list of locations and cache them locally.
if ($locations === NULL) {
$locations = backup_migrate_crud_get_items('location');
}
// Return all if that's what was asked for.
if ($op == 'all') {
return $locations;
}
// Return only those locations which support the given op.
$out = array();
if ($locations) {
foreach ($locations as $key => $location) {
if ($location->op($op)) {
$out[$key] = $location;
}
}
}
return $out;
}
/**
* Get the location of the given id.
*/
function backup_migrate_get_location($id) {
$locations = backup_migrate_get_locations('all');
return empty($locations[$id]) ? NULL : $locations[$id];
}
/**
* A base class for creating locations.
*/
class backup_migrate_location extends backup_migrate_item {
var $db_table = "backup_migrate_destinations";
var $type_name = "location";
var $default_values = array('settings' => array());
var $singular = 'location';
var $plural = 'locations';
var $title_plural = 'Locations';
var $title_singular = 'Location';
var $subtype = "";
var $supported_ops = 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('location');
t('locations');
t('Location');
t('Locations');
}
function ops() {
return $this->supported_ops;
}
/**
* Does this location support the given operation.
*/
function op($op) {
$ops = (array)$this->ops();
return in_array($op, $ops);
}
/**
* Remove the given op from the support list.
*/
function remove_op($op) {
$key = array_search($op, $this->supported_ops);
if ($key !== FALSE) {
unset($this->supported_ops[$key]);
}
}
function get_name() {
return @$this->name;
}
function set_name($name) {
return $this->name = $name;
}
function set_location($location) {
$this->location = $location;
}
function get_location() {
return @$this->location;
}
function get_display_location() {
return $this->get_location();
}
function settings($key = NULL) {
$out = $this->settings;
if ($key) {
$out = isset($out[$key]) ? $out[$key] : NULL;
}
return $out;
}
/**
* Get the type name of this location for display to the user.
*/
function get_subtype_name() {
if ($type = $this->get('subtype')) {
$types = $this->location_types();
return isset($types[$type]['type_name']) ? $types[$type]['type_name'] : $type;
}
}
/**
* Get the edit form for the item.
*/
function edit_form() {
if (!empty($this->supported_ops)) {
$form = parent::edit_form();
$form['subtype'] = array(
"#type" => "value",
"#default_value" => $this->get('subtype'),
);
}
else {
$types = $this->location_types();
$items = array();
// If no (valid) node type has been provided, display a node type overview.
foreach ($types as $key => $type) {
if (@$type['can_create']) {
$type_url_str = str_replace('_', '-', $key);
$out = '<dt>'. l($type['type_name'], BACKUP_MIGRATE_MENU_PATH . "/settings/$this->type_name/add/$type_url_str", array('attributes' => array('title' => t('Add a new @s location.', array('@s' => $type['type_name']))))) .'</dt>';
$out .= '<dd>'. filter_xss_admin($type['description']) .'</dd>';
$items[] = $out;
}
}
if (count($items)) {
$output = t('Choose the type of location you would like to create:') .'<dl>'. implode('', $items) .'</dl>';
}
else {
$output = t('No types available.');
}
$form['select_type'] = array(
'#type' => 'markup',
'#markup' => $output,
);
}
return $form;
}
/**
* Get the available location types.
*/
function location_types() {
return backup_migrate_get_location_subtypes();
}
/**
* 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 %name?', array('%name' => $this->get_name()));
}
/**
* 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')),
'subtype_name' => array('title' => t('Type')),
'display_location' => array('title' => t('Location')),
) + $out;
return $out;
}
/**
* Get a row of data to be used in a list of items of this type.
*/
function get_list_row() {
$out = parent::get_list_row();
// Suppress locations with no actions as there's no value in showing them (and they may confuse new users).
if (empty($out['actions'])) {
return NULL;
}
return $out;
}
/**
* Get the action links for a location.
*/
function get_action_links() {
$out = parent::get_action_links();
$item_id = $this->get_id();
// Don't display the download/delete/restore ops if they are not available for this location.
if ($this->op('list files') && user_access("access backup files")) {
$out = array('list files' => l(t("list files"), BACKUP_MIGRATE_MENU_PATH . "/$this->type_name/list/files/". $item_id)) + $out;
}
if (!$this->op('configure') || !user_access('administer backup and migrate')) {
unset($out['edit']);
}
return $out;
}
/**
* Determine if we can read the given file.
*/
function can_read_file($file_id) {
return $this->op('restore');
}
/**
* Get the form for the settings for this location type.
*/
function settings_default() {
return array();
}
/**
* Get the form for the settings for this location.
*/
function settings_form($form) {
return $form;
}
/**
* Validate the form for the settings for this location.
*/
function settings_form_validate($form_values) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function settings_form_submit($form_values) {
return $form_values;
}
/**
* 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) {
}
/**
* 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_values) {
}
/**
* Submit the settings form. Any values returned will be saved.
*/
function restore_settings_form_submit($form_values) {
return $form_values;
}
/**
* Create a new location of the correct type.
*/
function create($params = array()) {
$out = NULL;
$types = backup_migrate_get_location_subtypes();
// Get the type passed in in the params, or if none, check the url for a valid type name.
// This is to allow new location type to be specified in the path.
$location_type = !empty($params['subtype']) ? $params['subtype'] : NULL;
if ($location_type && ($type = @$types[$location_type])) {
// Include the necessary file if specified by the type.
if (!empty($type['file'])) {
require_once './'. $type['file'];
}
$out = new $type['class']($params + array('subtype' => $location_type));
}
if (empty($out)) {
$out = parent::create($params);
}
return $out;
}
/**
* Get a url from the parts.
*/
function url($hide_password = TRUE) {
return $this->glue_url($this->dest_url, $hide_password);
}
/**
* Glue a URLs component parts back into a URL.
*/
function glue_url($parts, $hide_password = TRUE) {
// Obscure the password if we need to.
$parts['pass'] = $hide_password ? "" : $parts['pass'];
// Assemble the URL.
$out = "";
$out .= $parts['scheme'] .'://';
$out .= $parts['user'] ? urlencode($parts['user']) : '';
$out .= ($parts['user'] && $parts['pass']) ? ":". urlencode($parts['pass']) : '';
$out .= ($parts['user'] || $parts['pass']) ? "@" : "";
$out .= $parts['host'];
$out .= !empty($parts['port']) ? ':'. $parts['port'] : '';
$out .= "/". $parts['path'];
return $out;
}
/**
* Break a URL into it's component parts.
*/
function set_url($url) {
$parts = (array)parse_url($url);
$parts['user'] = urldecode(@$parts['user']);
$parts['pass'] = urldecode(@$parts['pass']);
$parts['path'] = urldecode(@$parts['path']);
$parts['path'] = ltrim(@$parts['path'], "/");
$this->dest_url = $parts;
}
/**
* Retrieve a list of filetypes supported by this source/destination.
*/
function file_types() {
return array();
}
}
/**
* A base class for creating locations.
*/
class backup_migrate_location_remote extends backup_migrate_location {
/**
* The location is a URI so parse it and store the parts.
*/
function get_location() {
return $this->url(FALSE);
}
/**
* The location to display is the url without the password.
*/
function get_display_location() {
return $this->url(TRUE);
}
/**
* Return the location with the password.
*/
function set_location($location) {
$this->location = $location;
$this->set_url($location);
}
/**
* Get a url from the parts.
*/
function url($hide_password = TRUE) {
return $this->glue_url($this->dest_url, $hide_password);
}
/**
* Glue a URLs component parts back into a URL.
*/
function glue_url($parts, $hide_password = TRUE) {
// Obscure the password if we need to.
$parts['pass'] = $hide_password ? "" : $parts['pass'];
// Assemble the URL.
$out = "";
$out .= $parts['scheme'] .'://';
$out .= $parts['user'] ? urlencode($parts['user']) : '';
$out .= ($parts['user'] && $parts['pass']) ? ":". urlencode($parts['pass']) : '';
$out .= ($parts['user'] || $parts['pass']) ? "@" : "";
$out .= $parts['host'];
$out .= !empty($parts['port']) ? ':'. $parts['port'] : '';
$out .= "/". $parts['path'];
return $out;
}
/**
* Break a URL into it's component parts.
*/
function set_url($url) {
$parts = (array)parse_url($url);
$parts['user'] = urldecode(@$parts['user']);
$parts['pass'] = urldecode(@$parts['pass']);
$parts['path'] = urldecode(@$parts['path']);
$parts['path'] = ltrim(@$parts['path'], "/");
$this->dest_url = $parts;
}
/**
* location configuration callback.
*/
function edit_form() {
$form = parent::edit_form();
$form['scheme'] = array(
"#type" => "select",
"#title" => t("Scheme"),
"#default_value" => @$this->dest_url['scheme'] ? $this->dest_url['scheme'] : 'mysql',
"#required" => TRUE,
"#options" => array($GLOBALS['db_type'] => $GLOBALS['db_type']),
"#weight" => 0,
);
$form['host'] = array(
"#type" => "textfield",
"#title" => t("Host"),
"#default_value" => @$this->dest_url['host'] ? $this->dest_url['host'] : 'localhost',
"#required" => TRUE,
"#weight" => 10,
);
$form['path'] = array(
"#type" => "textfield",
"#title" => t("Path"),
"#default_value" => @$this->dest_url['path'],
"#required" => TRUE,
"#weight" => 20,
);
$form['user'] = array(
"#type" => "textfield",
"#title" => t("Username"),
"#default_value" => @$this->dest_url['user'],
"#required" => TRUE,
"#weight" => 30,
);
$form['pass'] = array(
"#type" => "password",
"#title" => t("Password"),
"#default_value" => @$this->dest_url['pass'],
'#description' => '',
"#weight" => 40,
);
if (@$this->dest_url['pass']) {
$form['old_password'] = array(
"#type" => "value",
"#value" => @$this->dest_url['pass'],
);
$form['pass']["#description"] .= t(' You do not need to enter a password unless you wish to change the currently saved password.');
}
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_submit($form, &$form_state) {
$form_state['values']['pass'] = $form_state['values']['pass'] ? $form_state['values']['pass'] : $form_state['values']['old_password'];
$form_state['values']['location'] = $this->glue_url($form_state['values'], FALSE);
parent::edit_form_submit($form, $form_state);
}
}

View file

@ -0,0 +1,388 @@
<?php
/**
* @file
* All of the settings profiles handling code for Backup and Migrate.
*/
backup_migrate_include('crud');
/**
* Implementation of hook_backup_migrate_profile_subtypes().
*
* Get the built in Backup and Migrate profile types.
*/
function backup_migrate_backup_migrate_profile_subtypes() {
$out = array();
$out += array(
'backup' => array(
'include' => 'profiles',
'type_name' => t('Backup Settings Profile'),
'class' => 'backup_migrate_profile',
),
);
return $out;
}
/**
* Get all the available backup profiles.
*/
function backup_migrate_get_profiles() {
backup_migrate_include('filters');
$profiles = &drupal_static('backup_migrate_get_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"), 'machine_name' => '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']['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']['filename']['#description'] = t('You can use tokens in the file name.');
}
$form['file']['append_timestamp'] = array(
"#type" => "checkbox",
"#title" => t("Append a timestamp."),
"#default_value" => $profile->append_timestamp,
);
$form['file']['timestamp_format_wrapper'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'append_timestamp' => TRUE,
),
);
$form['file']['timestamp_format_wrapper']['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 = 'settings profile';
var $plural = 'settings profiles';
var $title_plural = 'Settings Profiles';
var $title_singular = 'Settings Profile';
/**
* Perform a shallow merge of the defaults and the parameters.
*
* This is needed because otherwise it will *combine* the nested arrays and
* make it impossible to deselect database tables from the 'nodata' setting.
*
* @param array $params
*/
public function __construct(array $params = array()) {
$params = (array)$params;
$defaults = (array)$this->get_default_values();
foreach ($defaults as $key => $val) {
if (!isset($params[$key])) {
$params[$key] = $val;
}
}
$this->from_array($params);
}
/**
* 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('Settings Profile');
t('Settings Profiles');
t('settings profile');
t('settings 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;
}
/**
* 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('locations');
if (!empty($this->source_id) && (empty($this->source) || $this->source->get_id() !== $this->source_id)) {
$this->source = backup_migrate_get_source($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() {
$destinations = (array)$this->get_destinations();
return reset($destinations);
}
/**
* Get the destination of the profile.
*/
function get_destinations() {
backup_migrate_include('destinations');
if (empty($this->destinations)) {
$this->destinations = array();
$ids = $weights = array();
if (!empty($this->destination_id)) {
foreach ((array)$this->destination_id as $destination_id) {
if (!in_array($destination_id, $ids) && $destination = backup_migrate_get_destination($destination_id)) {
$this->destinations[] = $destination;
$weights[] = $destination->get('weight');
$ids[] = $destination_id;
}
}
}
// Sort the destinations by weight.
array_multisort($weights, SORT_NUMERIC, $this->destinations);
}
return $this->destinations;
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
$out = array();
foreach ($this->get_destinations() as $destination) {
$out[] = $destination->get_name();
}
if ($out) {
return implode(', ', $out);
}
return t("Missing");
}
/**
* Get the source and destinations specified in the given settings profile
*/
function get_all_locations() {
$out = array();
$out += $this->get('destinations');
$out[] = $this->get('source');
return $out;
}
/**
* 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,807 @@
<?php
/**
* @file
* All of the schedule handling code needed for Backup and Migrate.
*/
define('BACKUP_MIGRATE_KEEP_ALL', 0);
define('BACKUP_MIGRATE_STANDARD_DELETE', -1);
define('BACKUP_MIGRATE_SMART_DELETE', -2);
define('BACKUP_MIGRATE_CRON_BUILTIN', 'builtin');
define('BACKUP_MIGRATE_CRON_ELYSIA', 'elysia');
define('BACKUP_MIGRATE_CRON_NONE', 'none');
define('BACKUP_MIGRATE_SMART_KEEP_SUBHOURLY', 3600);
define('BACKUP_MIGRATE_SMART_KEEP_HOURLY', 24);
define('BACKUP_MIGRATE_SMART_KEEP_DAILY', 30);
define('BACKUP_MIGRATE_SMART_KEEP_WEEKLY', PHP_INT_MAX);
define('BACKUP_MIGRATE_KEEP_DEFAULT', 100);
backup_migrate_include('crud');
/**
* Implementation of hook_backup_migrate_destination_types().
*
* Get the built in Backup and Migrate destination types.
*/
function backup_migrate_backup_migrate_schedule_types() {
$out = array();
$out += array(
'backup' => array(
'include' => 'schedule',
'type_name' => t('Backup Schedule'),
'class' => 'backup_migrate_schedule',
),
);
return $out;
}
/**
* Run the preconfigured schedules. Called on cron.
*/
function backup_migrate_schedules_cron() {
backup_migrate_include('profiles');
foreach (backup_migrate_get_schedules() as $schedule) {
$schedule->cron();
}
backup_migrate_cleanup();
}
/**
* Run the preconfigured schedules regardless of scheduled time settings.
*/
function backup_migrate_schedules_run() {
backup_migrate_include('profiles');
foreach (backup_migrate_get_schedules() as $schedule) {
$schedule->run();
}
backup_migrate_cleanup();
}
/**
* Run the preconfigured schedules. Called on cron.
*/
function backup_migrate_schedule_run($schedule_id) {
backup_migrate_include('profiles');
if (($schedule = backup_migrate_get_schedule($schedule_id)) && $schedule->is_enabled()) {
$schedule->run();
}
backup_migrate_cleanup();
}
/**
* Get all the available backup schedules.
*/
function backup_migrate_get_schedules() {
$schedules = &drupal_static('backup_migrate_get_schedules');
// 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 $title_plural = 'Schedules';
var $title_singular = 'Schedule';
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' => BACKUP_MIGRATE_KEEP_ALL,
'period' => 60 * 60 * 24,
'storage' => BACKUP_MIGRATE_STORAGE_NONE,
'cron' => BACKUP_MIGRATE_CRON_BUILTIN,
'cron_schedule' => '0 4 * * *',
);
}
/**
* Return as an array of values.
*/
function to_array() {
$out = parent::to_array();
unset($out['last_run']);
return $out;
}
/**
* 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('Destinations'), '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 the columns needed to list the type.
*/
function get_settings_path() {
// Pull the schedules tab up a level to the top.
return BACKUP_MIGRATE_MENU_PATH . '/' . $this->type_name;
}
/**
* Get the menu items for manipulating this type.
*/
function get_menu_items() {
$items = parent::get_menu_items();
$path = $this->get_settings_path();
return $items;
}
/**
* 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) {
if (!is_array($field)) {
$row[$key] = array('data' => $field, 'class' => 'schedule-list-disabled');
}
else if (isset($row[$key]['class'])) {
$row[$key]['class'] .= ' schedule-list-disabled';
}
else {
$row[$key]['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() {
$destinations = (array)$this->get_destinations();
return reset($destinations);
}
/**
* Get the destination object of the schedule.
*/
function get_destination_ids() {
$out = array();
foreach (array('destination_id', 'copy_destination_id') as $key) {
if ($id = $this->get($key)) {
$out[$key] = $id;
}
}
return $out;
}
/**
* Get the destination object of the schedule.
*/
function get_destinations() {
backup_migrate_include('destinations');
$out = array();
foreach ($this->get_destination_ids() as $id) {
if ($dest = backup_migrate_get_destination($id)) {
$out[$id] = $dest;
}
}
return $out;
}
/**
* Get the destination object of the schedule.
*/
function get_destination_remote() {
backup_migrate_include('destinations');
return backup_migrate_get_destination($this->get('destination_remote_id'));
}
/**
* Get the destination object of the schedule.
*/
function get_destination_local() {
backup_migrate_include('destinations');
return backup_migrate_get_destination($this->get('destination_local_id'));
}
/**
* Get the name of the destination.
*/
function get_destination_name() {
if ($destinations = $this->get_destinations()) {
$out = array();
foreach ((array)$destinations as $destination) {
$out[] = check_plain($destination->get_name());
}
return implode(', ', $out);
}
return '<div class="row-error">'. t("Missing") .'</div>';
}
/**
* Get the destination of the schedule.
*/
function get_profile() {
backup_migrate_include('profiles');
if ($settings = backup_migrate_get_profile($this->get('profile_id'))) {
$settings->file_info = empty($settings->file_info) ? array() : $settings->file_info;
$settings->file_info += array(
'schedule_id' => $this->get_id(),
'schedule_name' => $this->get('name'),
);
}
return $settings;
}
/**
* 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();
$cron = $this->get('cron');
if ($cron == BACKUP_MIGRATE_CRON_BUILTIN) {
$out = format_plural(($this->period / $period['seconds']), $period['singular'], $period['plural']);
}
else if ($cron == BACKUP_MIGRATE_CRON_ELYSIA) {
$out = $this->get('cron_schedule');
}
else {
$out = t('None');
}
return $out;
}
/**
* Format the number to keep in human-readable form.
*/
function get_keep_description() {
return $this->generate_keep_description($this->keep);
}
/**
* Format a number to keep in human readable from
*/
function generate_keep_description($keep, $terse = TRUE) {
if ($keep == BACKUP_MIGRATE_KEEP_ALL) {
return t('all backups');
}
else if ($keep == BACKUP_MIGRATE_SMART_DELETE) {
$keep_hourly = variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY);
$keep_daily = variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY);
$keep_weekly = variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY);
if ($terse) {
return t('!hours hourly, !days daily, !weeks weekly backups',
array(
'!hours' => $keep_hourly == PHP_INT_MAX ? t('all') : $keep_hourly,
'!days' => $keep_daily == PHP_INT_MAX ? t('all') : $keep_daily,
'!weeks' => $keep_weekly == PHP_INT_MAX ? t('all') : $keep_weekly,
));
}
else {
return t('hourly backups !hours, daily backups !days and weekly backups !weeks',
array(
'!hours' => $keep_hourly == PHP_INT_MAX ? t('forever') : format_plural($keep_hourly, 'for 1 hour', 'for the past @count hours'),
'!days' => $keep_daily == PHP_INT_MAX ? t('forever') : format_plural($keep_daily, 'for 1 day', 'for the past @count days'),
'!weeks' => $keep_weekly == PHP_INT_MAX ? t('forever') : format_plural($keep_weekly, 'for 1 week', 'for the past @count weeks'),
)
);
}
}
return format_plural($keep, 'last 1 backup', 'last @count backups');
}
/**
* 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', 'sources', 'profiles');
$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 . '/settings/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['enabled'] = array(
'#type' => "checkbox",
'#title' => t('Enabled'),
'#default_value' => $this->get('enabled'),
);
$form['cron_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'enabled' => TRUE,
),
);
$cron = $this->get('cron');
$form['cron_settings']['cron_builtin'] = array(
"#type" => "radio",
"#title" => t('Run using Drupal\'s cron'),
'#return_value' => BACKUP_MIGRATE_CRON_BUILTIN,
"#description" => t('Run this schedule when !cron runs.', array('!cron' => l(t('your cron task'), 'http://drupal.org/cron'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
$form['cron_settings']['period_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'cron' => BACKUP_MIGRATE_CRON_BUILTIN,
),
);
$form['cron_settings']['period_settings']['period'] = array(
"#type" => "item",
"#title" => t("Backup every"),
"#prefix" => '<div class="container-inline">',
"#suffix" => '</div>',
"#tree" => TRUE,
'#parents' => array('period'),
);
$form['cron_settings']['period_settings']['period']['number'] = array(
"#type" => "textfield",
"#size" => 6,
"#default_value" => $default_period_num,
'#parents' => array('period', 'number'),
);
$form['cron_settings']['period_settings']['period']['type'] = array(
"#type" => "select",
"#options" => $period_options,
"#default_value" => $default_period['type'],
'#parents' => array('period', 'type'),
);
$form['cron_settings']['cron_elysia'] = array(
"#type" => "radio",
"#title" => t('Run using Elysia cron'),
'#return_value' => BACKUP_MIGRATE_CRON_ELYSIA,
"#description" => t('You can specify exactly when this schedule should run using !elysia.', array('!elysia' => l(t('the Elysia Cron module'), 'http://drupal.org/project/elysia_cron'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
if (!module_exists('elysia_cron') && !module_exists('ultimate_cron')) {
$form['cron_settings']['cron_elysia']['#disabled'] = TRUE;
$form['cron_settings']['cron_elysia']['#description'] .= ' ' . t('Install !elysia to enable this option.', array('!elysia' => l(t('Elysia Cron'), 'http://drupal.org/project/elysia_cron')));
}
$form['cron_settings']['cron_schedule_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'cron' => BACKUP_MIGRATE_CRON_ELYSIA,
),
);
$form['cron_settings']['cron_schedule_settings']['cron_schedule'] = array(
"#type" => "textfield",
"#title" => t('Cron Schedule'),
'#length' => 10,
"#description" => t('Specify the frequecy of the schedule using standard cron notation. For more information see the !elysiareadme.', array('!elysiareadme' => l(t('the Elysia Cron README'), 'http://drupalcode.org/project/elysia_cron.git/blob/refs/heads/7.x-1.x:/README.txt'))),
"#default_value" => $this->get('cron_schedule'),
'#parents' => array('cron_schedule'),
);
$form['cron_settings']['cron_none'] = array(
"#type" => "radio",
"#title" => t('Do not run automatically'),
'#return_value' => 'none',
"#description" => t('Do not run this schedule automatically. You can still run it using !drush.', array('!drush' => l(t('Drush'), 'http://drupal.org/project/drush'))),
"#default_value" => $cron ? $cron : BACKUP_MIGRATE_CRON_BUILTIN,
'#parents' => array('cron'),
);
$keep = $this->get('keep');
$form['delete'] = array(
'#type' => 'checkbox',
'#default_value' => $keep != 0,
'#title' => t('Automatically delete old backups'),
);
$form['delete_settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'delete' => TRUE,
),
);
$keep_hourly = variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY);
$keep_daily = variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY);
$keep_weekly = variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY);
$form['delete_settings']['smartdelete'] = array(
"#type" => "radio",
"#title" => t('Smart Delete'),
'#return_value' => BACKUP_MIGRATE_SMART_DELETE,
"#description" => t('Keep !keep. <strong>Recommended</strong>', array('!keep' => $this->generate_keep_description(BACKUP_MIGRATE_SMART_DELETE, FALSE))),
"#default_value" => $keep ? $keep : BACKUP_MIGRATE_SMART_DELETE,
'#parents' => array('deletetype'),
);
$form['delete_settings']['standarddelete'] = array(
"#type" => "radio",
"#title" => t('Simple Delete'),
'#return_value' => BACKUP_MIGRATE_STANDARD_DELETE,
"#description" => t("Keep a specified number of files deleting the oldest ones first."),
"#default_value" => $keep > 0 ? BACKUP_MIGRATE_STANDARD_DELETE : 0,
'#parents' => array('deletetype'),
);
$form['delete_settings']['keep-settings'] = array(
'#type' => 'backup_migrate_dependent',
'#dependencies' => array(
'deletetype' => BACKUP_MIGRATE_STANDARD_DELETE,
),
);
$form['delete_settings']['keep-settings']['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."),
"#default_value" => $keep > 0 ? $keep : BACKUP_MIGRATE_KEEP_DEFAULT,
);
$form['destination'] = _backup_migrate_get_destination_pulldown('scheduled backup', $this->get('destination_id'), $this->get('copy_destination_id'));
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 (!$form_state['values']['delete']) {
$form_state['values']['keep'] = 0;
}
else if ($form_state['values']['deletetype'] == BACKUP_MIGRATE_SMART_DELETE) {
$form_state['values']['keep'] = BACKUP_MIGRATE_SMART_DELETE;
}
else if (!is_numeric($form_state['values']['keep']) || $form_state['values']['keep'] <= 0) {
form_set_error('keep', t('Number to keep must be a number greater than 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 schedule %name? Backups made with this schedule will not be deleted.', 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));
$cron = $this->get('cron');
if ($cron == BACKUP_MIGRATE_CRON_BUILTIN && $this->is_enabled() && ($now - $this->get('last_run')) >= $wait_time) {
$this->run();
}
}
/**
* Run the actual schedule.
*/
function run() {
// Clear cached profile data which could have been altered by previous
// schedule run; see #2672478
drupal_static_reset('backup_migrate_get_profiles');
if ($settings = $this->get_profile()) {
$settings->source_id = $this->get('source_id');
$settings->destination_id = $this->get('destination_ids');
$this->update_last_run(time());
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() {
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() {
backup_migrate_include('destinations');
$num_to_keep = $this->keep;
// If num to keep is not 0 (0 is infinity).
foreach ((array)$this->get_destinations() as $destination) {
if ($destination && $destination->op('delete') && $destination_files = $destination->list_files()) {
if ($num_to_keep == BACKUP_MIGRATE_SMART_DELETE) {
$this->smart_delete_backups(
$destination,
$destination_files,
variable_get('backup_migrate_smart_keep_subhourly', BACKUP_MIGRATE_SMART_KEEP_SUBHOURLY),
variable_get('backup_migrate_smart_keep_hourly', BACKUP_MIGRATE_SMART_KEEP_HOURLY),
variable_get('backup_migrate_smart_keep_daily', BACKUP_MIGRATE_SMART_KEEP_DAILY),
variable_get('backup_migrate_smart_keep_weekly', BACKUP_MIGRATE_SMART_KEEP_WEEKLY)
);
}
else if ($num_to_keep != BACKUP_MIGRATE_KEEP_ALL) {
$this->delete_backups($destination, $destination_files, $num_to_keep);
}
}
}
}
/**
* Remove older backups keeping only the number specified by the aministrator.
*/
function delete_backups($destination, $files, $num_to_keep) {
backup_migrate_include('destinations');
$num_to_keep = $this->keep;
// Sort the files by modified time.
$i = 0;
foreach ($files as $id => $file) {
if ($file->is_recognized_type()) {
$time = $file->info('filetime');
$sorted[$id] = $time;
}
}
asort($sorted);
// 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;
// Delete from the start of the list (earliest).
foreach ($sorted as $id => $time) {
if (!$num_to_delete--) {
break;
}
$destination->delete_file($id);
}
}
}
/**
* Delete files keeping the specified number of hourly, daily, weekly and monthly backups.
*/
function smart_delete_backups($destination, $files, $keep_subhourly = 3600, $keep_hourly = 24, $keep_daily = 14, $keep_weekly = PHP_INT_MAX, $keep_monthly = PHP_INT_MAX) {
$now = time();
$periods = array(
'subhourly' => array(
'delta' => 1,
'keep' => $keep_subhourly,
'last_time' => 0,
'files' => array(),
),
'hourly' => array(
'delta' => 60*60,
'keep' => $keep_hourly,
'last_time' => 0,
'files' => array(),
),
'daily' => array(
'delta' => 60*60*24,
'keep' => $keep_daily,
'last_time' => 0,
'files' => array(),
),
'weekly' => array(
'delta' => 60*60*24*7,
'keep' => $keep_weekly,
'last_time' => 0,
'files' => array(),
),
/*
'monthly' => array(
'delta' => 60*60*24*7*4,
'keep' => $keep_monthly,
'last_time' => 0,
'files' => array(),
),
*/
);
$keep_files = $filetimes = $times = $groups = $sorted = $saved = array();
foreach ($files as $id => $file) {
if ($file->is_recognized_type()) {
$time = $file->info('filetime');
$sorted[$id] = $time;
}
}
arsort($sorted);
$now = time();
foreach ($periods as $i => $period) {
foreach ($sorted as $id => $time) {
if ($time < ($now - ($period['delta'] * $period['keep']))) {
break;
}
if ($period['last_time'] == 0 || $time <= ($period['last_time'] - $period['delta'])) {
$period['last_time'] = $time;
$keep_files[$id] = $id;
}
}
// Keep oldest backup or it will get deleted if it doesn't fall on an exact multiple of the period
if ($id) {
$keep_files[$id] = $id;
}
}
// Do the delete.
foreach ($files as $id => $file) {
if (!isset($keep_files[$id])) {
$destination->delete_file($file->file_id());
}
}
}
}

View file

@ -0,0 +1,287 @@
<?php
backup_migrate_include('sources.filesource');
/**
* @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_files_destination_archivesource extends backup_migrate_destination_filesource {
var $supported_ops = array('source');
function type_name() {
return t("Site Archive Source");
}
/**
* Declare the current files directory as a backup source..
*/
function sources() {
$out = array();
$out['archive'] = backup_migrate_create_destination('archive', array('machine_name' => 'archive', 'location' => '.', 'name' => t('Entire Site (code, files & DB)'), 'show_in_list' => FALSE));
return $out;
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
return array(
"sitearchive" => array(
"extension" => "sitearchive.tar",
"filemime" => "application/x-tar",
"backup" => TRUE,
"restore" => FALSE,
),
);
}
/**
* Get the form for the settings for this destination.
*/
function backup_settings_default() {
$out = parent::backup_settings_default();
$excludes = explode("\n", $out['exclude_filepaths']);
foreach ($excludes as $i => $exclude) {
$excludes[$i] = 'public://' . $exclude;
}
$excludes[] = 'private://backup_migrate';
$excludes[] = conf_path() . '/settings.php';
$excludes[] = file_directory_temp();
return array(
'exclude_filepaths' => implode("\n", $excludes),
);
}
/**
* Backup from this source.
*/
function _backup_to_file_php($file, $settings) {
if ($this->check_libs()) {
$base_dir = $this->get_realpath();
$excluded_paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
$exclude = $this->get_excluded_paths($settings);
$files = $this->get_files_to_backup($this->get_realpath(), $settings, $exclude);
if ($files) {
$manifest = $this->generate_manifest();
$db = $this->get_db();
$file->push_type('sitearchive');
$gz = new Archive_Tar($file->filepath(), false);
$gz->addModify(array($manifest), $file->name .'/', dirname($manifest));
$gz->addModify($files, $file->name .'/docroot', $base_dir);
$gz->addModify($db, $file->name . '/', dirname($db));
unlink($manifest);
rmdir(dirname($manifest));
unlink($db);
rmdir(dirname($db));
return $file;
}
backup_migrate_backup_fail('No files available.', array(), $settings);
return FALSE;
}
return FALSE;
}
/**
* Backup from this source.
*/
function _backup_to_file_cli($file, $settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec') && function_exists('escapeshellarg')) {
$excluded_paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
foreach ($this->get_excluded_paths($excluded_paths) as $path) {
$exclude[] = '--exclude=' . escapeshellarg($path);
}
$exclude = implode(' ', $exclude);
// Create a symlink in a temp directory so we can rename the file in the archive.
$temp = backup_migrate_temp_directory();
$manifest = $this->generate_manifest();
$db = $this->get_db();
rename($db, $temp . '/database.sql');
rename($manifest, $temp . '/MANIFEST.ini');
$file->push_type('sitearchive');
$link = $temp . '/docroot';
$input = realpath($this->get_location());
backup_migrate_exec("ln -s %input %link; tar --dereference -C %temp -rf %output $exclude .", array('%output' => $file->filepath(), '%input' => $input, '%temp' => $temp, '%link' => $link));
return $file;
}
return FALSE;
}
/**
* Generate a manifest file.
*/
function generate_manifest() {
$info = array(
'Global' => array(
'datestamp' => time(),
'formatversion' => '2011-07-02',
'generator' => 'Backup and Migrate (http://drupal.org/project/backup_migrate)',
'generatorversion' => BACKUP_MIGRATE_VERSION,
),
'Site 0' => array(
'version' => VERSION,
'name' => variable_get('site_name', ''),
'docroot' => 'docroot',
'sitedir' => 'docroot/' . conf_path(),
'database-file-default' => 'database.sql',
'database-file-driver' => 'mysql',
),
);
if ($private = variable_get('file_private_path', FALSE)) {
$info['Site 0']['files-private'] = 'docroot/' . $private;
}
$info['Site 0']['files-public'] = 'docroot/' . variable_get('file_public_path', FALSE);
$ini = $this->_array_to_ini($info);
$tmpdir = backup_migrate_temp_directory();
$filepath = $tmpdir . '/MANIFEST.ini';
file_put_contents($filepath, $ini);
return $filepath;
}
/**
* Get a database dump to add to the archive.
*/
function get_db() {
backup_migrate_include('destinations', 'files', 'filters', 'profiles');
$file = new backup_file();
// Clone the default settings so we can make changes without them leaking out of this function.
$settings = clone _backup_migrate_profile_saved_default_profile();
$settings->source_id = 'db';
$settings->filters['compression'] = 'none';
// Execute the backup on the db with the default settings.
$file = backup_migrate_filters_backup($file, $settings);
// Generate a tmp file with the correct final title (because ArchiveTar doesn't seem to allow renaming).
$tmpdir = backup_migrate_temp_directory();
$filepath = $tmpdir . '/database.sql';
rename($file->filepath(), $filepath);
return $filepath;
}
/**
* Restore to this source.
*/
function _restore_from_file_php($file, &$settings) {
$success = false;
if ($this->check_libs()) {
$from = $file->pop_type();
$temp = backup_migrate_temp_directory();
$tar = new Archive_Tar($from->filepath());
$tar->extractModify($temp, $file->name);
// Parse the manifest
$manifest = $this->read_manifest($temp);
// Currently only the first site in the archive is supported.
$site = $manifest['Site 0'];
$docroot = $temp . '/' . $site['docroot'];
$sqlfile = $temp . '/' . $site['database-file-default'];
$filepath = NULL;
if (isset($site['files-private'])) {
$filepath = $temp . '/' . $site['files-private'];
}
else if (isset($site['files-public'])) {
$filepath = $temp . '/' . $site['files-public'];
}
// Move the files from the temp directory.
if ($filepath && file_exists($filepath)) {
_backup_migrate_move_files($filepath, variable_get('file_public_path', conf_path() . '/files') );
}
else {
_backup_migrate_message('Files were not restored because the archive did not seem to contain a files directory or was in a format that Backup and Migrate couldn\'t read', array(), 'warning');
}
// Restore the sql db.
if ($sqlfile && file_exists($sqlfile)) {
$db_settings = clone $settings;
$db_settings->source_id = 'db';
$file = new backup_file(array('filepath' => $sqlfile));
$success = backup_migrate_filters_restore($file, $db_settings);
}
else {
_backup_migrate_message('The database was not restored because the archive did not seem to contain a database backup or was in a format that Backup and Migrate couldn\'t read', array(), 'warning');
}
if ($docroot) {
_backup_migrate_message('Backup and Migrate cannot restore the php code of the site for security reasons. You will have to copy the code to the server by hand if you wish to restore the full site.', array(), 'warning');
}
return $success && $file;
}
return FALSE;
}
/**
* Restore to this source.
*/
function _restore_from_file_cli($file, &$settings) {
// @TODO: implement the cli version of the restore.
return FALSE;
}
/**
* Generate a manifest file.
*/
function read_manifest($directory) {
// Assume some defaults if values ore the manifest is missing.
$defaults = array(
'docroot' => 'docroot',
'database-file-default' => 'database.sql',
'database-file-driver' => 'mysql',
);
$out = $this->_ini_to_array($directory . '/MANIFEST.ini');
// Set the defaults.
$out['Site 0'] = isset($out['Site 0']) ? $out['Site 0'] : array();
$out['Site 0'] += $defaults;
return $out;
}
/**
* Convert an associated array to an ini format string. Only allows 2 levels of depth to allow parse_ini_file to parse.
*/
function _array_to_ini($sections) {
$content = "";
foreach ($sections as $section => $data) {
$content .= '['. $section .']' . "\n";
foreach ($data as $key => $val) {
$content .= $key . " = \"". $val ."\"\n";
}
$content .= "\n";
}
return $content;
}
/**
* Convert an associated array to an ini format string. Only allows 2 levels of depth to allow parse_ini_file to parse.
*/
function _ini_to_array($path) {
return parse_ini_file($path, TRUE);
}
}

View file

@ -0,0 +1,325 @@
<?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_source_db extends backup_migrate_source_remote {
var $supported_ops = array('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']['#default_value'] = $this->default_scheme();
$form['scheme']['#access'] = FALSE;
$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 default settings for this object.
*
* @return array
* 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 as access log and watchdog).
*/
function backup_settings_default() {
$all_tables = $this->_get_table_names();
// Basic modules that should be excluded.
$basic = array(
// Default core tables.
'accesslog',
'sessions',
'watchdog',
// Search module.
'search_dataset',
'search_index',
'search_keywords_log',
'search_total',
// Devel module.
'devel_queries',
'devel_times',
);
// Identify all cache tables.
$cache = array('cache');
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'cache_') === 0) {
$cache[] = $table_name;
}
}
// Simpletest can create a lot of tables that do not need to be backed up,
// but all of them start with the string 'simpletest' so they can be easily
// excluded.
$simpletest = array();
foreach ($all_tables as $table_name) {
if (strpos($table_name, 'simpletest') === 0) {
$simpletest[] = $table_name;
}
}
return array(
'nodata_tables' => drupal_map_assoc(array_merge($basic, $cache, module_invoke_all('devel_caches'))),
'exclude_tables' => $simpletest,
'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."),
);
$form['nodata_tables'] = array(
"#type" => "select",
"#multiple" => TRUE,
"#title" => t("Exclude the data from the following tables"),
"#options" => $objects,
"#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());
//$this->lock_tables($settings);
// Switch to a different db if specified.
$success = $this->_backup_db_to_file($file, $settings);
//$this->unlock_tables($settings);
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';
}
/**
* Get the version info for the given DB.
*/
function _db_info() {
return array(
'type' => FALSE,
'version' => t('Unknown'),
);
}
}

View file

@ -0,0 +1,497 @@
<?php
backup_migrate_include('sources.db');
/**
* @file
* Functions to handle the direct to database source.
*/
/**
* A source type for backing up from database server.
*
* @ingroup backup_migrate_destinations
*/
class backup_migrate_source_db_mysql extends backup_migrate_source_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,
),
);
}
/**
* Return the scheme for this db type.
*/
function default_scheme() {
return 'mysql';
}
/**
* Declare any mysql databases defined in the settings.php file as a possible source.
*/
function sources() {
$out = array();
global $databases;
foreach ((array)$databases as $db_key => $target) {
foreach ((array)$target as $tgt_key => $info) {
// Only mysql/mysqli supported by this source.
$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 ($source = 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') {
$source->set_id('db');
$source->set_name(t('Default Database'));
// Dissalow backing up to the default database because that's confusing and potentially dangerous.
$source->remove_op('scheduled backup');
$source->remove_op('manual backup');
}
else {
$source->set_id('db:'. $key);
$source->set_name($key .": ". $source->get_display_location());
}
$out[$source->get_id()] = $source;
}
}
}
}
return $out;
}
/**
* Get the file type for to backup this source to.
*/
function get_file_type_id() {
return 'mysql';
}
/**
* 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_cli']) && $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' => isset($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.
if (!empty($settings->filters['exclude_tables'])) {
$db = $this->dest_url['path'];
foreach ((array)$settings->filters['exclude_tables'] as $table) {
if (isset($alltables[$table])) {
$command .= ' --ignore-table='. $db .'.'. $table;
}
}
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()) {
$first2 = substr($line, 0, 2);
$first3 = substr($line, 0, 3);
// Ignore single line comments. This function doesn't support multiline comments or inline comments.
if ($first2 != '--' && ($first2 != '/*' || $first3 == '/*!')) {
$out .= ' ' . trim($line);
// If a line ends in ; or */ it is a sql command.
if (substr($out, strlen($out) - 1, 1) == ';') {
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 view.
*/
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) {
// 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 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 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 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() {
$info = $this->_db_info();
return "-- Backup and Migrate (Drupal) MySQL Dump
-- Backup and Migrate Version: ". BACKUP_MIGRATE_VERSION ."
-- http://drupal.org/project/backup_migrate
-- Drupal Version: " . VERSION . "
-- http://drupal.org/
--
-- Host: " . url('', array('absolute' => TRUE)) . "
-- Site Name: " . url('', array('absolute' => TRUE)) . "
-- Generation Time: " . format_date(time(), 'custom', 'r') . "
-- MySQL Version: " . $info['version'] . "
/*!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 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 */;
";
}
/**
* Get the version info for the given DB.
*/
function _db_info() {
$db = $this->_get_db_connection();
return array(
'type' => 'mysql',
'version' => $db ? $db->version() : t('Unknown'),
);
}
}

View file

@ -0,0 +1,314 @@
<?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_filesource extends backup_migrate_source {
var $supported_ops = array('restore', 'configure', 'delete', 'source');
function type_name() {
return t("Files Directory");
}
/**
* Declare the current files directory as a backup source..
*/
function sources() {
$out = array();
$out['files'] = backup_migrate_create_destination('filesource', array('machine_name' => 'files', 'location' => 'public://', 'name' => t('Public Files Directory'), 'show_in_list' => FALSE));
if (variable_get('file_private_path', FALSE)) {
$out['files_private'] = backup_migrate_create_destination('filesource', array('machine_name' => 'files', 'location' => 'private://', 'name' => t('Private Files Directory'), 'show_in_list' => FALSE));
}
return $out;
}
/**
* 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 back up. Use a relative path to pick a path relative to your Drupal root directory. The web server must be able to read from this path.'),
);
return $form;
}
/**
* Return a list of backup filetypes.
*/
function file_types() {
return array(
"tar" => array(
"extension" => "tar",
"filemime" => "application/x-tar",
"backup" => TRUE,
"restore" => TRUE,
),
);
}
/**
* Get the form for the settings for this destination.
*
* Return the default directories whose data can be ignored. These directories contain
* info which can be easily reproducted. Also exclude the backup and migrate folder
* to prevent exponential bloat.
*/
function backup_settings_default() {
return array(
'exclude_filepaths' => "backup_migrate\nstyles\ncss\njs\nctools\nless",
);
}
/**
* Get the form for the backup settings for this destination.
*/
function backup_settings_form($settings) {
$form['exclude_filepaths'] = array(
"#type" => "textarea",
"#multiple" => TRUE,
"#title" => t("Exclude the following files or directories"),
"#default_value" => $settings['exclude_filepaths'],
"#description" => t("A list of files or directories to be excluded from backups. Add one path per line relative to the directory being backed up."),
);
return $form;
}
/**
* Backup from this source.
*/
function backup_to_file($file, $settings) {
if ($out = $this->_backup_to_file_cli($file, $settings)) {
return $out;
}
else {
return $this->_backup_to_file_php($file, $settings);
}
}
/**
* Backup from this source.
*/
function _backup_to_file_php($file, $settings) {
if ($this->check_libs()) {
$excluded = $this->get_excluded_paths($settings);
$files = $this->get_files_to_backup($this->get_realpath(), $settings, $excluded);
if ($files) {
$file->push_type('tar');
$gz = new Archive_Tar($file->filepath(), false);
$gz->addModify($files, '', $this->get_realpath());
return $file;
}
backup_migrate_backup_fail('No files available.', array(), $settings);
return FALSE;
}
return FALSE;
}
/**
* Backup from this source.
*/
function _backup_to_file_cli($file, $settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec') && function_exists('escapeshellarg')) {
$excluded = $this->get_excluded_paths($settings);
$exclude = array();
foreach ($excluded as $path) {
$exclude[] = '--exclude=' . escapeshellarg($path);
}
$exclude = implode(' ', $exclude);
// Create a symlink in a temp directory so we can rename the file in the archive.
$temp = backup_migrate_temp_directory();
$file->push_type('tar');
backup_migrate_exec("tar --dereference -C %input -rf %output $exclude .", array('%output' => $file->filepath(), '%input' => $this->get_realpath(), '%temp' => $temp));
return $file;
}
return FALSE;
}
/**
* Restore to this source.
*/
function restore_from_file($file, &$settings) {
if ($out = $this->_restore_from_file_cli($file, $settings)) {
return $out;
}
else {
return $this->_restore_from_file_php($file, $settings);
}
}
/**
* Restore to this source.
*/
function _restore_from_file_php($file, &$settings) {
if ($this->check_libs()) {
$from = $file->pop_type();
$temp = backup_migrate_temp_directory();
$tar = new Archive_Tar($from->filepath());
$tar->extractModify($temp, $file->name);
// Older B&M Files format included a base 'files' directory.
if (file_exists($temp .'/files')) {
$temp = $temp . '/files';
}
if (file_exists($temp .'/'. $file->name .'/files')) {
$temp = $temp . '/files';
}
// Move the files from the temp directory.
_backup_migrate_move_files($temp, $this->get_realpath());
return $file;
}
return FALSE;
}
/**
* Restore to this source.
*/
function _restore_from_file_cli($file, &$settings) {
if (!empty($settings->filters['use_cli']) && function_exists('backup_migrate_exec')) {
$temp = backup_migrate_temp_directory();
backup_migrate_exec("tar -C %temp -xf %input", array('%input' => $file->filepath(), '%temp' => $temp));
// Older B&M Files format included a base 'files' directory.
if (file_exists($temp .'/files')) {
$temp = $temp . '/files';
}
if (file_exists($temp .'/'. $file->name .'/files')) {
$temp = $temp . '/files';
}
// Move the files from the temp directory.
backup_migrate_exec("mv -rf %temp/* %output", array('%output' => $this->get_realpath(), '%temp' => $temp));
return $file;
}
return FALSE;
}
/**
* Get a list of files to backup from the given set if dirs. Exclude any that match the array $exclude.
*/
function get_files_to_backup($dir, $settings, $exclude = array()) {
$out = $errors = array();
if (!file_exists($dir)) {
backup_migrate_backup_fail('Directory %dir does not exist.', array('%dir' => $dir), $settings);
return FALSE;
}
if ($handle = @opendir($dir)) {
while (($file = readdir($handle)) !== FALSE) {
if ($file != '.' && $file != '..' && !in_array($file, $exclude)) {
$real = realpath($dir . '/' . $file);
// If the path is not excluded.
if (!in_array($real, $exclude)) {
if (is_dir($real)) {
$subdir = $this->get_files_to_backup($real, $settings, $exclude);
// If there was an error reading the subdirectory then abort the backup.
if ($subdir === FALSE) {
closedir($handle);
return FALSE;
}
// If the directory is empty, add an empty directory.
if (count($subdir) == 0) {
$out[] = $real;
}
$out = array_merge($out, $subdir);
}
else {
if (is_readable($real)) {
$out[] = $real;
}
else {
$errors[] = $dir . '/' . $file;
}
}
}
}
}
closedir($handle);
}
else {
backup_migrate_backup_fail('Could not open directory %dir', array('%dir' => $dir), $settings);
return FALSE;
}
// Alert the user to any errors there might have been.
if ($errors) {
if (count($errors < 5)) {
$filesmsg = t('The following files: !files', array('!files' => theme('item_list', array('items' => $errors))));
}
else {
$filesmsg = t('!count files', array('!count' => count($errors)));
}
if (empty($settings->filters['ignore_errors'])) {
backup_migrate_backup_fail('The backup could not be completed because !files could not be read. If you want to skip unreadable files use the \'Ignore Errors\' setting under \'Advanced Options\' in \'Advanced Backup\' or in your schedule settings profile.', array('!files' => $filesmsg), 'error');
$out = FALSE;
}
else {
backup_migrate_backup_fail('!files could not be read and were skipped', array('!files' => $filesmsg), 'error');
}
}
return $out;
}
/**
* Break the excpluded paths string into a usable list of paths.
*/
function get_excluded_paths($settings) {
$base_dir = $this->get_realpath() . '/';
$paths = empty($settings->filters['exclude_filepaths']) ? '' : $settings->filters['exclude_filepaths'];
$out = explode("\n", $paths);
foreach ($out as $key => $val) {
$path = trim($val, "/ \t\r\n");
// If the path specified is a stream url or absolute path add the normalized version.
if ($real = drupal_realpath($path)) {
$out[$key] = $real;
}
// If the path is a relative path add it.
else if ($real = drupal_realpath($base_dir . $path)) {
$out[$key] = $real;
}
// Otherwise add it as is even though it probably won't match any files.
else {
$out[$key] = $path;
}
}
return $out;
}
/**
* Check that the required libraries are installed.
*/
function check_libs() {
$result = true;
// Drupal 7 has Archive_Tar built in so there should be no need to include anything here.
return $result;
}
/**
* Get the file location.
*/
function get_realpath() {
return drupal_realpath($this->get_location());
}
}

View file

@ -0,0 +1,268 @@
<?php
/**
* @file
* All of the source handling code needed for Backup and Migrate.
*/
backup_migrate_include('crud', 'locations', 'destinations');
/**
* Get all the available backup sources.
*/
function backup_migrate_get_sources() {
return backup_migrate_crud_get_items('source');
}
/**
* Get the available source types.
*/
function backup_migrate_get_source_subtypes() {
return backup_migrate_crud_subtypes('source');
}
/**
* Get the destination of the given id.
*/
function backup_migrate_get_source($id) {
$sources = backup_migrate_get_sources();
return empty($sources[$id]) ? NULL : $sources[$id];
}
/**
* Create a source object of the given type with the given params.
*/
function backup_migrate_create_source($subtype, $params = array()) {
$params['subtype'] = $subtype;
return backup_migrate_crud_create_item('source', $params);
}
/**
* Implementation of hook_backup_migrate_source_subtypes().
*
* Get the built in Backup and Migrate source types.
*/
function backup_migrate_backup_migrate_source_subtypes() {
$out = array();
$out += array(
'db' => array(
'type_name' => t('Database'),
'description' => t('Import the backup directly into another database. Database sources can also be used as a source to backup from.'),
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/sources.db.inc',
'class' => 'backup_migrate_source_db',
'can_create' => FALSE,
),
'mysql' => array(
'type_name' => t('MySQL Database'),
'description' => t('Import the backup directly into another MySQL database. Database sources can also be used as a source to backup from.'),
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/sources.db.mysql.inc',
'class' => 'backup_migrate_source_db_mysql',
'can_create' => TRUE,
),
'filesource' => array(
'description' => t('A files directory which can be backed up from.'),
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/sources.filesource.inc',
'class' => 'backup_migrate_destination_filesource',
'type_name' => t('File Directory'),
'can_create' => TRUE,
),
'archive' => array(
'description' => t('Create an archive of your entire site.'),
'file' => drupal_get_path('module', 'backup_migrate') .'/includes/sources.archivesource.inc',
'class' => 'backup_migrate_files_destination_archivesource',
'type_name' => t('Site Archive'),
'can_create' => FALSE,
),
);
return $out;
}
/**
* Implementation of hook_backup_migrate_sources().
*
* Get the built in backup sources and those in the db.
*/
function backup_migrate_backup_migrate_sources() {
$out = array();
// Expose the configured databases as sources.
backup_migrate_include('filters');
$out += backup_migrate_filters_invoke_all('sources');
return $out;
}
/**
* Get the source options as a form element.
*/
function _backup_migrate_get_source_form($source_id = 'db') {
backup_migrate_include('destinations');
$form = array();
$sources = _backup_migrate_get_source_pulldown($source_id);
if (count($sources['#options']) > 1) {
$form['source'] = array(
"#type" => "fieldset",
"#title" => t("Backup Source"),
"#collapsible" => TRUE,
"#collapsed" => FALSE,
"#tree" => FALSE,
);
$sources['#description'] = t("Choose the database to backup. Any database destinations you have created and any databases specified in your settings.php can be backed up.");
$form['source']['source_id'] = $sources;
}
else {
$form = array();
$form['source']['source_id'] = array(
"#type" => "value",
"#value" => $source_id,
);
}
return $form;
}
/**
* Get pulldown to select existing source options.
*/
function _backup_migrate_get_source_pulldown($source_id = NULL) {
$sources = _backup_migrate_get_source_form_item_options();
$form = array(
"#type" => "select",
"#title" => t("Backup Source"),
"#options" => _backup_migrate_get_source_form_item_options(),
"#default_value" => $source_id,
);
return $form;
}
/**
* Get the location options as an options array for a form item.
*/
function _backup_migrate_get_source_form_item_options() {
$out = array();
foreach (backup_migrate_get_sources() as $key => $location) {
$out[$key] = $location->get_name();
}
return $out;
}
/**
* A base class for creating sources.
*/
class backup_migrate_source extends backup_migrate_location {
var $db_table = "backup_migrate_sources";
var $type_name = 'source';
var $singular = 'source';
var $plural = 'sources';
var $title_plural = 'Sources';
var $title_singular = 'Source';
/**
* 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('source');
t('sources');
t('Sources');
t('Source');
}
/**
* Get the available location types.
*/
function location_types() {
return backup_migrate_get_source_subtypes();
}
}
/**
* A base class for creating sources.
*/
class backup_migrate_source_remote extends backup_migrate_source {
/**
* The location is a URI so parse it and store the parts.
*/
function get_location() {
return $this->url(FALSE);
}
/**
* The location to display is the url without the password.
*/
function get_display_location() {
return $this->url(TRUE);
}
/**
* Return the location with the password.
*/
function set_location($location) {
$this->location = $location;
$this->set_url($location);
}
/**
* source configuration callback.
*/
function edit_form() {
$form = parent::edit_form();
$form['scheme'] = array(
"#type" => "textfield",
"#title" => t("Scheme"),
"#default_value" => @$this->dest_url['scheme'] ? $this->dest_url['scheme'] : '',
"#required" => TRUE,
"#weight" => 0,
);
$form['host'] = array(
"#type" => "textfield",
"#title" => t("Host"),
"#default_value" => @$this->dest_url['host'] ? $this->dest_url['host'] : 'localhost',
"#required" => TRUE,
"#weight" => 10,
);
$form['path'] = array(
"#type" => "textfield",
"#title" => t("Path"),
"#default_value" => @$this->dest_url['path'],
"#required" => TRUE,
"#weight" => 20,
);
$form['user'] = array(
"#type" => "textfield",
"#title" => t("Username"),
"#default_value" => @$this->dest_url['user'],
"#required" => TRUE,
"#weight" => 30,
);
$form['pass'] = array(
"#type" => "password",
"#title" => t("Password"),
"#default_value" => @$this->dest_url['pass'],
'#description' => '',
"#weight" => 40,
);
if (@$this->dest_url['pass']) {
$form['old_password'] = array(
"#type" => "value",
"#value" => @$this->dest_url['pass'],
);
$form['pass']["#description"] .= t(' You do not need to enter a password unless you wish to change the currently saved password.');
}
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_submit($form, &$form_state) {
$form_state['values']['pass'] = $form_state['values']['pass'] ? $form_state['values']['pass'] : $form_state['values']['old_password'];
$form_state['values']['location'] = $this->glue_url($form_state['values'], FALSE);
parent::edit_form_submit($form, $form_state);
}
}

View file

@ -0,0 +1,565 @@
The following people and organizations sponsored and/or contributed new and improved features to the project.
************************************************
Key Contributors and Sponsors for 4.7
************************************************
CiviCRM Team - Atif Shaikh, Coleman Watts, David Greenberg, Eileen McNaughton,
Jitendra Purohit, Josh Gowan, Kurund Jalmi,
Michael McAndrew, Monish Deb, Rohan Ramesh Katkar, Tim Otten,
Yashodha Chaku
AGH Strategies - Andrew Hunt, Tyrell Cook, Nikki Murray
Agileware - Justin Freeman, Francis Whittle, Iris Abarquez, Vaibhav Sagar
Andrew West
Aputsiaĸ Niels Janussen
Aron Novak
Backoffice Thinking
Barbara Miller
Borislav Zlatanov
Brian Dombrowski
Caroline Badley
Christian Wach
Charlie DeTar
Chirojeugd Vlaanderen - Johan Vervloet
Circle Interactive - Dave Jenkins
CiviCoop - Jaap Jansma
CiviDesk - Nicolas Ganivet, Sunil Pawar, Virginie Ganivet
Compucorp - Guanhuan Chen, Jamie Novick
CiviCoop - Jaap Jansma
Coop SymbioTIC - Mathieu Lutfy, Samuel Vanhove
Dave D
David Hayes
Dhanesh Dhuri
Dmitry Smirnov
Elin Waring
Emphanos LLC - Allen Shaw
Esantanche
Freeform Solutions - Lola Slade, Stephanie Gray, Herb van den Dool
Future First - David Knoll, John Prescott
Fuzion NZ - Chris Burgess, Eileen McNaughton, Peter Davis, Torrance Hodgson
Giant Rabbit - Peter Haight
Ginkgo Street Labs - Frank Gomez, Galata Tona, Michael Daryabeygi, Roshani Kothari, Toby Lounsbury
Jake Martin White
Joanne Chester
Joe McLaughlin
John P Kirk
Joris
JMA Consulting - Joe Murray, Pradeep Nayak, Edsel Lopez
gah242s
Greenleaf Advancement - Guy Iaccarino
K Sneed Consulting - Kate Sneed
Kemal Bay
Ken West
Kevin Levie
Korlon - Stuart Gaston
kreynen
Laryn
Lesley Evensen (zorgalina)
Lighthouse Consulting and Design - Brian Shaughnessy
Marty Wright
Matthew Wire
Mattias Michaux
Megaphone Technology Consulting - Jon Goldberg
Mohit Aggarwal
National Urban League - Lisa Taliano
Nicholai Burton
Niels Heinemann
New York City Council
New York State Senate - Ken Zalewski
Northbridge Digital - Oliver Gibson
Olaf Buddenhagen
Palante Technology Cooperative - Joseph Lacey
Paul Campbell
Progressive Tech Project - Alice Aguilar, Jamie McClelland
Richard Van Oosterhout
RocXa
Saurabh Batra
Seamus Lee
Seb35
Semper IT - Karin Gerritsen
Shawn Holt
Skvare - Jeremy Proffitt, Peter Petrik
Smiling Heart Enterprises - Neil Planchon
Squiffle Consulting - Aidan Saunders
Stephen Palmstrom
Symbiotic - Mathieu Lutfy, Samuel Vanhove
Systopia - Björn Endres, Niko Bochan
Tadpole - Dana Skallman, Kevin Cristiano
Tech to the People - Xavier Dutoit
Thomas Leichtuss
Tim Mallezie
Torenware Networks - Rob Thorne
University of Cambridge Alex Corr, John Kingsnorth
Veda Consulting - Parvez Saleh, Deepak Srivastava, Kajan
Wanna Pixel - Nathan Porter, Marisa Porter
Web Access - Sudha Bisht
Wikimedia Foundation - Adam Wight
yurg
zarandras
************************************************
Key Contributors and Sponsors for 4.6
************************************************
CiviCRM Team - Atif Shaikh, Coleman Watts, David Greenberg, Donald Lobo,
Eileen McNaughton, Jitendra Purohit, Josh Gowan, Kurund Jalmi,
Michael McAndrew, Monish Deb, Rohan Ramesh Katkar, Tim Otten,
Yashodha Chaku
ADG Communications - Steve Binkowski
AGH Strategies - Andrew Hunt, Jane Hanley, Tommy Bobo, Tyrell Cook
Agileware - Justin Freeman, Francis Whittle, Iris Abarquez, Vaibhav Sagar
Alex C
Allan Chappell
Amnesty International Spain - Carlos Capote
Andreas Hennings
Andy Clark
Arete Imagine - Marisa Porter, Nate Porter
Asylum Hill Congregational Church
Blackfly Solutions - Alan Dixon
Botanical Society of America - Toby Lounsbury
Chirojeugd Vlaanderen - Johan Vervloet
Christian Wach
Chris Ward
Circle Interactive - Dave Moreton, Andrew Walker, Dave Jenkins, Maya Gibbs
CiviCoop - Erik Hommel, Jaap Jansma
CiviDesk - Nicolas Ganivet, Sunil Pawar
Community Human Services Corporation - Paul Mosey
Compucorp - Jamie Novick, Greg Meszeros, Robin Mitra, Guanhuan Chen, Chanun Chirattikanon
David Hepper
Detlev Sieber
Drishtant - Ruchi Kumar
Drupal Association - Neil Drumm
Elliott Eggleston
Freeform Solutions - Lola Slade
Future First - David Knoll, John Prescott, Vitor Nobrega
Fuzion, NZ - Chris Burgess, Eileen McNaughton, Peter Davis
Giantrabbit - Anthony Nemirovsky, Peter Haight
Ginkgo Street Labs - Frank J. Gómez, Michael Daryabeygi
GMVCO Databases - Jon-man Cheung, Alex Lee, Craig Almond
Google Summer of Code - Aditya Nambiar, Siddhant Rajagopalan, Torrance Hodgeson
Gnu.org - David Thompson
Jaka Kranjc
JMA Consulting - Joe Murray, Pradeep Nayak, Edsel Lopez
Joanne Chester
John Kingsnorth
jsnyder83
Kathryn Benedicto
Han Velthuis
Ken West
Kirk Jackson
Korlon - Stuart Gaston
Lighthouse Consulting and Design - Brian Shaughnessy
Mattias Michaux
Max
MC3 - Graham Mitchell
Mission Matters - Joshua Aranda
Mobius - Jeremy Proffitt
Northbridge Digital - Oliver Gibson
Symbiotic - Mathieu Lutfy, Samuel Vanhove
National Democratic Institute - Chris Doten
New York State Senate - Ken Zalewski
Niro Solutions
Palente Technology Cooperative - Jon Goldberg, Joseph Lacey
Paul Campbell
Pogstone - Sarah Gladstone
Progressive Tech Project - Alice Aguilar, Jamie McClelland
Registered Nurses Association of Ontario - Stan Dragnev
Richard Van Oosterhout
Seamus Lee
Semper IT - Karin Gerritsen
Skvare - Mark Hanna, Peter Petrik
Squiffle Consulting - Aidan Saunders
Stephen Palmstrom
Systopia - Björn Endres, Fabian Schuttenberg, Martin Peth, Niko Bochan
Tadpole - Dana Skallman, Kevin Cristiano
Tech to the People - Xavier Dutoit
TeNNoX
Tim Mallezie
Toke Høiland-Jørgensen
Veda Consulting - Priyanka Karan, Parvez Saleh, Deepak Srivastava
William Theaker
Web Access - Tony Mazzerella, Nileema Jadhav, Parag Bhilkar, Pratiksha Dubey, Manish More
Wikimedia Foundation - Adam Wight
Zing - Simon West, Andrew Tombs, Vivek Arora
************************************************
Key Contributors and Sponsors for 4.5
************************************************
CiviCRM Team - Coleman Watts, David Greenberg, Donald Lobo,
Kurund Jalmi, Michael McAndrew, Monish Deb, Pratik Joshi,
Tim Otten, Yashodha Chaku, Eileen McNaughton
AGH Strategies - Andrew Hunt, Maggie Epps, Tyrell Cook
Allan Chappell
Amnesty International Spain - Carlos Capote
Andy Clark
Arete Imagine - Marisa Porter, Nate Porter
Botanical Society of America - Toby Lounsbury
Chris Burgess
Chris Ward
Circle Interactive - Andrew Walker, Dave Jenkins
CiviDesk - Nicolas Ganivet, Sunil Pawar
Compucorp - Jamie Novick, Erawat Chamanont
CiviCoop - Erik Hommel, Jaap Jansma
Detlev Sieber
Drishtant - Ruchi Kumar
Drupal Association - Neil Drumm
Electronic Frontier Foundation - Mark Burdett, Max Hunter, Leez Wright
Freeform Solutions - Lola Slade
Fuzion, NZ - Eileen McNaughton, Peter Davis, Torrance Hodgeson
Giant Rabbit - Peter Haight, Anthony Nemirovsky
Ginkgo Street Labs - Frank J. Gómez, Michael Daryabeygi
Graham Mitchell
Great Lakes Planetarium Association - Geoff Holt
Jennifer Simonis
Jeremy Proffitt
Jim Meehan
Jimmy Huang
JMA Consulting - Joe Murray
Joanne Chester
Ken West
Kirk Jackson
Korlon - Stuart Gaston
Koumbit - Samuel Vanhove
Lighthouse Consulting and Design - Brian Shaughnessy
Mathieu Lutfy
Mission Matters - Joshua Aranda
National Democratic Institute - Chris Doten
New York State Senate - Ken Zalewski
Niro Solutions
Palente Technology Cooperative - Jon Goldberg, Joseph Lacey
Pogstone - Sarah Gladstone
Progressive Tech Project - Alice Aguilar, Jamie McClelland
Semper IT - Karin Gerritsen
Skvare - Mark Hanna, Peter Petrik
Systopia - Björn Endres
Tadpole - Dana Skallman
Tech to the People - Xavier Dutoit
Veda Consulting - Parvez Saleh, Deepak Srivastava
Web Access - Pradeep Nayak, Tony Mazzarella
Wikimedia Foundation - Adam Wight
Zing - Simon West, Andrew Tombs
************************************************
Key Contributors and Sponsors for 4.4
************************************************
CiviCRM Team - Coleman Watts, David Greenberg, Donald Lobo,
Kurund Jalmi, Michael McAndrew, Monish Deb,
Tim Otten, Yashodha Chaku, Eileen McNaughton
AGH Strategies - Andrew Hunt
Backoffice Thinking
Chris Burgess
Circle Interactive - Andrew Walker, Dave Jenkins
CiviDesk - Nicolas Ganivet
CiviCoop - Erik Hommel, Jaap Jansma
CiviHosting - Hershel Robinson
CompuCorp - Jamie Novick, Erawat Chamanont
Confluence - Frank Gomez, Michael Daryabeygi
Dave D
Detlev Sieber
Drupal Association - Neil Drumm
Electronic Frontier Foundation - Micah Lee, Kellie Brownell
Emphanos - Allen Shaw
Freeform Solutions - Lola Slade
Fuzion, NZ - Eileen McNaughton, Peter Davis, Torrance Hodgeson
Giant Rabbit - Anna Heath
Jim Meehan
JMA Consulting - Joe Murray
Joanne Chester
Keith Morgan
Ken West
Korlon - Stuart Gaston
Koumbit - Samuel Vanhove
Lighthouse Consulting and Design - Brian Shaughnessy
Mathieu Lutfy
National Democratic Institute - Chris Doten
New York State Senate - Ken Zalewski
NfP Services (MTL Software Group) - Jag Kandasamy, Rajesh Sundararajan
Niro Solutions
Noah Miller
Orgis - Hans Idink
Palente Technology Cooperative - Jon Goldberg, Joseph Lacey
Paul Delbar
Pogstone - Sarah Gladstone
Progressive Tech Project - Alice Aguilar, Jamie McClelland
Registered Nurses Association of Ontario
San Francisco Baykeeper - Eliet Henderson
Tadpole - Dana Skallman
Tallyfox
Tech to the People - Xavier Dutoit
Veda Consulting - Parvez Saleh, Deepak Srivastava
Web Access - Pradeep Nayak
Wikimedia Foundation - Adam Wight
Zing - Simon West, Andrew Tombs
************************************************
Key Contributors and Sponsors for 4.3
************************************************
CiviCRM Team - Coleman Watts, David Greenberg, Deepak Srivastava, Donald Lobo,
Kurund Jalmi, Michael McAndrew, Pratik Joshi, Ravish Nair,
Tim Otten, Yashodha Chaku, Eileen McNaughton
AGH Strategies - Andrew Hunt
Backoffice Thinking
Chris Burgess
Circle Interactive - Andrew Walker, Dave Jenkins
CiviDesk - Nicolas Ganivet
CiviHosting - Hershel Robinson
Community Builders
Compucorp
Dave D
EE-atWork - Erik Hommel
Electronic Frontier Foundation - Micah Lee, Kellie Brownell
Emphanos - Allen Shaw
Fuzion, NZ - Eileen McNaughton, Peter Davis, Torrance Hodgeson
Ginkgo Street Labs - Frank J. Gómez, Michael Daryabeygi
Jim Meehan
JMA Consulting - Joe Murray, Pradeep Nayak
Keith Morgan
Ken West
Korlon - Stuart Gaston
Koumbit - Samuel Vanhove
Lighthouse Consulting and Design - Brian Shaughnessy
Mathieu Lutfy
New York State Senate - Ken Zalewski
NfP Services (MTL Software Group) - Jag Kandasamy, Rajesh Sundararajan
Niro Solutions
Noah Miller
Palente Technology Cooperative - Jon Goldberg
Progressive Tech Project - Alice Aguilar, Jamie McClelland
Paul Delbar
Registered Nurses Association of Ontario
San Francisco Baykeeper - Eliet Henderson
Tech to the People - Xavier Dutoit
Third Sector Design
Veda Consulting - Parvez Saleh
Web Access
Zing - Simon West, Andrew Tombs
************************************************
Sponsors and key contributors for 4.2
************************************************
The following people and organizations sponsored and/or contributed new and improved features for the 4.2 release.
Abril Rocabert
Adam Wight
Alice Aguilar
Allen Shaw
Andres Spagarino
Andrew Hunt
Anthony Camilleri
Ariel Gold
Brian Shaughnessy
Chris Ward
Dave Moreton
Eileen McNaughton
Eliet Henderson
Erik Hommel
Frank Gomez
Graylin Kim
Jamie McClelland
Jane Hanley
Jason Bertolacci
Joe Murray
John Derry
Jon Goldberg
Kasia Wakarecy
Katie Horn
Katy Jockelson
Ken Zalewski
Lisa Jervis
Mathieu Lutfy
Matt Neimayer
Micah Lee
Michael McAndrew
Nicolas Ganivet
Noah Miller
Parvez Saleh
Peter Gehres
Peter McAndrew
Robyn Perry
Samuel Vanhove
Simon West
Stéphane Lussier
Stuart Gaston
Xavier Dutoit
Art of Living
Backoffice Thinking
Community Builders
DC Road Runners
EE atWork
Electronic Frontier Foundation
Freeform Solutions
Free Software Foundation
Fuzion NZ
Gingko Street Consulting
JMA Consulting
Korlon
Koumbit
Lighthouse Consulting
National Democratic Institute
New York State Senate
NS Web Solutions
Progressive Technology Project
San Francisco Baykeeper
Tech to the People
The Monthly.com
Veda Consulting
Xstreme Media
Zing
************************************************
Sponsors and key contributors for 4.1
************************************************
The following people and organizations sponsored and/or contributed new and improved features for the 4.1 release.
Adam Wight
Andrew Harris
Alice Aguilar
Andre Gurgel
Brian Shaugnessy
Coleman Watts
Dave D
Dave Moreton
Eileen McNaughton
Erik Brower
Erik Hommel
Henry Bennett
Jamie McClelland
Jim Taylor
Jonathan Mark
Joe Murray
Marianela Zucotti Bozzano
Michael McAndrew
Steve Colson
Stuart Gaston
Tim Otten
Tom Kirkpatrick
Xavier Dutoit
AGH Strategies
Amigos Library Services
Association for Learning Technology
Attendee Management
Benton Consulting
Circle Interactive
CivicActions
Community Builders
EE-atWork
Fuzion (NZ)
Giant Rabbit
Kindling Trust
Korlon
International Mountain Biking Association
International Society for Bayesian Analysis
Josiesque Designs
Michigan Parents for Schools
New York State Senate
Nonprofit Association of Oregon
Nonprofit Solutions
Powered by Action
Progressive Technology Project
Resolutions Northwest
River Pool at Beacon
Rooty Hollow
San Francisco Baykeeper
Scotland's Colleges
Switchback
System Seed
Tech to the People
The San Francisco Orff-Schulwerk
Third Sector Design
Voluntary Action Westminster
Vpod Schweiz
Woven
************************************************
Sponsors for 3.4 / 4.0 Make-it-Happen Projects
************************************************
The following people and organizations sponsored new and improved features for the 3.4 / 4.0 release.
ACORN Canada http://acorncanada.org
Allora Consulting http://alloraconsulting.com
American Friends Service Committee http://afsc.org/
Australian Greens http://greens.org.au
BREAZE http://breaze.org.au
Canadian Paramedics http://www.peelparamedics.com
Community Builders Australia Pty Ltd
Corvair Society of America (CORSA) http://www.corvair.org/
Donor Depot http://donordepot.com
Energetica http://energetica.com.au
Fuzion http://fuzion.co.nz
Gold Strategy Group http://www.goldstrategygroup.com
JMA Consulting http://jmaconsulting.biz
Joomkit Ltd http://joomkit.com
Kabissa - Space for Change in Africa http://kabissa.org
NS Web Solutions http://nswebsolutions.com
NAMI Louisville http://namilouisville.org
Progressive Technology Project http://www.progressivetech.org
RVTC http://rvtc.us
Volunteer Honduras http://www.volunteerhonduras.org
Briney, Matthew
Brownsberger, Will
Burden, Monica
Calleeuw, Bart
Cimpian, Casti
Clarke, Jill
Davis, Peter
Day, Janette
Gold, Ariel
Hadar, Kehilat
Malkoun, Anthony
Matsushita, Jun
McNaughton, Eileen
Murray, Joe
Shaughnessy, Brian
Spagarino, Andres
Speleo
Stuart, josh
Tabletguy
Watts, Danny
Wistreich, Nic
****************************************
Sponsors for 3.3 Make-it-Happen Projects
****************************************
The following people and organizations sponsored new and improved features for the 3.3 release.
JMA Consulting: http://jmaconsulting.biz/
Emergency Picnic: http://emergencypicnic.net/
Thomas Carlson
Micheas Herman
T.J. Hellman
Gold Strategy Group: http://www.goldstrategygroup.com
Laura Velkei
John Barclay
Matthew Briney: http://emotivellc.com
2020Media: http://www.2020media.com/
Social Contxt: http://socialcontxt.com/
Impari Systems Inc: http://www.imparisystems.com/
Alpha: http://uk.alpha.org
Cambridge Union: http://www.cus.org
St Ethelburga's: http://stethelburgas.org
Joomkit: http://www.joomkit.com
International Mountain Biking Association: http://www.imba.com/
Niro Solutions: http://www.nirosolutions.com/
Fuzion: http://fuzion.co.nz
ArtD Webdesign
CivicActions: http://civicactions.com/
NES Alumni and Friends Nonprofit Partnership: https://www.nesalumni.org/en
Gold Strategy Group: http://www.goldstrategygroup.com
Creative Commons: http://creativecommons.org/
Community Builders Australia Pty Ltd: http://www.communitybuilders.com.au/
Australian Greens: http://greens.org.au/
NES Alumni and Friends Nonprofit Partnership: https://www.nesalumni.org/en
Data-Scribe: http://www.datascribe.biz/
Rayogram: http://www.rayogram.com/
GingerFeet LLC: http://www.gingerfeet.com/
Kabissa: http://kabissa.org
Beth Hynes-Ciernia

View file

@ -0,0 +1,221 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_API {
/**
* The various type of permissions.
*
* @var int
*/
const EDIT = 1;
const VIEW = 2;
const DELETE = 3;
const CREATE = 4;
const SEARCH = 5;
const ALL = 6;
/**
* Given a permission string, check for access requirements
*
* @param string $str
* The permission to check.
* @param int $contactID
* The contactID for whom the check is made.
*
* @return bool
* true if yes, else false
*/
public static function check($str, $contactID = NULL) {
if ($contactID == NULL) {
$contactID = CRM_Core_Session::getLoggedInContactID();
}
if (!$contactID) {
// anonymous user
$contactID = 0;
}
return CRM_ACL_BAO_ACL::check($str, $contactID);
}
/**
* Get the permissioned where clause for the user.
*
* @param int $type
* The type of permission needed.
* @param array $tables
* (reference ) add the tables that are needed for the select clause.
* @param array $whereTables
* (reference ) add the tables that are needed for the where clause.
* @param int $contactID
* The contactID for whom the check is made.
* @param bool $onlyDeleted
* Whether to include only deleted contacts.
* @param bool $skipDeleteClause
* Don't add delete clause if this is true,.
* this means it is handled by generating query
* @param bool $skipOwnContactClause
* Do not add 'OR contact_id = $userID' to the where clause.
* This is a hideously inefficient query and should be avoided
* wherever possible.
*
* @return string
* the group where clause for this user
*/
public static function whereClause(
$type,
&$tables,
&$whereTables,
$contactID = NULL,
$onlyDeleted = FALSE,
$skipDeleteClause = FALSE,
$skipOwnContactClause = FALSE
) {
// the default value which is valid for the final AND
$deleteClause = ' ( 1 ) ';
if (!$skipDeleteClause) {
if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
$deleteClause = '(contact_a.is_deleted)';
}
else {
// CRM-6181
$deleteClause = '(contact_a.is_deleted = 0)';
}
}
// first see if the contact has edit / view all contacts
if (CRM_Core_Permission::check('edit all contacts') ||
($type == self::VIEW && CRM_Core_Permission::check('view all contacts'))
) {
return $deleteClause;
}
if (!$contactID) {
$contactID = CRM_Core_Session::getLoggedInContactID();
}
$contactID = (int) $contactID;
$where = implode(' AND ',
array(
CRM_ACL_BAO_ACL::whereClause($type,
$tables,
$whereTables,
$contactID
),
$deleteClause,
)
);
// Add permission on self if we really hate our server or have hardly any contacts.
if (!$skipOwnContactClause && $contactID && (CRM_Core_Permission::check('edit my contact') ||
$type == self::VIEW && CRM_Core_Permission::check('view my contact'))
) {
$where = "(contact_a.id = $contactID OR ($where))";
}
return $where;
}
/**
* Get all the groups the user has access to for the given operation.
*
* @param int $type
* The type of permission needed.
* @param int $contactID
* The contactID for whom the check is made.
*
* @param string $tableName
* @param null $allGroups
* @param null $includedGroups
*
* @return array
* the ids of the groups for which the user has permissions
*/
public static function group(
$type,
$contactID = NULL,
$tableName = 'civicrm_saved_search',
$allGroups = NULL,
$includedGroups = NULL
) {
if ($contactID == NULL) {
$contactID = CRM_Core_Session::getLoggedInContactID();
}
if (!$contactID) {
// anonymous user
$contactID = 0;
}
return CRM_ACL_BAO_ACL::group($type, $contactID, $tableName, $allGroups, $includedGroups);
}
/**
* Check if the user has access to this group for operation $type
*
* @param int $type
* The type of permission needed.
* @param int $groupID
* @param int $contactID
* The contactID for whom the check is made.
* @param string $tableName
* @param null $allGroups
* @param null $includedGroups
*
* @return bool
*/
public static function groupPermission(
$type,
$groupID,
$contactID = NULL,
$tableName = 'civicrm_saved_search',
$allGroups = NULL,
$includedGroups = NULL
) {
if (!isset(Civi::$statics[__CLASS__]) || !isset(Civi::$statics[__CLASS__]['group_permission'])) {
Civi::$statics[__CLASS__]['group_permission'] = array();
}
if (!$contactID) {
$contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
}
$key = "{$tableName}_{$type}_{$contactID}";
if (!array_key_exists($key, Civi::$statics[__CLASS__]['group_permission'])) {
Civi::$statics[__CLASS__]['group_permission'][$key] = self::group($type, $contactID, $tableName, $allGroups, $includedGroups);
}
return in_array($groupID, Civi::$statics[__CLASS__]['group_permission'][$key]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,172 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Access Control Cache.
*/
class CRM_ACL_BAO_Cache extends CRM_ACL_DAO_Cache {
static $_cache = NULL;
/**
* @param int $id
*
* @return mixed
*/
public static function &build($id) {
if (!self::$_cache) {
self::$_cache = array();
}
if (array_key_exists($id, self::$_cache)) {
return self::$_cache[$id];
}
// check if this entry exists in db
// if so retrieve and return
self::$_cache[$id] = self::retrieve($id);
if (self::$_cache[$id]) {
return self::$_cache[$id];
}
self::$_cache[$id] = CRM_ACL_BAO_ACL::getAllByContact($id);
self::store($id, self::$_cache[$id]);
return self::$_cache[$id];
}
/**
* @param int $id
*
* @return array
*/
public static function retrieve($id) {
$query = "
SELECT acl_id
FROM civicrm_acl_cache
WHERE contact_id = %1
";
$params = array(1 => array($id, 'Integer'));
if ($id == 0) {
$query .= " OR contact_id IS NULL";
}
$dao = CRM_Core_DAO::executeQuery($query, $params);
$cache = array();
while ($dao->fetch()) {
$cache[$dao->acl_id] = 1;
}
return $cache;
}
/**
* @param int $id
* @param array $cache
*/
public static function store($id, &$cache) {
foreach ($cache as $aclID => $data) {
$dao = new CRM_ACL_DAO_Cache();
if ($id) {
$dao->contact_id = $id;
}
$dao->acl_id = $aclID;
$cache[$aclID] = 1;
$dao->save();
}
}
/**
* @param int $id
*/
public static function deleteEntry($id) {
if (self::$_cache &&
array_key_exists($id, self::$_cache)
) {
unset(self::$_cache[$id]);
}
$query = "
DELETE FROM civicrm_acl_cache
WHERE contact_id = %1
";
$params = array(1 => array($id, 'Integer'));
CRM_Core_DAO::executeQuery($query, $params);
}
/**
* @param int $id
*/
public static function updateEntry($id) {
// rebuilds civicrm_acl_cache
self::deleteEntry($id);
self::build($id);
// rebuilds civicrm_acl_contact_cache
CRM_Contact_BAO_Contact_Permission::cache($id, CRM_Core_Permission::VIEW, TRUE);
}
/**
* Deletes all the cache entries.
*/
public static function resetCache() {
if (!CRM_Core_Config::isPermitCacheFlushMode()) {
return;
}
// reset any static caching
self::$_cache = NULL;
$query = "
DELETE
FROM civicrm_acl_cache
WHERE modified_date IS NULL
OR (modified_date <= %1)
";
$params = array(1 => array(CRM_Contact_BAO_GroupContactCache::getCacheInvalidDateTime(), 'String'));
CRM_Core_DAO::singleValueQuery($query, $params);
// CRM_Core_DAO::singleValueQuery("TRUNCATE TABLE civicrm_acl_contact_cache"); // No, force-commits transaction
// CRM_Core_DAO::singleValueQuery("DELETE FROM civicrm_acl_contact_cache"); // Transaction-safe
if (CRM_Core_Transaction::isActive()) {
CRM_Core_Transaction::addCallback(CRM_Core_Transaction::PHASE_POST_COMMIT, function () {
CRM_Core_DAO::singleValueQuery("TRUNCATE TABLE civicrm_acl_contact_cache");
});
}
else {
CRM_Core_DAO::singleValueQuery("TRUNCATE TABLE civicrm_acl_contact_cache");
}
}
}

View file

@ -0,0 +1,104 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Access Control EntityRole.
*/
class CRM_ACL_BAO_EntityRole extends CRM_ACL_DAO_EntityRole {
static $_entityTable = NULL;
/**
* Get entity table.
*
* @return array|null
*/
public static function entityTable() {
if (!self::$_entityTable) {
self::$_entityTable = array(
'civicrm_contact' => ts('Contact'),
'civicrm_group' => ts('Group'),
);
}
return self::$_entityTable;
}
/**
* @param array $params
*
* @return CRM_ACL_DAO_EntityRole
*/
public static function create(&$params) {
$dao = new CRM_ACL_DAO_EntityRole();
$dao->copyValues($params);
$dao->save();
return $dao;
}
/**
* @param array $params
* @param $defaults
*/
public static function retrieve(&$params, &$defaults) {
CRM_Core_DAO::commonRetrieve('CRM_ACL_DAO_EntityRole', $params, $defaults);
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_ACL_DAO_EntityRole', $id, 'is_active', $is_active);
}
/**
* Delete Entity Role records.
*
* @param int $entityRoleId
* ID of the EntityRole record to be deleted.
*
*/
public static function del($entityRoleId) {
$entityDAO = new CRM_ACL_DAO_EntityRole();
$entityDAO->id = $entityRoleId;
$entityDAO->find(TRUE);
$entityDAO->delete();
}
}

View file

@ -0,0 +1,358 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/ACL/ACL.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:f56c9ad63ff247e68abf2c7c70ff65ba)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_ACL_DAO_ACL constructor.
*/
class CRM_ACL_DAO_ACL extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_acl';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Unique table ID
*
* @var int unsigned
*/
public $id;
/**
* ACL Name.
*
* @var string
*/
public $name;
/**
* Is this ACL entry Allow (0) or Deny (1) ?
*
* @var boolean
*/
public $deny;
/**
* Table of the object possessing this ACL entry (Contact, Group, or ACL Group)
*
* @var string
*/
public $entity_table;
/**
* ID of the object possessing this ACL
*
* @var int unsigned
*/
public $entity_id;
/**
* What operation does this ACL entry control?
*
* @var string
*/
public $operation;
/**
* The table of the object controlled by this ACL entry
*
* @var string
*/
public $object_table;
/**
* The ID of the object controlled by this ACL entry
*
* @var int unsigned
*/
public $object_id;
/**
* If this is a grant/revoke entry, what table are we granting?
*
* @var string
*/
public $acl_table;
/**
* ID of the ACL or ACL group being granted/revoked
*
* @var int unsigned
*/
public $acl_id;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_acl';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('ACL ID') ,
'description' => 'Unique table ID',
'required' => true,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('ACL Name') ,
'description' => 'ACL Name.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'deny' => array(
'name' => 'deny',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Deny ACL?') ,
'description' => 'Is this ACL entry Allow (0) or Deny (1) ?',
'required' => true,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
'html' => array(
'type' => 'Radio',
) ,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('ACL Entity') ,
'description' => 'Table of the object possessing this ACL entry (Contact, Group, or ACL Group)',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity ID') ,
'description' => 'ID of the object possessing this ACL',
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'operation' => array(
'name' => 'operation',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('ACL Operation') ,
'description' => 'What operation does this ACL entry control?',
'required' => true,
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_ACL_BAO_ACL::operation',
)
) ,
'object_table' => array(
'name' => 'object_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('ACL Object') ,
'description' => 'The table of the object controlled by this ACL entry',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'object_id' => array(
'name' => 'object_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('ACL Object ID') ,
'description' => 'The ID of the object controlled by this ACL entry',
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'acl_table' => array(
'name' => 'acl_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('ACL Table') ,
'description' => 'If this is a grant/revoke entry, what table are we granting?',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'acl_id' => array(
'name' => 'acl_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('ACL Group ID') ,
'description' => 'ID of the ACL or ACL group being granted/revoked',
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('ACL Is Active?') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_acl',
'entity' => 'ACL',
'bao' => 'CRM_ACL_BAO_ACL',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_acl_id' => array(
'name' => 'index_acl_id',
'field' => array(
0 => 'acl_id',
) ,
'localizable' => false,
'sig' => 'civicrm_acl::0::acl_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,223 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/ACL/Cache.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:f65002b394a3b1f9c18de75751364acc)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_ACL_DAO_Cache constructor.
*/
class CRM_ACL_DAO_Cache extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_acl_cache';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Unique table ID
*
* @var int unsigned
*/
public $id;
/**
* Foreign Key to Contact
*
* @var int unsigned
*/
public $contact_id;
/**
* Foreign Key to ACL
*
* @var int unsigned
*/
public $acl_id;
/**
* When was this cache entry last modified
*
* @var timestamp
*/
public $modified_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_acl_cache';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'acl_id', 'civicrm_acl', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Cache ID') ,
'description' => 'Unique table ID',
'required' => true,
'table_name' => 'civicrm_acl_cache',
'entity' => 'Cache',
'bao' => 'CRM_ACL_BAO_Cache',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Cache Contact') ,
'description' => 'Foreign Key to Contact',
'table_name' => 'civicrm_acl_cache',
'entity' => 'Cache',
'bao' => 'CRM_ACL_BAO_Cache',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'acl_id' => array(
'name' => 'acl_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Cache ACL') ,
'description' => 'Foreign Key to ACL',
'required' => true,
'table_name' => 'civicrm_acl_cache',
'entity' => 'Cache',
'bao' => 'CRM_ACL_BAO_Cache',
'localizable' => 0,
'FKClassName' => 'CRM_ACL_DAO_ACL',
) ,
'modified_date' => array(
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Cache Modified Date') ,
'description' => 'When was this cache entry last modified',
'required' => false,
'table_name' => 'civicrm_acl_cache',
'entity' => 'Cache',
'bao' => 'CRM_ACL_BAO_Cache',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_cache', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_cache', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_acl_id' => array(
'name' => 'index_acl_id',
'field' => array(
0 => 'acl_id',
) ,
'localizable' => false,
'sig' => 'civicrm_acl_cache::0::acl_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,248 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/ACL/EntityRole.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:b6780a8cf74433fd38a0c7f9e6161986)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_ACL_DAO_EntityRole constructor.
*/
class CRM_ACL_DAO_EntityRole extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_acl_entity_role';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Unique table ID
*
* @var int unsigned
*/
public $id;
/**
* Foreign Key to ACL Role (which is an option value pair and hence an implicit FK)
*
* @var int unsigned
*/
public $acl_role_id;
/**
* Table of the object joined to the ACL Role (Contact or Group)
*
* @var string
*/
public $entity_table;
/**
* ID of the group/contact object being joined
*
* @var int unsigned
*/
public $entity_id;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_acl_entity_role';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity Role') ,
'description' => 'Unique table ID',
'required' => true,
'table_name' => 'civicrm_acl_entity_role',
'entity' => 'EntityRole',
'bao' => 'CRM_ACL_BAO_EntityRole',
'localizable' => 0,
) ,
'acl_role_id' => array(
'name' => 'acl_role_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('ACL Role ID') ,
'description' => 'Foreign Key to ACL Role (which is an option value pair and hence an implicit FK)',
'required' => true,
'table_name' => 'civicrm_acl_entity_role',
'entity' => 'EntityRole',
'bao' => 'CRM_ACL_BAO_EntityRole',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Table') ,
'description' => 'Table of the object joined to the ACL Role (Contact or Group)',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_acl_entity_role',
'entity' => 'EntityRole',
'bao' => 'CRM_ACL_BAO_EntityRole',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('ACL Entity ID') ,
'description' => 'ID of the group/contact object being joined',
'required' => true,
'table_name' => 'civicrm_acl_entity_role',
'entity' => 'EntityRole',
'bao' => 'CRM_ACL_BAO_EntityRole',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('ACL Entity Role is Active') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_acl_entity_role',
'entity' => 'EntityRole',
'bao' => 'CRM_ACL_BAO_EntityRole',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_entity_role', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_entity_role', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_role' => array(
'name' => 'index_role',
'field' => array(
0 => 'acl_role_id',
) ,
'localizable' => false,
'sig' => 'civicrm_acl_entity_role::0::acl_role_id',
) ,
'index_entity' => array(
'name' => 'index_entity',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
) ,
'localizable' => false,
'sig' => 'civicrm_acl_entity_role::0::entity_table::entity_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,300 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Form_ACL extends CRM_Admin_Form {
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
if ($this->_action & CRM_Core_Action::ADD) {
$defaults['object_type'] = 1;
}
$showHide = new CRM_Core_ShowHideBlocks();
if (isset($defaults['object_table'])) {
switch ($defaults['object_table']) {
case 'civicrm_saved_search':
$defaults['group_id'] = $defaults['object_id'];
$defaults['object_type'] = 1;
$showHide->addShow("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-event-acl");
break;
case 'civicrm_uf_group':
$defaults['uf_group_id'] = $defaults['object_id'];
$defaults['object_type'] = 2;
$showHide->addHide("id-group-acl");
$showHide->addShow("id-profile-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-event-acl");
break;
case 'civicrm_custom_group':
$defaults['custom_group_id'] = $defaults['object_id'];
$defaults['object_type'] = 3;
$showHide->addHide("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addShow("id-custom-acl");
$showHide->addHide("id-event-acl");
break;
case 'civicrm_event':
$defaults['event_id'] = $defaults['object_id'];
$defaults['object_type'] = 4;
$showHide->addHide("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addHide("id-custom-acl");
$showHide->addShow("id-event-acl");
break;
}
}
else {
$showHide->addHide("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-event-acl");
}
// Don't assign showHide elements to template in DELETE mode (fields to be shown and hidden don't exist)
if (!($this->_action & CRM_Core_Action::DELETE)) {
$showHide->addToTemplate();
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->setPageTitle(ts('ACL'));
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_ACL_DAO_ACL');
$this->add('text', 'name', ts('Description'), CRM_Core_DAO::getAttribute('CRM_ACL_DAO_ACL', 'name'), TRUE);
$operations = array('' => ts('- select -')) + CRM_ACL_BAO_ACL::operation();
$this->add('select',
'operation',
ts('Operation'),
$operations, TRUE
);
$objTypes = array(
'1' => ts('A group of contacts'),
'2' => ts('A profile'),
'3' => ts('A set of custom data fields'),
);
if (CRM_Core_Permission::access('CiviEvent')) {
$objTypes['4'] = ts('Events');
}
$extra = array('onclick' => "showObjectSelect();");
$this->addRadio('object_type',
ts('Type of Data'),
$objTypes,
$extra,
'&nbsp;', TRUE
);
$label = ts('Role');
$role = array(
'-1' => ts('- select role -'),
'0' => ts('Everyone'),
) + CRM_Core_OptionGroup::values('acl_role');
$this->add('select', 'entity_id', $label, $role, TRUE);
$group = array(
'-1' => ts('- select -'),
'0' => ts('All Groups'),
) + CRM_Core_PseudoConstant::group();
$customGroup = array(
'-1' => ts('- select -'),
'0' => ts('All Custom Groups'),
) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
$ufGroup = array(
'-1' => ts('- select -'),
'0' => ts('All Profiles'),
) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
$event = array(
'-1' => ts('- select -'),
'0' => ts('All Events'),
) + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$this->add('select', 'group_id', ts('Group'), $group);
$this->add('select', 'custom_group_id', ts('Custom Data'), $customGroup);
$this->add('select', 'uf_group_id', ts('Profile'), $ufGroup);
$this->add('select', 'event_id', ts('Event'), $event);
$this->add('checkbox', 'is_active', ts('Enabled?'));
$this->addFormRule(array('CRM_ACL_Form_ACL', 'formRule'));
}
/**
* @param array $params
*
* @return bool
*/
public static function formRule($params) {
$showHide = new CRM_Core_ShowHideBlocks();
// Make sure role is not -1
if ($params['entity_id'] == -1) {
$errors['entity_id'] = ts('Please assign this permission to a Role.');
}
$validOperations = array('View', 'Edit');
$operationMessage = ts("Only 'View' and 'Edit' operations are valid for this type of data");
// Figure out which type of object we're permissioning on and make sure user has selected a value.
switch ($params['object_type']) {
case 1:
if ($params['group_id'] == -1) {
$errors['group_id'] = ts('Please select a Group (or ALL Groups).');
$showHide->addShow("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-event-acl");
}
if (!in_array($params['operation'], $validOperations)) {
$errors['operation'] = $operationMessage;
}
break;
case 2:
if ($params['uf_group_id'] == -1) {
$errors['uf_group_id'] = ts('Please select a Profile (or ALL Profiles).');
$showHide->addShow("id-profile-acl");
$showHide->addHide("id-group-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-event-acl");
}
break;
case 3:
if ($params['custom_group_id'] == -1) {
$errors['custom_group_id'] = ts('Please select a set of Custom Data (or ALL Custom Data).');
$showHide->addShow("id-custom-acl");
$showHide->addHide("id-group-acl");
$showHide->addHide("id-profile-acl");
$showHide->addHide("id-event-acl");
}
if (!in_array($params['operation'], $validOperations)) {
$errors['operation'] = $operationMessage;
}
break;
case 4:
if ($params['event_id'] == -1) {
$errors['event_id'] = ts('Please select an Event (or ALL Events).');
$showHide->addShow("id-event-acl");
$showHide->addHide("id-custom-acl");
$showHide->addHide("id-group-acl");
$showHide->addHide("id-profile-acl");
}
if (!in_array($params['operation'], $validOperations)) {
$errors['operation'] = $operationMessage;
}
break;
}
$showHide->addToTemplate();
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
// note this also resets any ACL cache
CRM_Core_BAO_Cache::deleteGroup('contact fields');
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_ACL_BAO_ACL::del($this->_id);
CRM_Core_Session::setStatus(ts('Selected ACL has been deleted.'), ts('Record Deleted'), 'success');
}
else {
$params = $this->controller->exportValues($this->_name);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['deny'] = 0;
$params['entity_table'] = 'civicrm_acl_role';
// Figure out which type of object we're permissioning on and set object_table and object_id.
switch ($params['object_type']) {
case 1:
$params['object_table'] = 'civicrm_saved_search';
$params['object_id'] = $params['group_id'];
break;
case 2:
$params['object_table'] = 'civicrm_uf_group';
$params['object_id'] = $params['uf_group_id'];
break;
case 3:
$params['object_table'] = 'civicrm_custom_group';
$params['object_id'] = $params['custom_group_id'];
break;
case 4:
$params['object_table'] = 'civicrm_event';
$params['object_id'] = $params['event_id'];
break;
}
if ($this->_id) {
$params['id'] = $this->_id;
}
CRM_ACL_BAO_ACL::create($params);
}
}
}

View file

@ -0,0 +1,151 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Form_ACLBasic extends CRM_Admin_Form {
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = array();
if ($this->_id ||
$this->_id === '0'
) {
$defaults['entity_id'] = $this->_id;
$query = "
SELECT object_table
FROM civicrm_acl
WHERE entity_id = %1
AND ( object_table NOT IN ( 'civicrm_saved_search', 'civicrm_uf_group', 'civicrm_custom_group' ) )
";
$params = array(1 => array($this->_id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
$defaults['object_table'] = array();
while ($dao->fetch()) {
$defaults['object_table'][$dao->object_table] = 1;
}
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$permissions = array_flip(CRM_Core_Permission::basicPermissions());
$this->addCheckBox('object_table',
ts('ACL Type'),
$permissions,
NULL, NULL, TRUE, NULL,
array('</td><td>', '</td></tr><tr><td>')
);
$label = ts('Role');
$role = array(
'-1' => ts('- select role -'),
'0' => ts('Everyone'),
) + CRM_Core_OptionGroup::values('acl_role');
$entityID = &$this->add('select', 'entity_id', $label, $role, TRUE);
if ($this->_id) {
$entityID->freeze();
}
$this->add('checkbox', 'is_active', ts('Enabled?'));
$this->addFormRule(array('CRM_ACL_Form_ACLBasic', 'formRule'));
}
/**
* @param array $params
*
* @return array|bool
*/
public static function formRule($params) {
if ($params['entity_id'] == -1) {
$errors = array('entity_id' => ts('Role is a required field'));
return $errors;
}
return TRUE;
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_ACL_BAO_Cache::resetCache();
$params = $this->controller->exportValues($this->_name);
if ($this->_id ||
$this->_id === '0'
) {
$query = "
DELETE
FROM civicrm_acl
WHERE entity_id = %1
AND ( object_table NOT IN ( 'civicrm_saved_search', 'civicrm_uf_group', 'civicrm_custom_group' ) )
";
$deleteParams = array(1 => array($this->_id, 'Integer'));
CRM_Core_DAO::executeQuery($query, $deleteParams);
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_Session::setStatus(ts('Selected ACL has been deleted.'), ts('Record Deleted'), 'success');
return;
}
}
$params['operation'] = 'All';
$params['deny'] = 0;
$params['is_active'] = 1;
$params['entity_table'] = 'civicrm_acl_role';
$params['name'] = 'Core ACL';
foreach ($params['object_table'] as $object_table => $value) {
if ($value) {
$newParams = $params;
unset($newParams['object_table']);
$newParams['object_table'] = $object_table;
CRM_ACL_BAO_ACL::create($newParams);
}
}
}
}

View file

@ -0,0 +1,78 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Form_EntityRole extends CRM_Admin_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$aclRoles = array('' => ts('- select -')) + CRM_Core_OptionGroup::values('acl_role');
$this->add('select', 'acl_role_id', ts('ACL Role'),
$aclRoles, TRUE
);
$label = ts('Assigned to');
$group = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::staticGroup(FALSE, 'Access');
$this->add('select', 'entity_id', $label, $group, TRUE, array('class' => 'crm-select2 huge'));
$this->add('checkbox', 'is_active', ts('Enabled?'));
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_ACL_BAO_Cache::resetCache();
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_ACL_BAO_EntityRole::del($this->_id);
CRM_Core_Session::setStatus(ts('Selected Entity Role has been deleted.'), ts('Record Deleted'), 'success');
}
else {
$params = $this->controller->exportValues($this->_name);
if ($this->_id) {
$params['id'] = $this->_id;
}
$params['entity_table'] = 'civicrm_group';
CRM_ACL_BAO_EntityRole::create($params);
}
}
}

View file

@ -0,0 +1,198 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to Grant access to CiviCRM components and other CiviCRM permissions.
*/
class CRM_ACL_Form_WordPress_Permissions extends CRM_Core_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle('Wordpress Access Control');
// Get the core permissions array
$permissionsArray = self::getPermissionArray();
$permissionsDesc = self::getPermissionArray(TRUE);
// Get the wordpress roles, default capabilities and assign to the form
// TODO: Create a new wordpress role (Anonymous user) and define capabilities in Wordpress Access Control
global $wp_roles;
if (!isset($wp_roles)) {
$wp_roles = new WP_Roles();
}
foreach ($wp_roles->role_names as $role => $name) {
// Dont show the permissions options for administrator, as they have all permissions
if ($role !== 'administrator') {
$roleObj = $wp_roles->get_role($role);
if (!empty($roleObj->capabilities)) {
foreach ($roleObj->capabilities as $ckey => $cname) {
if (array_key_exists($ckey, $permissionsArray)) {
$elementName = $role . '[' . $ckey . ']';
$defaults[$elementName] = 1;
}
}
}
// Compose the checkbox array for each role, to assign to form
$rolePerms[$role] = $permissionsArray;
foreach ($rolePerms[$role] as $key => $value) {
$elementName = $role . '[' . $key . ']';
$this->add('checkbox', $elementName, $value);
}
$roles[$role] = $name;
}
}
$this->setDefaults($defaults);
$descArray = array();
foreach ($permissionsDesc as $perm => $attr) {
if (count($attr) > 1) {
$descArray[$perm] = $attr[1];
}
}
$this->assign('permDesc', $descArray);
$this->assign('rolePerms', $rolePerms);
$this->assign('roles', $roles);
$this->addButtons(
array(
array(
'type' => 'next',
'name' => ts('Save'),
'spacing' => '',
'isDefault' => FALSE,
),
)
);
}
/**
* Process the form submission.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$permissionsArray = self::getPermissionArray();
// Function to get Wordpress roles
global $wp_roles;
if (!isset($wp_roles)) {
$wp_roles = new WP_Roles();
}
foreach ($wp_roles->role_names as $role => $name) {
$roleObj = $wp_roles->get_role($role);
//Remove all civicrm capabilities for the role, as there may be some capabilities checkbox unticked
foreach ($permissionsArray as $key => $capability) {
$roleObj->remove_cap($key);
}
//Add the selected wordpress capabilities for the role
$rolePermissions = $params[$role];
if (!empty($rolePermissions)) {
foreach ($rolePermissions as $key => $capability) {
$roleObj->add_cap($key);
}
}
if ($role == 'anonymous_user') {
// Get the permissions into a format that matches what we get from WP
$allWarningPermissions = CRM_Core_Permission::getAnonymousPermissionsWarnings();
foreach ($allWarningPermissions as $key => $permission) {
$allWarningPermissions[$key] = CRM_Utils_String::munge(strtolower($permission));
}
$warningPermissions = array_intersect($allWarningPermissions, array_keys($rolePermissions));
$warningPermissionNames = array();
foreach ($warningPermissions as $permission) {
$warningPermissionNames[$permission] = $permissionsArray[$permission];
}
if (!empty($warningPermissionNames)) {
CRM_Core_Session::setStatus(
ts('The %1 role was assigned one or more permissions that may prove dangerous for users of that role to have. Please reconsider assigning %2 to them.', array(
1 => $wp_roles->role_names[$role],
2 => implode(', ', $warningPermissionNames),
)),
ts('Unsafe Permission Settings')
);
}
}
}
// FIXME
// Changed the 'access_civicrm_nav_link' capability in civicrm.php file
// But for some reason, if i remove 'Access CiviCRM' administrator and save, it is showing
// 'You do not have sufficient permissions to access this page'
// which should not happen for Super Admin and Administrators, as checking permissions for Super
// Admin and Administrators always gives TRUE
wp_civicrm_capability();
CRM_Core_Session::setStatus("", ts('Wordpress Access Control Updated'), "success");
// rebuild the menus to comply with the new permisssions/capabilites
CRM_Core_Invoke::rebuildMenuAndCaches();
CRM_Utils_System::redirect('admin.php?page=CiviCRM&q=civicrm/admin/access&reset=1');
CRM_Utils_System::civiExit();
}
/**
* Get the core civicrm permissions array.
* This function should be shared from a similar one in
* distmaker/utils/joomlaxml.php
*
* @param bool $descriptions
* Whether to return permission descriptions
*
* @return array
* civicrm permissions
*/
public static function getPermissionArray($descriptions = FALSE) {
global $civicrm_root;
$permissions = CRM_Core_Permission::basicPermissions(FALSE, $descriptions);
$perms_array = array();
foreach ($permissions as $perm => $title) {
//order matters here, but we deal with that later
$perms_array[CRM_Utils_String::munge(strtolower($perm))] = $title;
}
return $perms_array;
}
}

View file

@ -0,0 +1,262 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Page_ACL extends CRM_Core_Page_Basic {
public $useLivePageJS = TRUE;
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Get BAO Name.
*
* @return string
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_ACL_BAO_ACL';
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/acl',
'qs' => 'reset=1&action=update&id=%%id%%',
'title' => ts('Edit ACL'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable ACL'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable ACL'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/acl',
'qs' => 'reset=1&action=delete&id=%%id%%',
'title' => ts('Delete ACL'),
),
);
}
return self::$_links;
}
/**
* Run the page.
*
* Set the breadcrumb before beginning the standard page run.
*/
public function run() {
// set breadcrumb to append to admin/access
$breadCrumb = array(
array(
'title' => ts('Access Control'),
'url' => CRM_Utils_System::url('civicrm/admin/access',
'reset=1'
),
),
);
CRM_Utils_System::appendBreadCrumb($breadCrumb);
// parent run
return parent::run();
}
/**
* Browse all acls.
*/
public function browse() {
// get all acl's sorted by weight
$acl = array();
$query = "
SELECT *
FROM civicrm_acl
WHERE ( object_table IN ( 'civicrm_saved_search', 'civicrm_uf_group', 'civicrm_custom_group', 'civicrm_event' ) )
ORDER BY entity_id
";
$dao = CRM_Core_DAO::executeQuery($query);
$roles = CRM_Core_OptionGroup::values('acl_role');
$group = array(
'-1' => ts('- select -'),
'0' => ts('All Groups'),
) + CRM_Core_PseudoConstant::group();
$customGroup = array(
'-1' => ts('- select -'),
'0' => ts('All Custom Groups'),
) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
$ufGroup = array(
'-1' => ts('- select -'),
'0' => ts('All Profiles'),
) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
$event = array(
'-1' => ts('- select -'),
'0' => ts('All Events'),
) + CRM_Event_PseudoConstant::event();
while ($dao->fetch()) {
$acl[$dao->id] = array();
$acl[$dao->id]['name'] = $dao->name;
$acl[$dao->id]['operation'] = $dao->operation;
$acl[$dao->id]['entity_id'] = $dao->entity_id;
$acl[$dao->id]['entity_table'] = $dao->entity_table;
$acl[$dao->id]['object_table'] = $dao->object_table;
$acl[$dao->id]['object_id'] = $dao->object_id;
$acl[$dao->id]['is_active'] = $dao->is_active;
if ($acl[$dao->id]['entity_id']) {
$acl[$dao->id]['entity'] = CRM_Utils_Array::value($acl[$dao->id]['entity_id'], $roles);
}
else {
$acl[$dao->id]['entity'] = ts('Everyone');
}
switch ($acl[$dao->id]['object_table']) {
case 'civicrm_saved_search':
$acl[$dao->id]['object'] = CRM_Utils_Array::value($acl[$dao->id]['object_id'], $group);
$acl[$dao->id]['object_name'] = ts('Group');
break;
case 'civicrm_uf_group':
$acl[$dao->id]['object'] = CRM_Utils_Array::value($acl[$dao->id]['object_id'], $ufGroup);
$acl[$dao->id]['object_name'] = ts('Profile');
break;
case 'civicrm_custom_group':
$acl[$dao->id]['object'] = CRM_Utils_Array::value($acl[$dao->id]['object_id'], $customGroup);
$acl[$dao->id]['object_name'] = ts('Custom Group');
break;
case 'civicrm_event':
$acl[$dao->id]['object'] = CRM_Utils_Array::value($acl[$dao->id]['object_id'], $event);
$acl[$dao->id]['object_name'] = ts('Event');
break;
}
// form all action links
$action = array_sum(array_keys($this->links()));
if ($dao->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$action -= CRM_Core_Action::DISABLE;
}
$acl[$dao->id]['action'] = CRM_Core_Action::formLink(
self::links(),
$action,
array('id' => $dao->id),
ts('more'),
FALSE,
'ACL.manage.action',
'ACL',
$dao->id
);
}
$this->assign('rows', $acl);
}
/**
* Get name of edit form.
*
* @return string
* Classname of edit form.
*/
public function editForm() {
return 'CRM_ACL_Form_ACL';
}
/**
* Get edit form name.
*
* @return string
* name of this page.
*/
public function editName() {
return 'ACL';
}
/**
* Get user context.
*
* @param null $mode
*
* @return string
* user context.
*/
public function userContext($mode = NULL) {
return 'civicrm/acl';
}
/**
* Edit an ACL.
*
* @param int $mode
* What mode for the form ?.
* @param int $id
* Id of the entity (for update, view operations).
* @param bool $imageUpload
* Not used in this case, but extended from CRM_Core_Page_Basic.
* @param bool $pushUserContext
* Not used in this case, but extended from CRM_Core_Page_Basic.
*/
public function edit($mode, $id = NULL, $imageUpload = FALSE, $pushUserContext = TRUE) {
if ($mode & (CRM_Core_Action::UPDATE)) {
if (isset($id)) {
$aclName = CRM_Core_DAO::getFieldValue('CRM_ACL_DAO_ACL', $id);
CRM_Utils_System::setTitle(ts('Edit ACL &ndash; %1', array(1 => $aclName)));
}
}
parent::edit($mode, $id, $imageUpload, $pushUserContext);
}
}

View file

@ -0,0 +1,196 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Page_ACLBasic extends CRM_Core_Page_Basic {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Get BAO Name.
*
* @return string
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_ACL_BAO_ACL';
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/acl/basic',
'qs' => 'reset=1&action=update&id=%%id%%',
'title' => ts('Edit ACL'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/acl/basic',
'qs' => 'reset=1&action=delete&id=%%id%%',
'title' => ts('Delete ACL'),
),
);
}
return self::$_links;
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
* Finally it calls the parent's run method.
*/
public function run() {
$id = $this->getIdAndAction();
// set breadcrumb to append to admin/access
$breadCrumb = array(
array(
'title' => ts('Access Control'),
'url' => CRM_Utils_System::url('civicrm/admin/access', 'reset=1'),
),
);
CRM_Utils_System::appendBreadCrumb($breadCrumb);
// what action to take ?
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) {
$this->edit($this->_action, $id);
}
// finally browse the acl's
$this->browse();
// This replaces parent run, but do parent's parent run
return CRM_Core_Page::run();
}
/**
* Browse all acls.
*/
public function browse() {
// get all acl's sorted by weight
$acl = array();
$query = "
SELECT *
FROM civicrm_acl
WHERE ( object_table NOT IN ( 'civicrm_saved_search', 'civicrm_uf_group', 'civicrm_custom_group' ) )
ORDER BY entity_id
";
$dao = CRM_Core_DAO::executeQuery($query);
$roles = CRM_Core_OptionGroup::values('acl_role');
$permissions = CRM_Core_Permission::basicPermissions();
while ($dao->fetch()) {
if (!array_key_exists($dao->entity_id, $acl)) {
$acl[$dao->entity_id] = array();
$acl[$dao->entity_id]['name'] = $dao->name;
$acl[$dao->entity_id]['entity_id'] = $dao->entity_id;
$acl[$dao->entity_id]['entity_table'] = $dao->entity_table;
$acl[$dao->entity_id]['object_table'] = CRM_Utils_Array::value($dao->object_table, $permissions);
$acl[$dao->entity_id]['is_active'] = 1;
if ($acl[$dao->entity_id]['entity_id']) {
$acl[$dao->entity_id]['entity'] = $roles[$acl[$dao->entity_id]['entity_id']];
}
else {
$acl[$dao->entity_id]['entity'] = ts('Any Role');
}
// form all action links
$action = array_sum(array_keys($this->links()));
$acl[$dao->entity_id]['action'] = CRM_Core_Action::formLink(
self::links(),
$action,
array('id' => $dao->entity_id),
ts('more'),
FALSE,
'aclRole.manage.action',
'ACLRole',
$dao->entity_id
);
}
elseif (!empty($permissions[$dao->object_table])) {
$acl[$dao->entity_id]['object_table'] .= ", {$permissions[$dao->object_table]}";
}
}
$this->assign('rows', $acl);
}
/**
* Get name of edit form.
*
* @return string
* Classname of edit form.
*/
public function editForm() {
return 'CRM_ACL_Form_ACLBasic';
}
/**
* Get edit form name.
*
* @return string
* name of this page.
*/
public function editName() {
return 'Core ACLs';
}
/**
* Get user context.
*
* @param null $mode
*
* @return string
* user context.
*/
public function userContext($mode = NULL) {
return 'civicrm/acl/basic';
}
}

View file

@ -0,0 +1,206 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_ACL_Page_EntityRole extends CRM_Core_Page_Basic {
public $useLivePageJS = TRUE;
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Get BAO Name.
*
* @return string
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_ACL_BAO_EntityRole';
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/acl/entityrole',
'qs' => 'action=update&id=%%id%%',
'title' => ts('Edit ACL Role Assignment'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable ACL Role Assignment'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable ACL Role Assignment'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/acl/entityrole',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete ACL Role Assignment'),
),
);
}
return self::$_links;
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
* Finally it calls the parent's run method.
*/
public function run() {
$id = $this->getIdAndAction();
// set breadcrumb to append to admin/access
$breadCrumb = array(
array(
'title' => ts('Access Control'),
'url' => CRM_Utils_System::url('civicrm/admin/access',
'reset=1'
),
),
);
CRM_Utils_System::appendBreadCrumb($breadCrumb);
CRM_Utils_System::setTitle(ts('Assign Users to Roles'));
// what action to take ?
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) {
$this->edit($this->_action, $id);
}
// reset cache if enabled/disabled
if ($this->_action & (CRM_Core_Action::DISABLE | CRM_Core_Action::ENABLE)) {
CRM_ACL_BAO_Cache::resetCache();
}
// finally browse the acl's
if ($this->_action & CRM_Core_Action::BROWSE) {
$this->browse();
}
// This replaces parent run, but do parent's parent run
return CRM_Core_Page::run();
}
/**
* Browse all acls.
*/
public function browse() {
// get all acl's sorted by weight
$entityRoles = array();
$dao = new CRM_ACL_DAO_EntityRole();
$dao->find();
$aclRoles = CRM_Core_OptionGroup::values('acl_role');
$groups = CRM_Core_PseudoConstant::staticGroup();
while ($dao->fetch()) {
$entityRoles[$dao->id] = array();
CRM_Core_DAO::storeValues($dao, $entityRoles[$dao->id]);
$entityRoles[$dao->id]['acl_role'] = CRM_Utils_Array::value($dao->acl_role_id, $aclRoles);
$entityRoles[$dao->id]['entity'] = $groups[$dao->entity_id];
// form all action links
$action = array_sum(array_keys($this->links()));
if ($dao->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$action -= CRM_Core_Action::DISABLE;
}
$entityRoles[$dao->id]['action'] = CRM_Core_Action::formLink(
self::links(),
$action,
array('id' => $dao->id),
ts('more'),
FALSE,
'entityRole.manage.action',
'EntityRole',
$dao->id
);
}
$this->assign('rows', $entityRoles);
}
/**
* Get name of edit form.
*
* @return string
* Classname of edit form.
*/
public function editForm() {
return 'CRM_ACL_Form_EntityRole';
}
/**
* Get edit form name.
*
* @return string
* name of this page.
*/
public function editName() {
return 'ACL EntityRole';
}
/**
* Get user context.
*
* @param null $mode
*
* @return string
* user context.
*/
public function userContext($mode = NULL) {
return 'civicrm/acl/entityrole';
}
}

View file

@ -0,0 +1,138 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
use Civi\ActionSchedule\RecipientBuilder;
/**
* Class CRM_Activity_ActionMapping
*
* This defines the scheduled-reminder functionality for contact
* entities. It is useful for, e.g., sending a reminder based on
* birth date, modification date, or other custom dates on
* the contact record.
*/
class CRM_Activity_ActionMapping extends \Civi\ActionSchedule\Mapping {
/**
* The value for civicrm_action_schedule.mapping_id which identifies the
* "Activity" mapping.
*
* Note: This value is chosen to match legacy DB IDs.
*/
const ACTIVITY_MAPPING_ID = 1;
/**
* Register Activity-related action mappings.
*
* @param \Civi\ActionSchedule\Event\MappingRegisterEvent $registrations
*/
public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\MappingRegisterEvent $registrations) {
$registrations->register(CRM_Activity_ActionMapping::create(array(
'id' => CRM_Activity_ActionMapping::ACTIVITY_MAPPING_ID,
'entity' => 'civicrm_activity',
'entity_label' => ts('Activity'),
'entity_value' => 'activity_type',
'entity_value_label' => ts('Activity Type'),
'entity_status' => 'activity_status',
'entity_status_label' => ts('Activity Status'),
'entity_date_start' => 'activity_date_time',
)));
}
/**
* Get a list of recipient types.
*
* Note: A single schedule may filter on *zero* or *one* recipient types.
* When an admin chooses a value, it's stored in $schedule->recipient.
*
* @return array
* array(string $value => string $label).
* Ex: array('assignee' => 'Activity Assignee').
*/
public function getRecipientTypes() {
return \CRM_Core_OptionGroup::values('activity_contacts');
}
/**
* Generate a query to locate recipients who match the given
* schedule.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* The schedule as configured by the administrator.
* @param string $phase
* See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
*
* @param array $defaultParams
*
* @return \CRM_Utils_SQL_Select
* @see RecipientBuilder
*/
public function createQuery($schedule, $phase, $defaultParams) {
$selectedValues = (array) \CRM_Utils_Array::explodePadded($schedule->entity_value);
$selectedStatuses = (array) \CRM_Utils_Array::explodePadded($schedule->entity_status);
$query = \CRM_Utils_SQL_Select::from("{$this->entity} e")->param($defaultParams);
$query['casAddlCheckFrom'] = 'civicrm_activity e';
$query['casContactIdField'] = 'r.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
$query['casDateField'] = 'e.activity_date_time';
if (!is_null($schedule->limit_to)) {
$activityContacts = \CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
if ($schedule->limit_to == 0 || !isset($activityContacts[$schedule->recipient])) {
$recipientTypeId = \CRM_Utils_Array::key('Activity Targets', $activityContacts);
}
else {
$recipientTypeId = $schedule->recipient;
}
$query->join('r', "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$recipientTypeId}");
}
// build where clause
if (!empty($selectedValues)) {
$query->where("e.activity_type_id IN (#selectedValues)")
->param('selectedValues', $selectedValues);
}
else {
$query->where("e.activity_type_id IS NULL");
}
if (!empty($selectedStatuses)) {
$query->where("e.status_id IN (#selectedStatuss)")
->param('selectedStatuss', $selectedStatuses);
}
$query->where('e.is_current_revision = 1 AND e.is_deleted = 0');
return $query;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,158 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityAssignment extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add activity assignment.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* activity type of object that is added
*/
public static function create(&$params) {
$assignment = new CRM_Activity_BAO_ActivityContact();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$assignment->copyValues($params);
$assignment->record_type_id = $assigneeID;
return $assignment->save();
}
/**
* Retrieve assignee_id by activity_id.
*
* @param int $activity_id
*
* @return array
*/
public static function retrieveAssigneeIdsByActivityId($activity_id) {
$assigneeArray = array();
if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
return $assigneeArray;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$sql = "
SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = $assigneeID
AND civicrm_contact.is_deleted = 0
";
$assignment = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
while ($assignment->fetch()) {
$assigneeArray[] = $assignment->contact_id;
}
return $assigneeArray;
}
/**
* Retrieve assignee names by activity_id.
*
* @param array $activityIDs
* IDs of the activities.
* @param bool $isDisplayName
* If set returns display names of assignees.
* @param bool $skipDetails
* If false returns all details of assignee contact.
*
* @return array
*/
public static function getAssigneeNames($activityIDs, $isDisplayName = FALSE, $skipDetails = TRUE) {
$assigneeNames = array();
if (empty($activityIDs)) {
return $assigneeNames;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$whereClause = "";
if (!$skipDetails) {
$whereClause = " AND ce.is_primary= 1";
}
$inClause = implode(",", $activityIDs);
$query = "
SELECT contact_a.id, contact_a.sort_name, contact_a.display_name, ce.email,
civicrm_activity_contact.activity_id
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
LEFT JOIN civicrm_email ce ON ce.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id IN ( $inClause )
AND contact_a.is_deleted = 0
AND civicrm_activity_contact.record_type_id = $assigneeID
{$whereClause}
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
if (!$isDisplayName) {
$assigneeNames[$dao->id] = $dao->sort_name;
}
else {
if ($skipDetails) {
$assigneeNames[$dao->id] = $dao->display_name;
}
else {
$assigneeNames[$dao->id]['contact_id'] = $dao->id;
$assigneeNames[$dao->id]['display_name'] = $dao->display_name;
$assigneeNames[$dao->id]['sort_name'] = $dao->sort_name;
$assigneeNames[$dao->id]['email'] = $dao->email;
$assigneeNames[$dao->id]['role'] = ts('Activity Assignee');
$assigneeNames[$dao->id]['activity_id'] = $dao->activity_id;
}
}
}
return $assigneeNames;
}
}

View file

@ -0,0 +1,159 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityContact extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Function to add activity contact.
*
* @param array $params
* The values for this table: activity id, contact id, record type.
*
* @return object
* activity_contact object
*/
public static function create(&$params) {
$activityContact = new CRM_Activity_DAO_ActivityContact();
$activityContact->copyValues($params);
if (!$activityContact->find(TRUE)) {
return $activityContact->save();
}
return $activityContact;
}
/**
* Retrieve names of contact by activity_id.
*
* @param int $activityID
* @param int $recordTypeID
* @param bool $alsoIDs
*
* @return array
*/
public static function getNames($activityID, $recordTypeID, $alsoIDs = FALSE) {
$names = array();
$ids = array();
if (empty($activityID)) {
return $alsoIDs ? array($names, $ids) : $names;
}
$query = "
SELECT contact_a.id, contact_a.sort_name
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id = %1
AND civicrm_activity_contact.record_type_id = %2
AND contact_a.is_deleted = 0
";
$params = array(
1 => array($activityID, 'Integer'),
2 => array($recordTypeID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$names[$dao->id] = $dao->sort_name;
$ids[] = $dao->id;
}
return $alsoIDs ? array($names, $ids) : $names;
}
/**
* Retrieve id of target contact by activity_id.
*
* @param int $activityID
* @param int $recordTypeID
*
* @return mixed
*/
public static function retrieveContactIdsByActivityId($activityID, $recordTypeID) {
$activityContact = array();
if (!CRM_Utils_Rule::positiveInteger($activityID) ||
!CRM_Utils_Rule::positiveInteger($recordTypeID)
) {
return $activityContact;
}
$sql = " SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = %2
AND civicrm_contact.is_deleted = 0
";
$params = array(
1 => array($activityID, 'Integer'),
2 => array($recordTypeID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
$activityContact[] = $dao->contact_id;
}
return $activityContact;
}
/**
* Get the links associate array as defined by the links.ini file.
*
* Experimental... -
* Should look a bit like
* [local_col_name] => "related_tablename:related_col_name"
*
* @see DB_DataObject::getLinks()
* @see DB_DataObject::getLink()
*
* @return array|null
* array = if there are links defined for this table.
* empty array - if there is a links.ini file, but no links on this table
* null - if no links.ini exists for this database (hence try auto_links).
*/
public function links() {
$link = array('activity_id' => 'civicrm_activity:id');
return $link;
}
}

View file

@ -0,0 +1,129 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for activity assignment functions.
*/
class CRM_Activity_BAO_ActivityTarget extends CRM_Activity_DAO_ActivityContact {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add activity target.
*
* @param array $params
*
* @return object
* activity type of object that is added
*/
public static function create(&$params) {
$target = new CRM_Activity_BAO_ActivityContact();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$target->copyValues($params);
$target->record_type_id = $targetID;
return $target->save();
}
/**
* Retrieve id of target contact by activity_id.
*
* @param int $activity_id
*
* @return mixed
*/
public static function retrieveTargetIdsByActivityId($activity_id) {
$targetArray = array();
if (!CRM_Utils_Rule::positiveInteger($activity_id)) {
return $targetArray;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$sql = "
SELECT contact_id
FROM civicrm_activity_contact
INNER JOIN civicrm_contact ON contact_id = civicrm_contact.id
WHERE activity_id = %1
AND record_type_id = $targetID
AND civicrm_contact.is_deleted = 0
";
$target = CRM_Core_DAO::executeQuery($sql, array(1 => array($activity_id, 'Integer')));
while ($target->fetch()) {
$targetArray[] = $target->contact_id;
}
return $targetArray;
}
/**
* Retrieve names of target contact by activity_id.
*
* @param int $activityID
*
* @return array
*/
public static function getTargetNames($activityID) {
$targetNames = array();
if (empty($activityID)) {
return $targetNames;
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$query = "
SELECT contact_a.id, contact_a.sort_name
FROM civicrm_contact contact_a
INNER JOIN civicrm_activity_contact ON civicrm_activity_contact.contact_id = contact_a.id
WHERE civicrm_activity_contact.activity_id = %1
AND civicrm_activity_contact.record_type_id = $targetID
AND contact_a.is_deleted = 0
";
$queryParam = array(1 => array($activityID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $queryParam);
while ($dao->fetch()) {
$targetNames[$dao->id] = $dao->sort_name;
}
return $targetNames;
}
}

View file

@ -0,0 +1,137 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Generate ical invites for activities.
*/
class CRM_Activity_BAO_ICalendar {
/**
* @var object The activity for which we're generating ical.
*/
protected $activity;
/**
* Constructor.
*
* @param object $act
* Reference to an activity object.
*
* @return \CRM_Activity_BAO_ICalendar
*/
public function __construct(&$act) {
$this->activity = $act;
}
/**
* Add an ics attachment to the input array.
*
* @param array $attachments
* Reference to array in same format returned from CRM_Core_BAO_File::getEntityFile().
* @param array $contacts
* Array of contacts (attendees).
*
* @return string|null
* Array index of the added attachment in the $attachments array, else NULL.
*/
public function addAttachment(&$attachments, $contacts) {
// Check preferences setting
if (Civi::settings()->get('activity_assignee_notification_ics')) {
$config = &CRM_Core_Config::singleton();
$this->icsfile = tempnam($config->customFileUploadDir, 'ics');
if ($this->icsfile !== FALSE) {
rename($this->icsfile, $this->icsfile . '.ics');
$this->icsfile .= '.ics';
$icsFileName = basename($this->icsfile);
// get logged in user's primary email
// TODO: Is there a better way to do this?
$organizer = $this->getPrimaryEmail();
$template = CRM_Core_Smarty::singleton();
$template->assign('activity', $this->activity);
$template->assign('organizer', $organizer);
$template->assign('contacts', $contacts);
$template->assign('timezone', date_default_timezone_get());
$calendar = $template->fetch('CRM/Activity/Calendar/ICal.tpl');
if (file_put_contents($this->icsfile, $calendar) !== FALSE) {
if (empty($attachments)) {
$attachments = array();
}
$attachments['activity_ics'] = array(
'mime_type' => 'text/calendar',
'fileName' => $icsFileName,
'cleanName' => $icsFileName,
'fullPath' => $this->icsfile,
);
return 'activity_ics';
}
}
}
return NULL;
}
/**
* Remove temp file.
*/
public function cleanup() {
if (!empty ($this->icsfile)) {
@unlink($this->icsfile);
}
}
/**
* @todo Is there a better way to do this?
* @return string
*/
private function getPrimaryEmail() {
$uid = CRM_Core_Session::getLoggedInContactID();
$primary = '';
$emails = CRM_Core_BAO_Email::allEmails($uid);
foreach ($emails as $eid => $e) {
if ($e['is_primary']) {
if ($e['email']) {
$primary = $e['email'];
break;
}
}
if (count($emails) == 1) {
$primary = $e['email'];
break;
}
}
return $primary;
}
}

View file

@ -0,0 +1,652 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_BAO_Query {
/**
* Build select for Case.
*
* @param CRM_Contact_BAO_Query $query
*/
public static function select(&$query) {
if (!empty($query->_returnProperties['activity_id'])) {
$query->_select['activity_id'] = 'civicrm_activity.id as activity_id';
$query->_element['activity_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_type_id'])) {
$query->_select['activity_type_id'] = 'activity_type.value as activity_type_id';
$query->_element['activity_type_id'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_type'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_type'] = 1;
}
if (!empty($query->_returnProperties['activity_type'])) {
$query->_select['activity_type'] = 'activity_type.label as activity_type';
$query->_element['activity_type'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_type'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_type'] = 1;
}
if (!empty($query->_returnProperties['activity_subject'])) {
$query->_select['activity_subject'] = 'civicrm_activity.subject as activity_subject';
$query->_element['activity_subject'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_date_time'])) {
$query->_select['activity_date_time'] = 'civicrm_activity.activity_date_time as activity_date_time';
$query->_element['activity_date_time'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_status_id'])) {
$query->_select['activity_status_id'] = 'civicrm_activity.status_id as activity_status_id';
$query->_element['activity_status_id'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_status'])) {
$query->_select['activity_status'] = 'activity_status.label as activity_status,
civicrm_activity.status_id as status_id';
$query->_element['activity_status'] = 1;
$query->_tables['civicrm_activity'] = 1;
$query->_tables['activity_status'] = 1;
$query->_whereTables['civicrm_activity'] = 1;
$query->_whereTables['activity_status'] = 1;
}
if (!empty($query->_returnProperties['activity_duration'])) {
$query->_select['activity_duration'] = 'civicrm_activity.duration as activity_duration';
$query->_element['activity_duration'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_location'])) {
$query->_select['activity_location'] = 'civicrm_activity.location as activity_location';
$query->_element['activity_location'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_details'])) {
$query->_select['activity_details'] = 'civicrm_activity.details as activity_details';
$query->_element['activity_details'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['source_record_id'])) {
$query->_select['source_record_id'] = 'civicrm_activity.source_record_id as source_record_id';
$query->_element['source_record_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_is_test'])) {
$query->_select['activity_is_test'] = 'civicrm_activity.is_test as activity_is_test';
$query->_element['activity_is_test'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_campaign_id'])) {
$query->_select['activity_campaign_id'] = 'civicrm_activity.campaign_id as activity_campaign_id';
$query->_element['activity_campaign_id'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['activity_engagement_level'])) {
$query->_select['activity_engagement_level'] = 'civicrm_activity.engagement_level as activity_engagement_level';
$query->_element['activity_engagement_level'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (!empty($query->_returnProperties['source_contact'])) {
$query->_select['source_contact'] = 'source_contact.sort_name as source_contact';
$query->_element['source_contact'] = 1;
$query->_tables['source_contact'] = $query->_whereTables['source_contact'] = 1;
}
if (!empty($query->_returnProperties['activity_result'])) {
$query->_select['activity_result'] = 'civicrm_activity.result as activity_result';
$query->_element['result'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
if (CRM_Utils_Array::value('parent_id', $query->_returnProperties)) {
$query->_tables['parent_id'] = 1;
$query->_whereTables['parent_id'] = 1;
$query->_element['parent_id'] = 1;
}
if (!empty($query->_returnProperties['activity_priority'])) {
$query->_select['activity_priority'] = 'activity_priority.label as activity_priority,
civicrm_activity.priority_id as priority_id';
$query->_element['activity_priority'] = 1;
$query->_tables['activity_priority'] = 1;
$query->_whereTables['activity_priority'] = 1;
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
}
}
/**
* Given a list of conditions in query generate the required where clause.
*
* @param $query
*/
public static function where(&$query) {
foreach (array_keys($query->_params) as $id) {
if (substr($query->_params[$id][0], 0, 9) == 'activity_') {
if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$query->_params[$id][3];
self::whereClauseSingle($query->_params[$id], $query);
}
}
}
/**
* Where clause for a single field.
*
* @param array $values
* @param CRM_Contact_BAO_Query $query
*/
public static function whereClauseSingle(&$values, &$query) {
list($name, $op, $value, $grouping) = $values;
$fields = CRM_Activity_BAO_Activity::exportableFields();
$query->_tables['civicrm_activity'] = $query->_whereTables['civicrm_activity'] = 1;
if ($query->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
$query->_skipDeleteClause = TRUE;
}
switch ($name) {
case 'activity_type_id':
case 'activity_status_id':
case 'activity_engagement_level':
case 'activity_id':
case 'activity_campaign_id':
case 'activity_priority_id':
// We no longer expect "subject" as a specific criteria (as of CRM-19447),
// but we still use activity_subject in Activity.Get API
case 'activity_subject':
$qillName = $name;
if (in_array($name, array('activity_engagement_level', 'activity_id'))) {
$name = $qillName = str_replace('activity_', '', $name);
}
if (in_array($name, array('activity_status_id', 'activity_subject', 'activity_priority_id'))) {
$name = str_replace('activity_', '', $name);
$qillName = str_replace('_id', '', $qillName);
}
if ($name == 'activity_campaign_id') {
$name = 'campaign_id';
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_activity.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
break;
case 'activity_text':
self::whereClauseSingleActivityText($values, $query);
break;
case 'activity_type':
case 'activity_status':
case 'activity_priority':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$name.label", $op, $value, 'String');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$name]['title'], 2 => $op, 3 => $value));
$query->_tables[$name] = $query->_whereTables[$name] = 1;
break;
case 'activity_survey_id':
if (!$value) {
break;
}
$value = CRM_Utils_Type::escape($value, 'Integer');
$query->_where[$grouping][] = " civicrm_activity.source_record_id = $value";
$query->_qill[$grouping][] = ts('Survey') . ' - ' . CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $value, 'title');
break;
case 'activity_role':
CRM_Contact_BAO_Query::$_activityRole = $values[2];
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
if ($values[2]) {
$query->_tables['civicrm_activity_contact'] = $query->_whereTables['civicrm_activity_contact'] = 1;
if ($values[2] == 1) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $sourceID";
$query->_qill[$grouping][] = ts('Activity created by');
}
elseif ($values[2] == 2) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $assigneeID";
$query->_qill[$grouping][] = ts('Activity assigned to');
}
elseif ($values[2] == 3) {
$query->_where[$grouping][] = " civicrm_activity_contact.record_type_id = $targetID";
$query->_qill[$grouping][] = ts('Activity targeted to');
}
}
break;
case 'activity_test':
// We don't want to include all tests for sql OR CRM-7827
if (!$value || $query->getOperator() != 'OR') {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_activity.is_test", $op, $value, "Boolean");
if ($value) {
$query->_qill[$grouping][] = ts('Activity is a Test');
}
}
break;
case 'activity_date':
case 'activity_date_low':
case 'activity_date_high':
$query->dateQueryBuilder($values,
'civicrm_activity', 'activity_date', 'activity_date_time', ts('Activity Date')
);
break;
case 'activity_taglist':
$taglist = $value;
$value = array();
foreach ($taglist as $val) {
if ($val) {
$val = explode(',', $val);
foreach ($val as $tId) {
if (is_numeric($tId)) {
$value[$tId] = 1;
}
}
}
}
case 'activity_tags':
$value = array_keys($value);
$activityTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
$names = array();
if (is_array($value)) {
foreach ($value as $k => $v) {
$names[] = $activityTags[$v];
}
}
$query->_where[$grouping][] = "civicrm_activity_tag.tag_id IN (" . implode(",", $value) . ")";
$query->_qill[$grouping][] = ts('Activity Tag %1', array(1 => $op)) . ' ' . implode(' ' . ts('OR') . ' ', $names);
$query->_tables['civicrm_activity_tag'] = $query->_whereTables['civicrm_activity_tag'] = 1;
break;
case 'activity_result':
if (is_array($value)) {
$safe = NULL;
while (list(, $k) = each($value)) {
$safe[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
}
$query->_where[$grouping][] = "civicrm_activity.result IN (" . implode(',', $safe) . ")";
$query->_qill[$grouping][] = ts("Activity Result - %1", array(1 => implode(' or ', $safe)));
}
break;
case 'parent_id':
if ($value == 1) {
$query->_where[$grouping][] = "parent_id.parent_id IS NOT NULL";
$query->_qill[$grouping][] = ts('Activities which have Followup Activities');
}
elseif ($value == 2) {
$query->_where[$grouping][] = "parent_id.parent_id IS NULL";
$query->_qill[$grouping][] = ts('Activities without Followup Activities');
}
break;
case 'followup_parent_id':
if ($value == 1) {
$query->_where[$grouping][] = "civicrm_activity.parent_id IS NOT NULL";
$query->_qill[$grouping][] = ts('Activities which are Followup Activities');
}
elseif ($value == 2) {
$query->_where[$grouping][] = "civicrm_activity.parent_id IS NULL";
$query->_qill[$grouping][] = ts('Activities which are not Followup Activities');
}
break;
}
}
/**
* @param string $name
* @param $mode
* @param $side
*
* @return null|string
*/
public static function from($name, $mode, $side) {
$from = NULL;
switch ($name) {
case 'civicrm_activity':
//CRM-7480 we are going to civicrm_activity table either
//from civicrm_activity_target or civicrm_activity_assignment.
//as component specific activities does not have entry in
//activity target table so lets consider civicrm_activity_assignment.
$from .= " $side JOIN civicrm_activity_contact
ON ( civicrm_activity_contact.contact_id = contact_a.id ) ";
$from .= " $side JOIN civicrm_activity
ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )";
// Do not show deleted contact's activity
$from .= " INNER JOIN civicrm_contact
ON ( civicrm_activity_contact.contact_id = civicrm_contact.id and civicrm_contact.is_deleted != 1 )";
break;
case 'activity_status':
$from .= " $side JOIN civicrm_option_group option_group_activity_status ON (option_group_activity_status.name = 'activity_status')";
$from .= " $side JOIN civicrm_option_value activity_status ON (civicrm_activity.status_id = activity_status.value
AND option_group_activity_status.id = activity_status.option_group_id ) ";
break;
case 'activity_type':
$from .= " $side JOIN civicrm_option_group option_group_activity_type ON (option_group_activity_type.name = 'activity_type')";
$from .= " $side JOIN civicrm_option_value activity_type ON (civicrm_activity.activity_type_id = activity_type.value
AND option_group_activity_type.id = activity_type.option_group_id ) ";
break;
case 'activity_priority':
$from .= " $side JOIN civicrm_option_group option_group_activity_priority ON (option_group_activity_priority.name = 'priority')";
$from .= " $side JOIN civicrm_option_value activity_priority ON (civicrm_activity.priority_id = activity_priority.value
AND option_group_activity_priority.id = activity_priority.option_group_id ) ";
break;
case 'civicrm_activity_tag':
$from .= " $side JOIN civicrm_entity_tag as civicrm_activity_tag ON ( civicrm_activity_tag.entity_table = 'civicrm_activity' AND civicrm_activity_tag.entity_id = civicrm_activity.id ) ";
break;
case 'source_contact':
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$from = "
LEFT JOIN civicrm_activity_contact ac
ON ( ac.activity_id = civicrm_activity_contact.activity_id AND ac.record_type_id = {$sourceID})
INNER JOIN civicrm_contact source_contact ON (ac.contact_id = source_contact.id)";
break;
case 'parent_id':
$from = "$side JOIN civicrm_activity AS parent_id ON civicrm_activity.id = parent_id.parent_id";
break;
}
return $from;
}
/**
* Add all the elements shared between case activity search and advanced search.
*
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
$form->addSelect('activity_type_id',
array('entity' => 'activity', 'label' => ts('Activity Type(s)'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
CRM_Core_Form_Date::buildDateRange($form, 'activity_date', 1, '_low', '_high', ts('From'), FALSE, FALSE);
$form->addElement('hidden', 'activity_date_range_error');
$form->addFormRule(array('CRM_Activity_BAO_Query', 'formRule'), $form);
$followUpActivity = array(
1 => ts('Yes'),
2 => ts('No'),
);
$form->addRadio('parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
$form->addRadio('followup_parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
$activityRoles = array(
3 => ts('With'),
2 => ts('Assigned to'),
1 => ts('Added by'),
);
$form->addRadio('activity_role', NULL, $activityRoles, array('allowClear' => TRUE));
$form->setDefaults(array('activity_role' => 3));
$activityStatus = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'status_id', array('flip' => 1, 'labelColumn' => 'name'));
$form->addSelect('status_id',
array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$ssID = $form->get('ssID');
$status = array($activityStatus['Completed'], $activityStatus['Scheduled']);
//If status is saved in smart group.
if (!empty($ssID) && !empty($form->_formValues['activity_status_id'])) {
$status = $form->_formValues['activity_status_id'];
}
$form->setDefaults(array('status_id' => $status));
$form->addElement('text', 'activity_text', ts('Activity Text'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
$form->addRadio('activity_option', '', CRM_Core_SelectValues::activityTextOptions());
$form->setDefaults(array('activity_option' => 'both'));
$priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
$form->addSelect('priority_id',
array('entity' => 'activity', 'label' => ts('Priority'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$form->addYesNo('activity_test', ts('Activity is a Test?'));
$activity_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
if ($activity_tags) {
foreach ($activity_tags as $tagID => $tagName) {
$form->_tagElement = &$form->addElement('checkbox', "activity_tags[$tagID]",
NULL, $tagName
);
}
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_activity', NULL, TRUE, TRUE);
$surveys = CRM_Campaign_BAO_Survey::getSurveys(TRUE, FALSE, FALSE, TRUE);
if ($surveys) {
$form->add('select', 'activity_survey_id', ts('Survey / Petition'),
array('' => ts('- none -')) + $surveys, FALSE,
array('class' => 'crm-select2')
);
}
CRM_Core_BAO_Query::addCustomFormFields($form, array('Activity'));
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'activity_campaign_id');
// Add engagement level CRM-7775.
$buildEngagementLevel = FALSE;
$buildSurveyResult = FALSE;
if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
CRM_Campaign_BAO_Campaign::accessCampaign()
) {
$buildEngagementLevel = TRUE;
$form->addSelect('activity_engagement_level', array('entity' => 'activity', 'context' => 'search'));
// Add survey result field.
$optionGroups = CRM_Campaign_BAO_Survey::getResultSets('name');
$resultOptions = array();
foreach ($optionGroups as $gid => $name) {
if ($name) {
$value = CRM_Core_OptionGroup::values($name);
if (!empty($value)) {
while (list($k, $v) = each($value)) {
$resultOptions[$v] = $v;
}
}
}
}
// If no survey result options have been created, don't build
// the field to avoid clutter.
if (count($resultOptions) > 0) {
$buildSurveyResult = TRUE;
asort($resultOptions);
$form->add('select', 'activity_result', ts("Survey Result"),
$resultOptions, FALSE,
array('id' => 'activity_result', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
}
}
$form->assign('buildEngagementLevel', $buildEngagementLevel);
$form->assign('buildSurveyResult', $buildSurveyResult);
$form->setDefaults(array('activity_test' => 0));
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
$properties = array(
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'activity_type' => 1,
'activity_type_id' => 1,
'activity_subject' => 1,
'activity_date_time' => 1,
'activity_duration' => 1,
'activity_location' => 1,
'activity_details' => 1,
'activity_status' => 1,
'activity_priority' => 1,
'source_contact' => 1,
'source_record_id' => 1,
'activity_is_test' => 1,
'activity_campaign_id' => 1,
'result' => 1,
'activity_engagement_level' => 1,
'parent_id' => 1,
);
if ($includeCustomFields) {
// also get all the custom activity properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Activity');
if (!empty($fields)) {
foreach ($fields as $name => $dontCare) {
$properties[$name] = 1;
}
}
}
}
return $properties;
}
/**
* Get the list of fields required to populate the selector.
*
* The default return properties array returns far too many fields for 'everyday use. Every field you add to this array
* kills a small kitten so add carefully.
*/
public static function selectorReturnProperties() {
$properties = array(
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'activity_type_id' => 1,
'activity_subject' => 1,
'activity_date_time' => 1,
'activity_status_id' => 1,
'source_contact' => 1,
'source_record_id' => 1,
'activity_is_test' => 1,
'activity_campaign_id' => 1,
'activity_engagement_level' => 1,
);
return $properties;
}
/**
* Custom form rules.
*
* @param array $fields
* @param array $files
* @param CRM_Core_Form $form
*
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
$errors = array();
if (empty($fields['activity_date_low']) || empty($fields['activity_date_high'])) {
return TRUE;
}
CRM_Utils_Rule::validDateRange($fields, 'activity_date', $errors, ts('Activity Date'));
return empty($errors) ? TRUE : $errors;
}
/**
* Where/qill clause for notes
*
* @param array $values
*/
public static function whereClauseSingleActivityText(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
$activityOptionValues = $query->getWhereValues('activity_option', $grouping);
$activityOption = CRM_Utils_Array::value(2, $activityOptionValues, 6);
$query->_useDistinct = TRUE;
$label = ts('Activity Text (%1)', array(1 => CRM_Utils_Array::value($activityOption, CRM_Core_SelectValues::activityTextOptions())));
$clauses = array();
if ($activityOption % 2 == 0) {
$clauses[] = $query->buildClause('civicrm_activity.details', $op, $value, 'String');
}
if ($activityOption % 3 == 0) {
$clauses[] = $query->buildClause('civicrm_activity.subject', $op, $value, 'String');
}
$query->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
list($qillOp, $qillVal) = $query->buildQillForFieldValue(NULL, $name, $value, $op);
$query->_qill[$grouping][] = ts("%1 %2 '%3'", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used by the Search functionality.
*
* - the search controller is used for building/processing multiform
* searches.
*
* Typically the first form will display the search criteria and it's results
*
* The second form is used to process search results with the associated actions
*
*/
class CRM_Activity_Controller_Search extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param null $title
* @param bool $modal
* @param int|mixed|null $action
*/
public function __construct($title = NULL, $modal = TRUE, $action = CRM_Core_Action::NONE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Activity_StateMachine_Search($this, $action);
// Create and instantiate the pages.
$this->addPages($this->_stateMachine, $action);
// Add all the actions.
$this->addActions();
}
/**
* Getter for selectorName.
*
* @return mixed
*/
public function selectorName() {
return $this->get('selectorName');
}
}

View file

@ -0,0 +1,808 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Activity/Activity.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:dfa63754ef6ea1a9c7148e735dd6ff8a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Activity_DAO_Activity constructor.
*/
class CRM_Activity_DAO_Activity extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_activity';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Unique Other Activity ID
*
* @var int unsigned
*/
public $id;
/**
* Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.
*
* @var int unsigned
*/
public $source_record_id;
/**
* FK to civicrm_option_value.id, that has to be valid, registered activity type.
*
* @var int unsigned
*/
public $activity_type_id;
/**
* The subject/purpose/short description of the activity.
*
* @var string
*/
public $subject;
/**
* Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.
*
* @var datetime
*/
public $activity_date_time;
/**
* Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.
*
* @var int unsigned
*/
public $duration;
/**
* Location of the activity (optional, open text).
*
* @var string
*/
public $location;
/**
* Phone ID of the number called (optional - used if an existing phone number is selected).
*
* @var int unsigned
*/
public $phone_id;
/**
* Phone number in case the number does not exist in the civicrm_phone table.
*
* @var string
*/
public $phone_number;
/**
* Details about the activity (agenda, notes, etc).
*
* @var longtext
*/
public $details;
/**
* ID of the status this activity is currently in. Foreign key to civicrm_option_value.
*
* @var int unsigned
*/
public $status_id;
/**
* ID of the priority given to this activity. Foreign key to civicrm_option_value.
*
* @var int unsigned
*/
public $priority_id;
/**
* Parent meeting ID (if this is a follow-up item). This is not currently implemented
*
* @var int unsigned
*/
public $parent_id;
/**
*
* @var boolean
*/
public $is_test;
/**
* Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.
*
* @var int unsigned
*/
public $medium_id;
/**
*
* @var boolean
*/
public $is_auto;
/**
* FK to Relationship ID
*
* @var int unsigned
*/
public $relationship_id;
/**
*
* @var boolean
*/
public $is_current_revision;
/**
* Activity ID of the first activity record in versioning chain.
*
* @var int unsigned
*/
public $original_id;
/**
* Currently being used to store result id for survey activity, FK to option value.
*
* @var string
*/
public $result;
/**
*
* @var boolean
*/
public $is_deleted;
/**
* The campaign for which this activity has been triggered.
*
* @var int unsigned
*/
public $campaign_id;
/**
* Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.
*
* @var int unsigned
*/
public $engagement_level;
/**
*
* @var int
*/
public $weight;
/**
* Activity marked as favorite.
*
* @var boolean
*/
public $is_star;
/**
* When was the activity was created.
*
* @var timestamp
*/
public $created_date;
/**
* When was the activity (or closely related entity) was created or modified or deleted.
*
* @var timestamp
*/
public $modified_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_activity';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'phone_id', 'civicrm_phone', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'relationship_id', 'civicrm_relationship', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'original_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'activity_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity ID') ,
'description' => 'Unique Other Activity ID',
'required' => true,
'import' => true,
'where' => 'civicrm_activity.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'source_record_id' => array(
'name' => 'source_record_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Source Record') ,
'description' => 'Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_type_id' => array(
'name' => 'activity_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Type ID') ,
'description' => 'FK to civicrm_option_value.id, that has to be valid, registered activity type.',
'required' => true,
'import' => true,
'where' => 'civicrm_activity.activity_type_id',
'headerPattern' => '/(activity.)?type(.id$)/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_type',
'optionEditPath' => 'civicrm/admin/options/activity_type',
)
) ,
'activity_subject' => array(
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Subject') ,
'description' => 'The subject/purpose/short description of the activity.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_activity.subject',
'headerPattern' => '/(activity.)?subject/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_date_time' => array(
'name' => 'activity_date_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Activity Date') ,
'description' => 'Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.',
'import' => true,
'where' => 'civicrm_activity.activity_date_time',
'headerPattern' => '/(activity.)?date(.time$)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'activity_duration' => array(
'name' => 'duration',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Duration') ,
'description' => 'Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.',
'import' => true,
'where' => 'civicrm_activity.duration',
'headerPattern' => '/(activity.)?duration(s)?$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_location' => array(
'name' => 'location',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Location') ,
'description' => 'Location of the activity (optional, open text).',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_activity.location',
'headerPattern' => '/(activity.)?location$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'phone_id' => array(
'name' => 'phone_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Phone (called) ID') ,
'description' => 'Phone ID of the number called (optional - used if an existing phone number is selected).',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Phone',
'html' => array(
'type' => 'EntityRef',
) ,
) ,
'phone_number' => array(
'name' => 'phone_number',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Phone (called) Number') ,
'description' => 'Phone number in case the number does not exist in the civicrm_phone table.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_details' => array(
'name' => 'details',
'type' => CRM_Utils_Type::T_LONGTEXT,
'title' => ts('Details') ,
'description' => 'Details about the activity (agenda, notes, etc).',
'import' => true,
'where' => 'civicrm_activity.details',
'headerPattern' => '/(activity.)?detail(s)?$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'activity_status_id' => array(
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Status') ,
'description' => 'ID of the status this activity is currently in. Foreign key to civicrm_option_value.',
'import' => true,
'where' => 'civicrm_activity.status_id',
'headerPattern' => '/(activity.)?status(.label$)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_status',
'optionEditPath' => 'civicrm/admin/options/activity_status',
)
) ,
'priority_id' => array(
'name' => 'priority_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Priority') ,
'description' => 'ID of the priority given to this activity. Foreign key to civicrm_option_value.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'priority',
'optionEditPath' => 'civicrm/admin/options/priority',
)
) ,
'parent_id' => array(
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Parent Activity Id') ,
'description' => 'Parent meeting ID (if this is a follow-up item). This is not currently implemented',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'activity_is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_activity.is_test',
'headerPattern' => '/(is.)?test(.activity)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
) ,
'activity_medium_id' => array(
'name' => 'medium_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Medium') ,
'description' => 'Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'encounter_medium',
'optionEditPath' => 'civicrm/admin/options/encounter_medium',
)
) ,
'is_auto' => array(
'name' => 'is_auto',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Auto') ,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'relationship_id' => array(
'name' => 'relationship_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Relationship Id') ,
'description' => 'FK to Relationship ID',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Relationship',
) ,
'is_current_revision' => array(
'name' => 'is_current_revision',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is this activity a current revision in versioning chain?') ,
'import' => true,
'where' => 'civicrm_activity.is_current_revision',
'headerPattern' => '/(is.)?(current.)?(revision|version(ing)?)/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'original_id' => array(
'name' => 'original_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Original Activity ID ') ,
'description' => 'Activity ID of the first activity record in versioning chain.',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'activity_result' => array(
'name' => 'result',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Result') ,
'description' => 'Currently being used to store result id for survey activity, FK to option value.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_is_deleted' => array(
'name' => 'is_deleted',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Activity is in the Trash') ,
'import' => true,
'where' => 'civicrm_activity.is_deleted',
'headerPattern' => '/(activity.)?(trash|deleted)/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'activity_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this activity has been triggered.',
'import' => true,
'where' => 'civicrm_activity.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'html' => array(
'type' => 'CheckBox',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'activity_engagement_level' => array(
'name' => 'engagement_level',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Engagement Index') ,
'description' => 'Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.',
'import' => true,
'where' => 'civicrm_activity.engagement_level',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'engagement_index',
'optionEditPath' => 'civicrm/admin/options/engagement_index',
)
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'is_star' => array(
'name' => 'is_star',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Starred') ,
'description' => 'Activity marked as favorite.',
'import' => true,
'where' => 'civicrm_activity.is_star',
'headerPattern' => '/(activity.)?(star|favorite)/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_created_date' => array(
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Created Date') ,
'description' => 'When was the activity was created.',
'required' => false,
'export' => true,
'where' => 'civicrm_activity.created_date',
'headerPattern' => '',
'dataPattern' => '',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
'activity_modified_date' => array(
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
'title' => ts('Modified Date') ,
'description' => 'When was the activity (or closely related entity) was created or modified or deleted.',
'required' => false,
'export' => true,
'where' => 'civicrm_activity.modified_date',
'headerPattern' => '',
'dataPattern' => '',
'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_source_record_id' => array(
'name' => 'UI_source_record_id',
'field' => array(
0 => 'source_record_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::source_record_id',
) ,
'UI_activity_type_id' => array(
'name' => 'UI_activity_type_id',
'field' => array(
0 => 'activity_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::activity_type_id',
) ,
'index_activity_date_time' => array(
'name' => 'index_activity_date_time',
'field' => array(
0 => 'activity_date_time',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::activity_date_time',
) ,
'index_status_id' => array(
'name' => 'index_status_id',
'field' => array(
0 => 'status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::status_id',
) ,
'index_medium_id' => array(
'name' => 'index_medium_id',
'field' => array(
0 => 'medium_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::medium_id',
) ,
'index_is_current_revision' => array(
'name' => 'index_is_current_revision',
'field' => array(
0 => 'is_current_revision',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::is_current_revision',
) ,
'index_is_deleted' => array(
'name' => 'index_is_deleted',
'field' => array(
0 => 'is_deleted',
) ,
'localizable' => false,
'sig' => 'civicrm_activity::0::is_deleted',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,247 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Activity/ActivityContact.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:7a410e20f48318deeb83f3dd1900983a)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Activity_DAO_ActivityContact constructor.
*/
class CRM_Activity_DAO_ActivityContact extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_activity_contact';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Activity contact id
*
* @var int unsigned
*/
public $id;
/**
* Foreign key to the activity for this record.
*
* @var int unsigned
*/
public $activity_id;
/**
* Foreign key to the contact for this record.
*
* @var int unsigned
*/
public $contact_id;
/**
* Nature of this contact's role in the activity: 1 assignee, 2 creator, 3 focus or target.
*
* @var int unsigned
*/
public $record_type_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_activity_contact';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'activity_id', 'civicrm_activity', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity Contact ID') ,
'description' => 'Activity contact id',
'required' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
) ,
'activity_id' => array(
'name' => 'activity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Activity ID') ,
'description' => 'Foreign key to the activity for this record.',
'required' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID (match to contact)') ,
'description' => 'Foreign key to the contact for this record.',
'required' => true,
'import' => true,
'where' => 'civicrm_activity_contact.contact_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'record_type_id' => array(
'name' => 'record_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Record Type ID') ,
'description' => 'Nature of this contact\'s role in the activity: 1 assignee, 2 creator, 3 focus or target.',
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'activity_contacts',
'optionEditPath' => 'civicrm/admin/options/activity_contacts',
)
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity_contact', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity_contact', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_activity_contact' => array(
'name' => 'UI_activity_contact',
'field' => array(
0 => 'contact_id',
1 => 'activity_id',
2 => 'record_type_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_activity_contact::1::contact_id::activity_id::record_type_id',
) ,
'index_record_type' => array(
'name' => 'index_record_type',
'field' => array(
0 => 'activity_id',
1 => 'record_type_id',
) ,
'localizable' => false,
'sig' => 'civicrm_activity_contact::0::activity_id::record_type_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,82 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Activity Filter.
*/
class CRM_Activity_Form_ActivityFilter extends CRM_Core_Form {
public function buildQuickForm() {
// add activity search filter
$activityOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
asort($activityOptions);
$this->add('select', 'activity_type_filter_id', ts('Include'), array('' => ts('- all activity type(s) -')) + $activityOptions);
$this->add('select', 'activity_type_exclude_filter_id', ts('Exclude'), array('' => ts('- select activity type -')) + $activityOptions);
CRM_Core_Form_Date::buildDateRange(
$this, 'activity_date', 1,
'_low', '_high', ts('From:'),
FALSE, array(), 'searchDate',
FALSE, array('class' => 'crm-select2 medium')
);
$this->addSelect('status_id',
array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
);
$this->assign('suppressForm', TRUE);
}
/**
* This virtual function is used to set the default values of
* various form elements
*
* access public
*
* @return array
* reference to the array of default values
*/
public function setDefaultValues() {
// CRM-11761 retrieve user's activity filter preferences
$defaults = array();
if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
$defaults = Civi::service('settings_manager')
->getBagByContact(NULL, $userID)
->get('activity_tab_filter');
}
// set Activity status 'Scheduled' by default only for dashlet
elseif (strstr(CRM_Utils_Array::value('q', $_GET), 'dashlet')) {
$defaults['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
}
return $defaults;
}
}

View file

@ -0,0 +1,107 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Activity Links.
*/
class CRM_Activity_Form_ActivityLinks extends CRM_Core_Form {
public function buildQuickForm() {
self::commonBuildQuickForm($this);
}
/**
* @param $self
*/
public static function commonBuildQuickForm($self) {
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $self);
if (!$contactId) {
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST);
}
$urlParams = "action=add&reset=1&cid={$contactId}&selectedChild=activity&atype=";
$allTypes = CRM_Utils_Array::value('values', civicrm_api3('OptionValue', 'get', array(
'option_group_id' => 'activity_type',
'is_active' => 1,
'options' => array('limit' => 0, 'sort' => 'weight'),
)));
$activityTypes = array();
foreach ($allTypes as $act) {
$url = 'civicrm/activity/add';
if ($act['name'] == 'Email') {
if (!CRM_Utils_Mail::validOutBoundMail() || !$contactId) {
continue;
}
list($name, $email, $doNotEmail, $onHold, $isDeceased) = CRM_Contact_BAO_Contact::getContactDetails($contactId);
if (!$doNotEmail && $email && !$isDeceased) {
$url = 'civicrm/activity/email/add';
$act['label'] = ts('Send an Email');
}
else {
continue;
}
}
elseif ($act['name'] == 'SMS') {
if (!$contactId || !CRM_SMS_BAO_Provider::activeProviderCount()) {
continue;
}
// Check for existence of a mobile phone and ! do not SMS privacy setting
$mobileTypeID = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile');
list($name, $phone, $doNotSMS) = CRM_Contact_BAO_Contact_Location::getPhoneDetails($contactId, $mobileTypeID);
if (!$doNotSMS && $phone) {
$url = 'civicrm/activity/sms/add';
}
else {
continue;
}
}
elseif ($act['name'] == 'Print PDF Letter') {
$url = 'civicrm/activity/pdf/add';
}
elseif (!empty($act['filter']) || (!empty($act['component_id']) && $act['component_id'] != '1')) {
continue;
}
$act['url'] = CRM_Utils_System::url($url,
"{$urlParams}{$act['value']}", FALSE, NULL, FALSE
);
$act += array('icon' => 'fa-plus-square-o');
$activityTypes[$act['value']] = $act;
}
$self->assign('activityTypes', $activityTypes);
$self->assign('suppressForm', TRUE);
}
}

View file

@ -0,0 +1,128 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class handle activity view mode.
*/
class CRM_Activity_Form_ActivityView extends CRM_Core_Form {
/**
* Set variables up before form is built.
*/
public function preProcess() {
// Get the activity values.
$activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
// Check for required permissions, CRM-6264.
if ($activityId &&
!CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)
) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$session = CRM_Core_Session::singleton();
if (!in_array($context, array(
'home',
'dashlet',
'dashletFullscreen',
))
) {
$url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity");
}
else {
$url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
}
$session->pushUserContext($url);
$defaults = array();
$params = array('id' => $activityId);
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
// Set activity type name and description to template.
list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']);
$this->assign('activityTypeName', $activityTypeName);
$this->assign('activityTypeDescription', $activityTypeDescription);
if (!empty($defaults['mailingId'])) {
$this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults);
$mailingReport = CRM_Mailing_BAO_Mailing::report($this->_mailing_id, TRUE);
CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this);
$this->assign('mailingReport', $mailingReport);
$full_open_report = CRM_Mailing_Event_BAO_Opened::getRows(
$this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, $cid);
$this->assign('openreport', $full_open_report);
$click_thru_report = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, NULL, $cid);
$this->assign('clickreport', $click_thru_report);
}
foreach ($defaults as $key => $value) {
if (substr($key, -3) != '_id') {
$values[$key] = $value;
}
}
// Get the campaign.
if ($campaignId = CRM_Utils_Array::value('campaign_id', $defaults)) {
$campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
$values['campaign'] = $campaigns[$campaignId];
}
if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $defaults)) {
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
$values['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
}
$values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
$this->assign('values', $values);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,417 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This file is for activity search.
*/
class CRM_Activity_Form_Search extends CRM_Core_Form_Search {
/**
* The params that are sent to the query.
*
* @var array
*/
protected $_queryParams;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* Prefix for the controller.
*/
protected $_prefix = "activity_";
/**
* The saved search ID retrieved from the GET vars.
*
* @var int
*/
protected $_ssID;
/**
* Processing needed for buildForm and later.
*/
public function preProcess() {
$this->set('searchFormName', 'Search');
// set the button names
$this->_searchButtonName = $this->getButtonName('refresh');
$this->_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
$this->defaults = array();
// we allow the controller to set force/reset externally, useful when we are being
// driven by the wizard framework
$this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
$this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
$this->assign("context", $this->_context);
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
if (!empty($_POST) && !$this->controller->isModal()) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
else {
$this->_formValues = $this->get('formValues');
if ($this->_force) {
// If we force the search then merge form values with url values
// and set submit values to form values.
$this->_formValues = array_merge((array) $this->_formValues, CRM_Utils_Request::exportValues());
$this->_submitValues = $this->_formValues;
}
}
if (empty($this->_formValues)) {
if (isset($this->_ssID)) {
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
}
if ($this->_force) {
$this->postProcess();
$this->set('force', 0);
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Activity_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::TRANSFER,
$prefix
);
$controller->setEmbedded(TRUE);
$controller->moveFromSessionToTemplate();
$this->assign('summary', $this->get('summary'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addSortNameField();
CRM_Activity_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
if (!$this->_single) {
$this->addRowSelectors($rows);
}
$permission = CRM_Core_Permission::getPermission();
$this->addTaskMenu(CRM_Activity_Task::permissionedTaskTitles($permission));
}
}
/**
* The post processing of the form gets done here.
*
* Key things done during post processing are
* - check for reset or next request. if present, skip post procesing.
* - now check if user requested running a saved search, if so, then
* the form values associated with the saved search are used for searching.
* - if user has done a submit with new values the regular post submissing is
* done.
*
* The processing consists of using a Selector / Controller framework for getting the
* search results.
*/
public function postProcess() {
if ($this->_done) {
return;
}
$this->_done = TRUE;
if (!empty($_POST)) {
$this->_formValues = $this->controller->exportValues($this->_name);
$specialParams = array(
'activity_type_id',
'status_id',
'priority_id',
'activity_text',
);
$changeNames = array(
'status_id' => 'activity_status_id',
'priority_id' => 'activity_priority_id',
);
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, $specialParams, $changeNames);
}
$this->fixFormValues();
if (isset($this->_ssID) && empty($_POST)) {
// if we are editing / running a saved search and the form has not been posted
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
// We don't show test records in summaries or dashboards
if (empty($this->_formValues['activity_test']) && $this->_force) {
$this->_formValues["activity_test"] = 0;
}
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_actionButtonName) {
// check actionName and if next, then do not repeat a search, since we are going to the next page
// hack, make sure we reset the task values
$stateMachine = $this->controller->getStateMachine();
$formName = $stateMachine->getTaskFormName();
$this->controller->resetPage($formName);
return;
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Activity_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$selector->setKey($this->controller->_key);
$prefix = NULL;
if ($this->_context == 'basic' || $this->_context == 'user') {
$prefix = $this->_prefix;
}
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::SESSION,
$prefix
);
$controller->setEmbedded(TRUE);
$query = &$selector->getQuery();
if ($this->_context == 'user') {
$query->setSkipPermission(TRUE);
}
$controller->run();
}
public function fixFormValues() {
if (!$this->_force) {
return;
}
$status = CRM_Utils_Request::retrieve('status', 'String', $this);
if ($status) {
$this->_formValues['activity_status_id'] = $status;
$this->_defaults['activity_status_id'] = $status;
}
$survey = CRM_Utils_Request::retrieve('survey', 'Positive');
if ($survey) {
$this->_formValues['activity_survey_id'] = $this->_defaults['activity_survey_id'] = $survey;
$sid = CRM_Utils_Array::value('activity_survey_id', $this->_formValues);
$activity_type_id = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $sid, 'activity_type_id');
// since checkbox are replaced by multiple select option
$this->_formValues['activity_type_id'] = $activity_type_id;
$this->_defaults['activity_type_id'] = $activity_type_id;
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
if ($cid) {
$cid = CRM_Utils_Type::escape($cid, 'Integer');
if ($cid > 0) {
$this->_formValues['contact_id'] = $cid;
$activity_role = CRM_Utils_Request::retrieve('activity_role', 'Positive', $this);
if ($activity_role) {
$this->_formValues['activity_role'] = $activity_role;
}
else {
$this->_defaults['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'sort_name');
}
// also assign individual mode to the template
$this->_single = TRUE;
}
}
// Added for membership search
$signupType = CRM_Utils_Request::retrieve('signupType', 'Positive');
if ($signupType) {
$this->_formValues['activity_role'] = 1;
$this->_defaults['activity_role'] = 1;
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
$renew = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
$signup = CRM_Utils_Array::key('Membership Signup', $activityTypes);
switch ($signupType) {
case 3: // signups and renewals
$this->_formValues['activity_type_id'][$renew] = 1;
$this->_defaults['activity_type_id'][$renew] = 1;
case 1: // signups only
$this->_formValues['activity_type_id'][$signup] = 1;
$this->_defaults['activity_type_id'][$signup] = 1;
break;
case 2: // renewals only
$this->_formValues['activity_type_id'][$renew] = 1;
$this->_defaults['activity_type_id'][$renew] = 1;
break;
}
}
$dateLow = CRM_Utils_Request::retrieve('dateLow', 'String');
if ($dateLow) {
$dateLow = date('m/d/Y', strtotime($dateLow));
$this->_formValues['activity_date_relative'] = 0;
$this->_defaults['activity_date_relative'] = 0;
$this->_formValues['activity_date_low'] = $dateLow;
$this->_defaults['activity_date_low'] = $dateLow;
}
$dateHigh = CRM_Utils_Request::retrieve('dateHigh', 'String');
if ($dateHigh) {
// Activity date time assumes midnight at the beginning of the date
// This sets it to almost midnight at the end of the date
/* if ($dateHigh <= 99999999) {
$dateHigh = 1000000 * $dateHigh + 235959;
} */
$dateHigh = date('m/d/Y', strtotime($dateHigh));
$this->_formValues['activity_date_relative'] = 0;
$this->_defaults['activity_date_relative'] = 0;
$this->_formValues['activity_date_high'] = $dateHigh;
$this->_defaults['activity_date_high'] = $dateHigh;
}
// Enable search activity by custom value
$requestParams = CRM_Utils_Request::exportValues();
foreach (array_keys($requestParams) as $key) {
if (substr($key, 0, 7) != 'custom_') {
continue;
}
elseif (empty($requestParams[$key])) {
continue;
}
$customValue = CRM_Utils_Request::retrieve($key, 'String', $this);
if ($customValue) {
$this->_formValues[$key] = $customValue;
$this->_defaults[$key] = $customValue;
}
}
if (!empty($this->_defaults)) {
$this->setDefaults($this->_defaults);
}
}
/**
* @return null
*/
public function getFormValues() {
return NULL;
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Find Activities');
}
}

View file

@ -0,0 +1,207 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class for activity task actions.
*/
class CRM_Activity_Form_Task extends CRM_Core_Form {
/**
* The task being performed.
*
* @var int
*/
protected $_task;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_componentClause = NULL;
/**
* The array that holds all the component ids.
*
* @var array
*/
protected $_componentIds;
/**
* The array that holds all the contact ids.
*
* @var array
*/
public $_contactIds;
/**
* The array that holds all the member ids.
*
* @var array
*/
public $_activityHolderIds;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
self::preProcessCommon($this);
}
/**
* Common pre-process function.
*
* @param CRM_Core_Form $form
* @param bool $useTable
*/
public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_activityHolderIds = array();
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
$activityTasks = CRM_Activity_Task::tasks();
$form->assign('taskName', $activityTasks[$form->_task]);
$ids = array();
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
$ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
}
}
}
else {
$queryParams = $form->get('queryParams');
$query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_ACTIVITY
);
$query->_distinctComponentClause = '( civicrm_activity.id )';
$query->_groupByComponentClause = " GROUP BY civicrm_activity.id ";
// CRM-12675
$activityClause = NULL;
$components = CRM_Core_Component::getNames();
$componentClause = array();
foreach ($components as $componentID => $componentName) {
if ($componentName != 'CiviCase' && !CRM_Core_Permission::check("access $componentName")) {
$componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) ";
}
}
if (!empty($componentClause)) {
$activityClause = implode(' AND ', $componentClause);
}
$result = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $activityClause);
while ($result->fetch()) {
if (!empty($result->activity_id)) {
$ids[] = $result->activity_id;
}
}
}
if (!empty($ids)) {
$form->_componentClause = ' civicrm_activity.id IN ( ' . implode(',', $ids) . ' ) ';
$form->assign('totalSelectedActivities', count($ids));
}
$form->_activityHolderIds = $form->_componentIds = $ids;
// Set the context for redirection for any task actions.
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$session = CRM_Core_Session::singleton();
$searchFormName = strtolower($form->get('searchFormName'));
if ($searchFormName == 'search') {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/activity/search', $urlParams));
}
else {
$session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/$searchFormName",
$urlParams
));
}
}
/**
* Given the membership id, compute the contact id
* since it's used for things like send email.
*/
public function setContactIDs() {
$IDs = implode(',', $this->_activityHolderIds);
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$query = "
SELECT contact_id
FROM civicrm_activity_contact
WHERE activity_id IN ( $IDs ) AND
record_type_id = {$sourceID}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$contactIDs[] = $dao->contact_id;
}
$this->_contactIds = $contactIDs;
}
/**
* Simple shell that derived classes can call to add buttons to
* the form with a customized title for the main Submit
*
* @param string $title
* Title of the main button.
* @param string $nextType
* Button type for the form after processing.
* @param string $backType
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
$this->addButtons(array(
array(
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
),
array(
'type' => $backType,
'name' => ts('Cancel'),
),
));
}
}

View file

@ -0,0 +1,154 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to delete a group of
* contacts. This class provides functionality for the actual
* addition of contacts to groups.
*/
class CRM_Activity_Form_Task_AddToTag extends CRM_Activity_Form_Task {
/**
* Name of the tag.
*
* @var string
*/
protected $_name;
/**
* All the tags in the system.
*
* @var array
*/
protected $_tags;
/**
* Build the form object.
*/
public function buildQuickForm() {
// add select for tag
$this->_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
foreach ($this->_tags as $tagID => $tagName) {
$this->_tagElement = &$this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity');
$this->addDefaultButtons(ts('Tag Activities'));
}
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_AddToTag', 'formRule'));
}
/**
* @param CRM_Core_Form $form
* @param $rule
*
* @return array
*/
public static function formRule($form, $rule) {
$errors = array();
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = ts("Please select at least one tag.");
}
return $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// Get the submitted values in an array.
$params = $this->controller->exportValues($this->_name);
$activityTags = $tagList = array();
// check if contact tags exists
if (!empty($params['tag'])) {
$activityTags = $params['tag'];
}
// check if tags are selected from taglists
if (!empty($params['activity_taglist'])) {
foreach ($params['activity_taglist'] as $val) {
if ($val) {
if (is_numeric($val)) {
$tagList[$val] = 1;
}
else {
$tagIDs = explode(',', $val);
if (!empty($tagIDs)) {
foreach ($tagIDs as $tagID) {
if (is_numeric($tagID)) {
$tagList[$tagID] = 1;
}
}
}
}
}
}
}
$tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_activity', FALSE, TRUE);
foreach ($tagSets as $key => $value) {
$this->_tags[$key] = $value['name'];
}
// merge activity and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
$this->_name = array();
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_activityHolderIds, $key,
'civicrm_activity', FALSE);
$status = array(ts('Activity tagged', array('count' => $added, 'plural' => '%count activities tagged')));
if ($notAdded) {
$status[] = ts('1 activity already had this tag', array(
'count' => $notAdded,
'plural' => '%count activities already had this tag',
));
}
$status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
CRM_Core_Session::setStatus($status, ts("Added Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
}
}
}

View file

@ -0,0 +1,258 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality for batch profile update for Activities
*/
class CRM_Activity_Form_Task_Batch extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum profile fields that will be displayed.
*/
protected $_maxFields = 9;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// Initialize the task and row fields.
parent::preProcess();
// Get the contact read only fields to display.
$readOnlyFields = array_merge(array('sort_name' => ts('Added By'), 'target_sort_name' => ts('With Contact')),
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
)
);
// Get the read only field data.
$returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
$contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_activityHolderIds,
'Activity', $returnProperties
);
$readOnlyFields['assignee_display_name'] = ts('Assigned to');
if (!empty($contactDetails)) {
foreach ($contactDetails as $key => $value) {
$assignee = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($key);
foreach ($assignee as $values) {
$assigneeContact[] = CRM_Contact_BAO_Contact::displayName($values);
}
$contactDetails[$key]['assignee_display_name'] = !empty($assigneeContact) ? implode(';', $assigneeContact) : NULL;
}
}
$this->assign('contactDetails', $contactDetails);
$this->assign('readOnlyFields', $readOnlyFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$ufGroupId = $this->get('ufGroupId');
if (!$ufGroupId) {
throw new CRM_Core_Exception('The profile id is missing');
}
$this->_title = ts('Update multiple activities') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
$this->_fields = array();
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
$removehtmlTypes = array('File', 'Autocomplete-Select');
foreach ($this->_fields as $name => $field) {
if (CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
) {
$suppressFields = TRUE;
unset($this->_fields[$name]);
}
// Fix to reduce size as we are using this field in grid.
if (is_array($field['attributes']) && !empty($this->_fields[$name]['attributes']['size']) && $this->_fields[$name]['attributes']['size'] > 19) {
// Shrink class to "form-text-medium".
$this->_fields[$name]['attributes']['size'] = 19;
}
}
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
$this->addButtons(array(
array(
'type' => 'submit',
'name' => ts('Update Activities'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
));
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_activityHolderIds);
// Load all campaigns.
if (array_key_exists('activity_campaign_id', $this->_fields)) {
$this->_componentCampaigns = array();
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Activity_DAO_Activity',
TRUE, 'campaign_id', 'id',
' id IN (' . implode(' , ', array_values($this->_activityHolderIds)) . ' ) '
);
}
$customFields = CRM_Core_BAO_CustomField::getFields('Activity');
// It is possible to have fields that are required in CiviCRM not be required in the
// profile. Overriding that here. Perhaps a better approach would be to
// make them required in the schema & read that up through getFields functionality.
$requiredFields = array('activity_date_time');
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
);
}
if (!empty($entityColumnValue[$typeId]) ||
CRM_Utils_System::isNull($entityColumnValue[$typeId])
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId);
}
}
else {
// Handle non custom fields.
if (in_array($field['name'], $requiredFields)) {
$field['is_required'] = TRUE;
}
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId);
}
}
}
$this->assign('fields', $this->_fields);
// Don't set the status message when form is submitted.
// $buttonName = $this->controller->getButtonName('submit');
if ($suppressFields) {
CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple activities."), ts('Some Fields Excluded'), 'info');
}
$this->addDefaultButtons(ts('Update Activities'));
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
if (empty($this->_fields)) {
return;
}
$defaults = array();
foreach ($this->_activityHolderIds as $activityId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $activityId, 'Activity');
}
return $defaults;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
if (isset($params['field'])) {
foreach ($params['field'] as $key => $value) {
$value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
$key, 'Activity'
);
$value['id'] = $key;
if (!empty($value['activity_status_id'])) {
$value['status_id'] = $value['activity_status_id'];
}
if (!empty($value['activity_details'])) {
$value['details'] = $value['activity_details'];
}
if (!empty($value['activity_location'])) {
$value['location'] = $value['activity_location'];
}
if (!empty($value['activity_subject'])) {
$value['subject'] = $value['activity_subject'];
}
$activityId = civicrm_api3('activity', 'create', $value);
// @todo this would be done by the api call above if the parames were passed through.
if (!empty($value['custom']) &&
is_array($value['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_activity', $activityId['id']);
}
}
CRM_Core_Session::setStatus("", ts("Updates Saved"), "success");
}
else {
CRM_Core_Session::setStatus("", ts("No Updates Saved"), "info");
}
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to delete a group of
* Activities. This class provides functionality for the actual
* deletion.
*/
class CRM_Activity_Form_Task_Delete extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. deleting one
* specific Activity?
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addDefaultButtons(ts('Delete Activities'), 'done');
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$deleted = $failed = 0;
foreach ($this->_activityHolderIds as $activityId['id']) {
$moveToTrash = CRM_Case_BAO_Case::isCaseActivity($activityId['id']);
if (CRM_Activity_BAO_Activity::deleteActivity($activityId, $moveToTrash)) {
$deleted++;
}
else {
$failed++;
}
}
if ($deleted) {
$msg = ts('%count activity deleted.', array('plural' => '%count activities deleted.', 'count' => $deleted));
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
}
}
}

View file

@ -0,0 +1,96 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts.
*/
class CRM_Activity_Form_Task_Email extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
public $_noEmails = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
CRM_Contact_Form_Task_EmailCommon::preProcessFromAddress($this);
parent::preProcess();
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// Enable form element.
$this->assign('emailTask', TRUE);
CRM_Contact_Form_Task_EmailCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_EmailCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,124 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts
*/
class CRM_Activity_Form_Task_FileOnCase extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Variable to store contact Ids.
*/
public $_contacts;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('File on Case'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addEntityRef('unclosed_case_id', ts('Select Case'), array('entity' => 'Case'), TRUE);
$this->addDefaultButtons(ts('Save'));
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$formparams = $this->exportValues();
$caseId = $formparams['unclosed_case_id'];
$filedActivities = 0;
foreach ($this->_activityHolderIds as $key => $id) {
$targetContactValues = $defaults = array();
$params = array('id' => $id);
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
if (CRM_Case_BAO_Case::checkPermission($id, 'File On Case', $defaults['activity_type_id'])) {
if (!CRM_Utils_Array::crmIsEmptyArray($defaults['target_contact'])) {
$targetContactValues = array_combine(array_unique($defaults['target_contact']),
explode(';', trim($defaults['target_contact_value']))
);
$targetContactValues = implode(',', array_keys($targetContactValues));
}
$params = array(
'caseID' => $caseId,
'activityID' => $id,
'newSubject' => empty($defaults['subject']) ? '' : $defaults['subject'],
'targetContactIds' => $targetContactValues,
'mode' => 'file',
);
$error_msg = CRM_Activity_Page_AJAX::_convertToCaseActivity($params);
if (empty($error_msg['error_msg'])) {
$filedActivities++;
}
else {
CRM_Core_Session::setStatus($error_msg['error_msg'], ts("Error"), "error");
}
}
else {
CRM_Core_Session::setStatus(ts('Not permitted to file activity %1 %2.', array(
1 => empty($defaults['subject']) ? '' : $defaults['subject'],
2 => $defaults['activity_date_time'],
)),
ts("Error"), "error");
}
}
CRM_Core_Session::setStatus($filedActivities, ts("Filed Activities"), "success");
CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))), "info");
}
}

View file

@ -0,0 +1,173 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of contacts.
*/
class CRM_Activity_Form_Task_PickOption extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum Activities that should be allowed to update.
*/
protected $_maxActivities = 100;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Variable to store contact Ids.
*/
public $_contacts;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// initialize the task and row fields.
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('Send Email to Contacts'));
$validate = FALSE;
//validations
if (count($this->_activityHolderIds) > $this->_maxActivities) {
CRM_Core_Session::setStatus(ts("The maximum number of Activities you can select to send an email is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
)), ts("Maximum Exceeded"), "error");
$validate = TRUE;
}
// then redirect
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addElement('checkbox', 'with_contact', ts('With Contact'));
$this->addElement('checkbox', 'assigned_to', ts('Assigned to Contact'));
$this->addElement('checkbox', 'created_by', ts('Created by'));
$this->setDefaults(array('with_contact' => 1));
$this->addDefaultButtons(ts('Continue'));
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_PickOption', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
if (!isset($fields['with_contact']) &&
!isset($fields['assigned_to']) &&
!isset($fields['created_by'])
) {
return array('with_contact' => ts('You must select at least one email recipient type.'));
}
return TRUE;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// Clear any formRule errors from Email form in case they came back here via Cancel button
$this->controller->resetPage('Email');
$params = $this->exportValues();
$this->_contacts = array();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
// Get assignee contacts.
if (!empty($params['assigned_to'])) {
foreach ($this->_activityHolderIds as $key => $id) {
$ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $assigneeID));
$this->_contacts = array_merge($this->_contacts, $ids);
}
}
// Get target contacts.
if (!empty($params['with_contact'])) {
foreach ($this->_activityHolderIds as $key => $id) {
$ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID));
$this->_contacts = array_merge($this->_contacts, $ids);
}
}
// Get 'Added by' contacts.
if (!empty($params['created_by'])) {
parent::setContactIDs();
if (!empty($this->_contactIds)) {
$this->_contacts = array_merge($this->_contacts, $this->_contactIds);
}
}
$this->_contacts = array_unique($this->_contacts);
// Bounce to pick option if no contacts to send to.
if (empty($this->_contacts)) {
$urlParams = "_qf_PickOption_display=true&qfKey={$params['qfKey']}";
$urlRedirect = CRM_Utils_System::url('civicrm/activity/search', $urlParams);
CRM_Core_Error::statusBounce(
ts('It appears you have no contacts with email addresses from the selected recipients.'),
$urlRedirect
);
}
$this->set('contacts', $this->_contacts);
}
}

View file

@ -0,0 +1,161 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality for batch profile update for Activity.
*/
class CRM_Activity_Form_Task_PickProfile extends CRM_Activity_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum Activities that should be allowed to update.
*/
protected $_maxActivities = 100;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
// Initialize the task and row fields.
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('Update multiple activities'));
$validate = FALSE;
// Validations.
if (count($this->_activityHolderIds) > $this->_maxActivities) {
CRM_Core_Session::setStatus(ts("The maximum number of activities you can select for Update multiple activities is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
)), ts('Maximum Exceeded'), 'error');
$validate = TRUE;
}
// Then redirect.
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$types = array('Activity');
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
$activityTypeIds = array_flip(CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'));
$nonEditableActivityTypeIds = array(
$activityTypeIds['Email'],
$activityTypeIds['Bulk Email'],
$activityTypeIds['Contribution'],
$activityTypeIds['Inbound Email'],
$activityTypeIds['Pledge Reminder'],
$activityTypeIds['Membership Signup'],
$activityTypeIds['Membership Renewal'],
$activityTypeIds['Event Registration'],
$activityTypeIds['Pledge Acknowledgment'],
);
$notEditable = FALSE;
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
if (in_array($typeId, $nonEditableActivityTypeIds)) {
$notEditable = TRUE;
break;
}
}
if (empty($profiles)) {
CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple activities. Navigate to Administer > Customize Data and Screens > Profiles to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts("No Profile Configured"), "alert");
CRM_Utils_System::redirect($this->_userContext);
}
elseif ($notEditable) {
CRM_Core_Session::setStatus("", ts("Some of the selected activities are not editable."), "alert");
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
array(
'' => ts('- select profile -'),
) + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_PickProfile', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
return TRUE;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
$this->set('ufGroupId', $params['uf_group_id']);
// also reset the batch page so it gets new values from the db
$this->controller->resetPage('Batch');
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to print activity records.
*/
class CRM_Activity_Form_Task_Print extends CRM_Activity_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preprocess();
// set print view, so that print templates are called
$this->controller->setPrint(1);
// get the formatted params
$queryParams = $this->get('queryParams');
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$selector = new CRM_Activity_Selector_Search($queryParams, $this->_action, $this->_componentClause);
$controller = new CRM_Core_Selector_Controller($selector, NULL, $sortID, CRM_Core_Action::VIEW, $this, CRM_Core_Selector_Controller::SCREEN);
$controller->setEmbedded(TRUE);
$controller->run();
}
/**
* Build the form object.
*
* Consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search
*/
public function buildQuickForm() {
// just need to add a javacript to popup the window for printing
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Activities'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
));
}
}

View file

@ -0,0 +1,147 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to remove tags of contact(s).
*/
class CRM_Activity_Form_Task_RemoveFromTag extends CRM_Activity_Form_Task {
/**
* Name of the tag
*
* @var string
*/
protected $_name;
/**
* All the tags in the system
*
* @var array
*/
protected $_tags;
/**
* Build the form object.
*/
public function buildQuickForm() {
// add select for tag
$this->_tags = CRM_Core_BAO_Tag::getTags('civicrm_activity');
foreach ($this->_tags as $tagID => $tagName) {
$this->_tagElement = &$this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
}
$parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', NULL, TRUE, FALSE);
$this->addDefaultButtons(ts('Remove Tags from activities'));
}
public function addRules() {
$this->addFormRule(array('CRM_Activity_Form_Task_RemoveFromTag', 'formRule'));
}
/**
* @param CRM_Core_Form $form
* @param $rule
*
* @return array
*/
public static function formRule($form, $rule) {
$errors = array();
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = "Please select atleast one tag.";
}
return $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
$activityTags = $tagList = array();
// check if contact tags exists
if (!empty($params['tag'])) {
$activityTags = $params['tag'];
}
// check if tags are selected from taglists
if (!empty($params['activity_taglist'])) {
foreach ($params['activity_taglist'] as $val) {
if ($val) {
if (is_numeric($val)) {
$tagList[$val] = 1;
}
else {
list($label, $tagID) = explode(',', $val);
$tagList[$tagID] = 1;
}
}
}
}
$tagSets = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_activity', FALSE, TRUE);
foreach ($tagSets as $key => $value) {
$this->_tags[$key] = $value['name'];
}
// merge contact and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
$this->_name = array();
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $removed, $notRemoved) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($this->_activityHolderIds,
$key, 'civicrm_activity', FALSE);
$status = array(
ts('%count activity un-tagged', array(
'count' => $removed,
'plural' => '%count activities un-tagged',
)),
);
if ($notRemoved) {
$status[] = ts('1 activity already did not have this tag', array(
'count' => $notRemoved,
'plural' => '%count activities already did not have this tag',
));
}
$status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
CRM_Core_Session::setStatus($status, ts("Removed Tag <em>%1</em>", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
}
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to sms a group of contacts.
*/
class CRM_Activity_Form_Task_SMS extends CRM_Activity_Form_Task {
/**
* Are we operating in "single mode", i.e. sending sms to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
CRM_Contact_Form_Task_SMSCommon::preProcessProvider($this);
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// Enable form element.
$this->assign('SMSTask', TRUE);
CRM_Contact_Form_Task_SMSCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_SMSCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,89 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Activity_Form_Task_SearchTaskHookSample extends CRM_Activity_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$rows = array();
// display name and activity details of all selected contacts
$activityIDs = implode(',', $this->_activityHolderIds);
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$query = "
SELECT at.subject as subject,
ov.label as activity_type,
at.activity_date_time as activity_date,
ct.display_name as display_name
FROM civicrm_activity at
LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = at.id AND ac.record_type_id = {$sourceID} )
INNER JOIN civicrm_contact ct ON ( ac.contact_id = ct.id )
LEFT JOIN civicrm_option_group og ON ( og.name = 'activity_type' )
LEFT JOIN civicrm_option_value ov ON (at.activity_type_id = ov.value AND og.id = ov.option_group_id )
WHERE at.id IN ( $activityIDs )";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$rows[] = array(
'subject' => $dao->subject,
'activity_type' => $dao->activity_type,
'activity_date' => $dao->activity_date,
'display_name' => $dao->display_name,
);
}
$this->assign('rows', $rows);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
));
}
}

View file

@ -0,0 +1,60 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}

View file

@ -0,0 +1,123 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_Import_Field {
/**
* @var string
* Name of the field
*/
public $_name;
/**
* Title of the field to be used in display
*/
public $_title;
/**
* Type of field
* @var enum
*/
public $_type;
/**
* Is this field required
* @var boolean
*/
public $_required;
/**
* Data to be carried for use by a derived class
* @var object
*/
public $_payload;
/**
* Regexp to match the CSV header of this column/field
* @var string
*/
public $_headerPattern;
/**
* Regexp to match the pattern of data from various column/fields
* @var string
*/
public $_dataPattern;
/**
* Value of this field
* @var object
*/
public $_value;
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function __construct($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
$this->_name = $name;
$this->_title = $title;
$this->_type = $type;
$this->_headerPattern = $headerPattern;
$this->_dataPattern = $dataPattern;
$this->_value = NULL;
}
public function resetValue() {
$this->_value = NULL;
}
/**
* The value is in string format. convert the value to the type of this field
* and set the field value with the appropriate type
* @param $value
*/
public function setValue($value) {
$this->_value = $value;
}
/**
* @return bool
*/
public function validate() {
if (CRM_Utils_System::isNull($this->_value)) {
return TRUE;
}
return TRUE;
}
}

View file

@ -0,0 +1,79 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload.
*/
class CRM_Activity_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/import/activity';
const IMPORT_ENTITY = 'Activity';
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
// FIXME: This 'onDuplicate' form element is never used -- copy/paste error?
$duplicateOptions = array();
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Update'), CRM_Import_Parser::DUPLICATE_UPDATE
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Fill'), CRM_Import_Parser::DUPLICATE_FILL
);
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('On duplicate entries')
);
}
/**
* Process the uploaded file.
*/
public function postProcess() {
$this->storeFormValues(array(
'onDuplicate',
'dateFormats',
'savedMapping',
));
$this->submitFileForMapping('CRM_Activity_Import_Parser_Activity');
}
}

View file

@ -0,0 +1,471 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload.
*/
class CRM_Activity_Import_Form_MapField extends CRM_Import_Form_MapField {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
unset($this->_mapperFields['id']);
asort($this->_mapperFields);
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
$this->assign('dataValues', $this->_dataValues);
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
// If we had a column header to skip, stash it for later.
$this->_columnHeaders = $this->_dataValues[0];
}
else {
$this->assign('rowDisplayCount', 2);
}
$highlightedFields = array();
$requiredFields = array(
'activity_date_time',
'activity_type_id',
'activity_label',
'target_contact_id',
'activity_subject',
);
foreach ($requiredFields as $val) {
$highlightedFields[] = $val;
}
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// To save the current mappings.
if (!$this->get('savedMapping')) {
$saveDetailsName = ts('Save this field mapping');
$this->applyFilter('saveMappingName', 'trim');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
else {
$savedMapping = $this->get('savedMapping');
// Mapping is to be loaded from database.
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
// Get loaded Mapping Fields.
$mappingName = CRM_Utils_Array::value('1', $mappingName);
$mappingContactType = CRM_Utils_Array::value('1', $mappingContactType);
$mappingLocation = CRM_Utils_Array::value('1', $mappingLocation);
$mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType);
$mappingRelation = CRM_Utils_Array::value('1', $mappingRelation);
$this->assign('loadedMapping', $savedMapping);
$this->set('loadedMapping', $savedMapping);
$params = array('id' => $savedMapping);
$temp = array();
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('savedName', $mappingDetails->name);
$this->add('hidden', 'mappingId', $savedMapping);
$this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
$saveDetailsName = ts('Save as a new field mapping');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
$this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
$this->addFormRule(array('CRM_Activity_Import_Form_MapField', 'formRule'));
//-------- end of saved mapping stuff ---------
$defaults = array();
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
$dataPatterns = $this->get('dataPatterns');
$hasLocationTypes = $this->get('fieldTypes');
// Initialize all field usages to false.
foreach ($mapperKeys as $key) {
$this->_fieldUsed[$key] = FALSE;
}
$this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$sel1 = $this->_mapperFields;
$sel2[''] = NULL;
$js = "<script type='text/javascript'>\n";
$formName = 'document.forms.' . $this->_name;
// Used to warn for mismatch column count or mismatch mapping.
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
$sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
if ($mappingName[$i] != ts('- do not import -')) {
$mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
if (!isset($locationId) || !$locationId) {
$js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
}
if (!isset($phoneType) || !$phoneType) {
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
}
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
$defaults["mapper[$i]"] = array(
$mappingHeader[0],
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
);
$jsSet = TRUE;
}
else {
$defaults["mapper[$i]"] = array();
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
$js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
}
}
}
else {
// this load section to help mapping if we ran out of saved columns when doing Load Mapping
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
);
}
else {
$defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
}
}
// End of load mapping.
}
else {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
// Infer the default from the skipped headers if we have them
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
0,
);
}
else {
// Otherwise guess the default from the form of the data
$defaults["mapper[$i]"] = array(
$this->defaultFromData($dataPatterns, $i),
0,
);
}
}
$sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
}
$js .= "</script>\n";
$this->assign('initHideBoxes', $js);
// Set warning if mismatch in more than.
if (isset($mappingName)) {
if (($this->_columnCount != count($mappingName))) {
$warning++;
}
}
if ($warning != 0 && $this->get('savedMapping')) {
$session = CRM_Core_Session::singleton();
$session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
}
else {
$session = CRM_Core_Session::singleton();
$session->setStatus(NULL);
}
$this->setDefaults($defaults);
$this->addButtons(array(
array(
'type' => 'back',
'name' => ts('Previous'),
),
array(
'type' => 'next',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
$errors = array();
// define so we avoid notices below
$errors['_qf_default'] = '';
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
// FIXME: should use the schema titles, not redeclare them
$requiredFields = array(
'target_contact_id' => ts('Contact ID'),
'activity_date_time' => ts('Activity Date'),
'activity_subject' => ts('Activity Subject'),
'activity_type_id' => ts('Activity Type ID'),
);
$params = array(
'used' => 'Unsupervised',
'contact_type' => 'Individual',
);
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
if (array_key_exists($val, $ruleFields)) {
$weightSum += $ruleFields[$val];
}
}
foreach ($ruleFields as $field => $weight) {
$fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
}
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
if ($field == 'target_contact_id') {
if ($weightSum >= $threshold || in_array('external_identifier', $importKeys)) {
continue;
}
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.')
. $fieldMessage . ' '
. ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(1 => $threshold))
. '<br />';
}
}
elseif ($field == 'activity_type_id') {
if (in_array('activity_label', $importKeys)) {
continue;
}
else {
$errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
array(
1 => $title,
2 => 'Activity Type Label',
)) . '<br />';
}
}
else {
$errors['_qf_default'] .= ts('Missing required field: %1', array(1 => $title)) . '<br />';
}
}
}
}
if (!empty($fields['saveMapping'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
if (empty($nameField)) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
$mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Activity', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
}
}
}
if (empty($errors['_qf_default'])) {
unset($errors['_qf_default']);
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
return $errors;
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file.
*
* Preview the file and extract some summary statistics
*/
public function postProcess() {
$params = $this->controller->exportValues('MapField');
// Reload the mapfield if load mapping is pressed.
if (!empty($params['savedMapping'])) {
$this->set('savedMapping', $params['savedMapping']);
$this->controller->resetPage($this->_name);
return;
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$mapperKeysMain = array();
$mapperLocType = array();
$mapperPhoneType = array();
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
if ((CRM_Utils_Array::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
$mapperLocType[$i] = $mapperKeys[$i][1];
}
else {
$mapperLocType[$i] = NULL;
}
if ((CRM_Utils_Array::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
$mapperPhoneType[$i] = $mapperKeys[$i][2];
}
else {
$mapperPhoneType[$i] = NULL;
}
}
$this->set('mapper', $mapper);
// store mapping Id to display it in the preview page
if (!empty($params['mappingId'])) {
$this->set('loadMappingId', $params['mappingId']);
}
// Updating Mapping Records.
if (!empty($params['updateMapping'])) {
$mappingFields = new CRM_Core_DAO_MappingField();
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
$mappingFieldsId = array();
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
}
}
for ($i = 0; $i < $this->_columnCount; $i++) {
$updateMappingFields = new CRM_Core_DAO_MappingField();
$updateMappingFields->id = $mappingFieldsId[$i];
$updateMappingFields->mapping_id = $params['mappingId'];
$updateMappingFields->column_number = $i;
$updateMappingFields->name = $mapper[$i];
$updateMappingFields->save();
}
}
// Saving Mapping Details and Records.
if (!empty($params['saveMapping'])) {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
'Import Activity',
'name'
),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $saveMapping->id;
$saveMappingFields->column_number = $i;
$saveMappingFields->name = $mapper[$i];
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
$parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
CRM_Import_Parser::MODE_PREVIEW
);
// add all the necessary variables to the form
$parser->set($this);
}
}

View file

@ -0,0 +1,188 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class previews the uploaded file and returns summary statistics.
*/
class CRM_Activity_Import_Form_Preview extends CRM_Import_Form_Preview {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
// Get the data from the session.
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$mismatchCount = $this->get('unMatchCount');
// Get the mapping name displayed if the mappingId is set.
$mappingId = $this->get('loadMappingId');
if ($mappingId) {
$mapDAO = new CRM_Core_DAO_Mapping();
$mapDAO->id = $mappingId;
$mapDAO->find(TRUE);
$this->assign('loadedMapping', $mappingId);
$this->assign('savedName', $mapDAO->name);
}
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($invalidRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'dataValues',
'columnCount',
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
/**
* Process the mapped fields and map it into the uploaded file.
*
* Preview the file and extract some summary statistics
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
$mapperLocType = array();
$mapperPhoneType = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
if (!empty($mapper[$key][1]) && is_numeric($mapper[$key][1])) {
$mapperLocType[$key] = $mapper[$key][1];
}
else {
$mapperLocType[$key] = NULL;
}
if (!empty($mapper[$key][2]) && (!is_numeric($mapper[$key][2]))) {
$mapperPhoneType[$key] = $mapper[$key][2];
}
else {
$mapperPhoneType[$key] = NULL;
}
}
$parser = new CRM_Activity_Import_Parser_Activity($mapperKeys, $mapperLocType, $mapperPhoneType);
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
$header = array();
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
$mapperFields[] = implode(' - ', $header);
}
$parser->run($fileName, $seperator,
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$onDuplicate
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
$errorMessage = array();
if (is_array($errors)) {
foreach ($errors as $key => $value) {
$errorMessage[] = $value['message'];
}
$errorFile = $fileName['name'] . '.error.log';
if ($fd = fopen($errorFile, 'w')) {
fwrite($fd, implode('\n', $errorMessage));
}
fclose($fd);
$this->set('errorFile', $errorFile);
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,110 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class summarizes the import results.
*/
class CRM_Activity_Import_Form_Summary extends CRM_Import_Form_Summary {
/**
* Set variables up before form is built.
*/
public function preProcess() {
// set the error message path to display
$this->assign('errorFile', $this->get('errorFile'));
$totalRowCount = $this->get('totalRowCount');
$relatedCount = $this->get('relatedCount');
$totalRowCount += $relatedCount;
$this->set('totalRowCount', $totalRowCount);
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$duplicateRowCount = $this->get('duplicateRowCount');
$onDuplicate = $this->get('onDuplicate');
$mismatchCount = $this->get('unMatchCount');
if ($duplicateRowCount > 0) {
$urlParams = 'type=' . CRM_Import_Parser::DUPLICATE . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
elseif ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Activity_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
else {
$duplicateRowCount = 0;
$this->set('duplicateRowCount', $duplicateRowCount);
}
$this->assign('dupeError', FALSE);
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$dupeActionString = ts('These records have been updated with the imported data.');
}
elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
$dupeActionString = ts('These records have been filled in with the imported data.');
}
else {
// Skip by default.
$dupeActionString = ts('These records have not been imported.');
$this->assign('dupeError', TRUE);
// Only subtract dupes from successful import if we're skipping.
$this->set('validRowCount', $totalRowCount - $invalidRowCount -
$conflictRowCount - $duplicateRowCount - $mismatchCount
);
}
$this->assign('dupeActionString', $dupeActionString);
$properties = array(
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadConflictRecordsUrl',
'downloadErrorRecordsUrl',
'duplicateRowCount',
'downloadDuplicateRecordsUrl',
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
}

View file

@ -0,0 +1,398 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
abstract class CRM_Activity_Import_Parser extends CRM_Import_Parser {
protected $_fileName;
/**
* Imported file size.
*/
protected $_fileSize;
/**
* Separator being used.
*/
protected $_seperator;
/**
* Total number of lines in file.
*/
protected $_lineCount;
/**
* Whether the file has a column header or not.
*
* @var boolean
*/
protected $_haveColumnHeader;
/**
* @param string $fileName
* @param string $seperator
* @param $mapper
* @param bool $skipColumnHeader
* @param int $mode
* @param int $onDuplicate
*
* @return mixed
* @throws Exception
*/
public function run(
$fileName,
$seperator = ',',
&$mapper,
$skipColumnHeader = FALSE,
$mode = self::MODE_PREVIEW,
$onDuplicate = self::DUPLICATE_SKIP
) {
if (!is_array($fileName)) {
CRM_Core_Error::fatal();
}
$fileName = $fileName['name'];
$this->init();
$this->_haveColumnHeader = $skipColumnHeader;
$this->_seperator = $seperator;
$fd = fopen($fileName, "r");
if (!$fd) {
return FALSE;
}
$this->_lineCount = $this->_warningCount = 0;
$this->_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
$this->_rows = array();
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
while (!feof($fd)) {
$this->_lineCount++;
$values = fgetcsv($fd, 8192, $seperator);
if (!$values) {
continue;
}
self::encloseScrub($values);
// skip column header if we're not in mapfield mode
if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
$skipColumnHeader = FALSE;
continue;
}
// Trim whitespace around the values.
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
}
if (CRM_Utils_System::isNull($values)) {
continue;
}
$this->_totalCount++;
if ($mode == self::MODE_MAPFIELD) {
$returnCode = $this->mapField($values);
}
elseif ($mode == self::MODE_PREVIEW) {
$returnCode = $this->preview($values);
}
elseif ($mode == self::MODE_SUMMARY) {
$returnCode = $this->summary($values);
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
}
else {
$returnCode = self::ERROR;
}
// note that a line could be valid but still produce a warning
if ($returnCode & self::VALID) {
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode & self::WARNING) {
$this->_warningCount++;
if ($this->_warningCount < $this->_maxWarningCount) {
$this->_warningCount[] = $line;
}
}
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
if ($this->_invalidRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_errors[] = $values;
}
}
if ($returnCode & self::CONFLICT) {
$this->_conflictCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_conflicts[] = $values;
}
if ($returnCode & self::DUPLICATE) {
if ($returnCode & self::MULTIPLE_DUPE) {
// TODO: multi-dupes should be counted apart from singles
// on non-skip action.
}
$this->_duplicateCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_duplicates[] = $values;
if ($onDuplicate != self::DUPLICATE_SKIP) {
$this->_validCount++;
}
}
// we give the derived class a way of aborting the process
// note that the return code could be multiple code or'ed together
if ($returnCode & self::STOP) {
break;
}
// if we are done processing the maxNumber of lines, break
if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
break;
}
}
fclose($fd);
if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
$customHeaders = $mapper;
$customfields = CRM_Core_BAO_CustomField::getFields('Activity');
foreach ($customHeaders as $key => $value) {
if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
$customHeaders[$key] = $customfields[$id][0];
}
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('View Activity History URL'),
),
$customHeaders
);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
}
}
return $this->fini();
}
/**
* Given a list of the importable field keys that the user has selected set the active fields array to this list.
*
* @param array $fieldKeys
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Activity_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* Format the field values for input to the api.
*
* @return array
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
$params = array();
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
&& !isset($this->_activeFields[$i]->_related)
) {
$params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
}
}
return $params;
}
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
if (empty($name)) {
$this->_fields['doNotImport'] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$tempField = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
if (!array_key_exists($name, $tempField)) {
$this->_fields[$name] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, CRM_Utils_Array::value('hasLocationType', $tempField[$name]));
}
}
}
/**
* Store parser values.
*
* @param CRM_Core_Session $store
*
* @param int $mode
*/
public function set($store, $mode = self::MODE_SUMMARY) {
$store->set('fileSize', $this->_fileSize);
$store->set('lineCount', $this->_lineCount);
$store->set('seperator', $this->_seperator);
$store->set('fields', $this->getSelectValues());
$store->set('fieldTypes', $this->getSelectTypes());
$store->set('headerPatterns', $this->getHeaderPatterns());
$store->set('dataPatterns', $this->getDataPatterns());
$store->set('columnCount', $this->_activeFieldCount);
$store->set('totalRowCount', $this->_totalCount);
$store->set('validRowCount', $this->_validCount);
$store->set('invalidRowCount', $this->_invalidRowCount);
$store->set('conflictRowCount', $this->_conflictCount);
if ($this->_invalidRowCount) {
$store->set('errorsFileName', $this->_errorFileName);
}
if ($this->_conflictCount) {
$store->set('conflictsFileName', $this->_conflictFileName);
}
if (isset($this->_rows) && !empty($this->_rows)) {
$store->set('dataValues', $this->_rows);
}
if ($mode == self::MODE_IMPORT) {
$store->set('duplicateRowCount', $this->_duplicateCount);
if ($this->_duplicateCount) {
$store->set('duplicatesFileName', $this->_duplicateFileName);
}
}
}
/**
* Export data to a CSV file.
*
* @param string $fileName
* @param array $header
* @param array $data
*/
public static function exportCSV($fileName, $header, $data) {
$output = array();
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
$header[$key] = "\"$value\"";
}
$config = CRM_Core_Config::singleton();
$output[] = implode($config->fieldSeparator, $header);
foreach ($data as $datum) {
foreach ($datum as $key => $value) {
$datum[$key] = "\"$value\"";
}
$output[] = implode($config->fieldSeparator, $datum);
}
fwrite($fd, implode("\n", $output));
fclose($fd);
}
}

View file

@ -0,0 +1,400 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class to parse activity csv files.
*/
class CRM_Activity_Import_Parser_Activity extends CRM_Activity_Import_Parser {
protected $_mapperKeys;
private $_contactIdIndex;
private $_activityTypeIndex;
private $_activityLabelIndex;
private $_activityDateIndex;
/**
* Array of successfully imported activity id's
*
* @array
*/
protected $_newActivity;
/**
* Class constructor.
*
* @param array $mapperKeys
* @param int $mapperLocType
* @param int $mapperPhoneType
*/
public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
}
/**
* Function of undocumented functionality required by the interface.
*/
protected function fini() {}
/**
* The initializer code, called before the processing.
*/
public function init() {
$activityContact = CRM_Activity_BAO_ActivityContact::import();
$activityTarget['target_contact_id'] = $activityContact['contact_id'];
$fields = array_merge(CRM_Activity_BAO_Activity::importableFields(),
$activityTarget
);
$fields = array_merge($fields, array(
'source_contact_id' => array(
'title' => ts('Source Contact'),
'headerPattern' => '/Source.Contact?/i',
),
'activity_label' => array(
'title' => ts('Activity Type Label'),
'headerPattern' => '/(activity.)?type label?/i',
),
));
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
$this->_newActivity = array();
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
$this->_contactIdIndex = -1;
$this->_activityTypeIndex = -1;
$this->_activityLabelIndex = -1;
$this->_activityDateIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
case 'target_contact_id':
case 'external_identifier':
$this->_contactIdIndex = $index;
break;
case 'activity_label':
$this->_activityLabelIndex = $index;
break;
case 'activity_type_id':
$this->_activityTypeIndex = $index;
break;
case 'activity_date_time':
$this->_activityDateIndex = $index;
break;
}
$index++;
}
}
/**
* Handle the values in mapField mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
*/
public function mapField(&$values) {
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in preview mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function preview(&$values) {
return $this->summary($values);
}
/**
* Handle the values in summary mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function summary(&$values) {
$erroneousField = NULL;
$this->setActiveFieldValues($values, $erroneousField);
$index = -1;
if ($this->_activityTypeIndex > -1 && $this->_activityLabelIndex > -1) {
array_unshift($values, ts('Please select either Activity Type ID OR Activity Type Label.'));
return CRM_Import_Parser::ERROR;
}
elseif ($this->_activityLabelIndex > -1) {
$index = $this->_activityLabelIndex;
}
elseif ($this->_activityTypeIndex > -1) {
$index = $this->_activityTypeIndex;
}
if ($index < 0 or $this->_activityDateIndex < 0) {
$errorRequired = TRUE;
}
else {
$errorRequired = !CRM_Utils_Array::value($index, $values) || !CRM_Utils_Array::value($this->_activityDateIndex, $values);
}
if ($errorRequired) {
array_unshift($values, ts('Missing required fields'));
return CRM_Import_Parser::ERROR;
}
$params = &$this->getActiveFieldParams();
$errorMessage = NULL;
// For date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
if (!isset($params['source_contact_id'])) {
$params['source_contact_id'] = $session->get('userID');
}
foreach ($params as $key => $val) {
if ($key == 'activity_date_time') {
if ($val) {
$dateValue = CRM_Utils_Date::formatDate($val, $dateType);
if ($dateValue) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity date', $errorMessage);
}
}
}
elseif ($key == 'activity_engagement_level' && $val &&
!CRM_Utils_Rule::positiveInteger($val)
) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity Engagement Index', $errorMessage);
}
}
// Date-Format part ends.
// Checking error in custom data.
$params['contact_type'] = isset($this->_contactType) ? $this->_contactType : 'Activity';
CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
if ($errorMessage) {
$tempMsg = "Invalid value for field(s) : $errorMessage";
array_unshift($values, $tempMsg);
$errorMessage = NULL;
return CRM_Import_Parser::ERROR;
}
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in import mode.
*
* @param int $onDuplicate
* The code for what action to take on duplicates.
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function import($onDuplicate, &$values) {
// First make sure this is a valid line
$response = $this->summary($values);
if ($response != CRM_Import_Parser::VALID) {
return $response;
}
$params = &$this->getActiveFieldParams();
$activityLabel = array_search('activity_label', $this->_mapperKeys);
if ($activityLabel) {
$params = array_merge($params, array('activity_label' => $values[$activityLabel]));
}
// For date-Formats.
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
if (!isset($params['source_contact_id'])) {
$params['source_contact_id'] = $session->get('userID');
}
$customFields = CRM_Core_BAO_CustomField::getFields('Activity');
foreach ($params as $key => $val) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
if ($key == 'activity_date_time' && $val) {
$params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
}
elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Date') {
CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
}
elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
$params[$key] = CRM_Utils_String::strtoboolstr($val);
}
}
elseif ($key == 'activity_date_time') {
$params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
}
elseif ($key == 'activity_subject') {
$params['subject'] = $val;
}
}
// Date-Format part ends.
require_once 'CRM/Utils/DeprecatedUtils.php';
$formatError = _civicrm_api3_deprecated_activity_formatted_param($params, $params, TRUE);
if ($formatError) {
array_unshift($values, $formatError['error_message']);
return CRM_Import_Parser::ERROR;
}
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
NULL,
'Activity'
);
if ($this->_contactIdIndex < 0) {
// Retrieve contact id using contact dedupe rule.
// Since we are supporting only individual's activity import.
$params['contact_type'] = 'Individual';
$params['version'] = 3;
$error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
if (count($matchedIDs) > 1) {
array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
return CRM_Import_Parser::ERROR;
}
else {
$cid = $matchedIDs[0];
$params['target_contact_id'] = $cid;
$params['version'] = 3;
$newActivity = civicrm_api('activity', 'create', $params);
if (!empty($newActivity['is_error'])) {
array_unshift($values, $newActivity['error_message']);
return CRM_Import_Parser::ERROR;
}
$this->_newActivity[] = $newActivity['id'];
return CRM_Import_Parser::VALID;
}
}
else {
// Using new Dedupe rule.
$ruleParams = array(
'contact_type' => 'Individual',
'used' => 'Unsupervised',
);
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = NULL;
foreach ($fieldsArray as $value) {
if (array_key_exists(trim($value), $params)) {
$paramValue = $params[trim($value)];
if (is_array($paramValue)) {
$disp .= $params[trim($value)][0][trim($value)] . " ";
}
else {
$disp .= $params[trim($value)] . " ";
}
}
}
if (!empty($params['external_identifier'])) {
if ($disp) {
$disp .= "AND {$params['external_identifier']}";
}
else {
$disp = $params['external_identifier'];
}
}
array_unshift($values, 'No matching Contact found for (' . $disp . ')');
return CRM_Import_Parser::ERROR;
}
}
else {
if (!empty($params['external_identifier'])) {
$targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$params['external_identifier'], 'id', 'external_identifier'
);
if (!empty($params['target_contact_id']) &&
$params['target_contact_id'] != $targetContactId
) {
array_unshift($values, 'Mismatch of External ID:' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
return CRM_Import_Parser::ERROR;
}
elseif ($targetContactId) {
$params['target_contact_id'] = $targetContactId;
}
else {
array_unshift($values, 'No Matching Contact for External ID:' . $params['external_identifier']);
return CRM_Import_Parser::ERROR;
}
}
$params['version'] = 3;
$newActivity = civicrm_api('activity', 'create', $params);
if (!empty($newActivity['is_error'])) {
array_unshift($values, $newActivity['error_message']);
return CRM_Import_Parser::ERROR;
}
$this->_newActivity[] = $newActivity['id'];
return CRM_Import_Parser::VALID;
}
}
}

View file

@ -0,0 +1,469 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
*/
/**
* This class contains all the function that are called using AJAX (jQuery)
*/
class CRM_Activity_Page_AJAX {
public static function getCaseActivity() {
// Should those params be passed through the validateParams method?
$caseID = CRM_Utils_Type::validate($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::validate($_GET['cid'], 'Integer');
$userID = CRM_Utils_Type::validate($_GET['userID'], 'Integer');
$context = CRM_Utils_Type::validate(CRM_Utils_Array::value('context', $_GET), 'String');
$optionalParameters = array(
'source_contact_id' => 'Integer',
'status_id' => 'Integer',
'activity_deleted' => 'Boolean',
'activity_type_id' => 'Integer',
'activity_date_low' => 'Date',
'activity_date_high' => 'Date',
);
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters);
// get the activities related to given case
$activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID);
CRM_Utils_JSON::output($activities);
}
public static function getCaseGlobalRelationships() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
// get the activities related to given case
$globalGroupInfo = array();
// get the total row count
CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, NULL, FALSE, TRUE, NULL, NULL);
// limit the rows
$relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, $params['sortBy'], $showLinks = TRUE, FALSE, $params['offset'], $params['rp']);
$relationships = array();
// after sort we can update username fields to be a url
foreach ($relGlobal as $key => $value) {
$relationship = array();
$relationship['sort_name'] = $value['sort_name'];
$relationship['phone'] = $value['phone'];
$relationship['email'] = $value['email'];
array_push($relationships, $relationship);
}
$globalRelationshipsDT = array();
$globalRelationshipsDT['data'] = $relationships;
$globalRelationshipsDT['recordsTotal'] = count($relationships);
$globalRelationshipsDT['recordsFiltered'] = count($relationships);
CRM_Utils_JSON::output($globalRelationshipsDT);
}
public static function getCaseClientRelationships() {
$caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
// Retrieve ALL client relationships
$relClient = CRM_Contact_BAO_Relationship::getRelationship($contactID,
CRM_Contact_BAO_Relationship::CURRENT,
0, 0, 0, NULL, NULL, FALSE
);
$caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
// Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
// so they don't show up twice.
$clientRelationships = array();
foreach ($relClient as $r) {
if (!array_key_exists($r['id'], $caseRelationships)) {
$clientRelationships[] = $r;
}
}
// sort clientRelationships array using jquery call params
foreach ($clientRelationships as $key => $row) {
$sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
}
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $clientRelationships);
$relationships = array();
// after sort we can update username fields to be a url
foreach ($clientRelationships as $key => $value) {
$relationship = array();
$relationship['relation'] = $value['relation'];
$relationship['name'] = '<a href=' . CRM_Utils_System::url('civicrm/contact/view',
'action=view&reset=1&cid=' . $clientRelationships[$key]['cid']) . '>' . $clientRelationships[$key]['name'] . '</a>';
$relationship['phone'] = $value['phone'];
$relationship['email'] = $value['email'];
array_push($relationships, $relationship);
}
$clientRelationshipsDT = array();
$clientRelationshipsDT['data'] = $relationships;
$clientRelationshipsDT['recordsTotal'] = count($relationships);
$clientRelationshipsDT['recordsFiltered'] = count($relationships);
CRM_Utils_JSON::output($clientRelationshipsDT);
}
public static function getCaseRoles() {
$caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
$caseTypeName = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
$xmlProcessor = new CRM_Case_XMLProcessor_Process();
$caseRoles = $xmlProcessor->get($caseTypeName, 'CaseRoles');
$hasAccessToAllCases = CRM_Core_Permission::check('access all cases and activities');
$managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseTypeName);
foreach ($caseRelationships as $key => $value) {
// This role has been filled
unset($caseRoles[$value['relation_type']]);
// mark original case relationships record to use on setting edit links below
$caseRelationships[$key]['source'] = 'caseRel';
}
$caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
// move/transform caseRoles array data to caseRelationships
// for sorting and display
// CRM-14466 added cid to the non-client array to avoid php notice
foreach ($caseRoles as $id => $value) {
if ($id != "client") {
$rel = array();
$rel['relation'] = $value;
$rel['relation_type'] = $id;
$rel['name'] = '(not assigned)';
$rel['phone'] = '';
$rel['email'] = '';
$rel['source'] = 'caseRoles';
$caseRelationships[] = $rel;
}
else {
foreach ($value as $clientRole) {
$relClient = array();
$relClient['relation'] = 'Client';
$relClient['name'] = $clientRole['sort_name'];
$relClient['phone'] = $clientRole['phone'];
$relClient['email'] = $clientRole['email'];
$relClient['cid'] = $clientRole['contact_id'];
$relClient['source'] = 'contact';
$caseRelationships[] = $relClient;
}
}
}
// sort clientRelationships array using jquery call params
foreach ($caseRelationships as $key => $row) {
$sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
}
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $caseRelationships);
$relationships = array();
// set user name, email and edit columns links
foreach ($caseRelationships as $key => &$row) {
$typeLabel = $row['relation'];
// Add "<br />(Case Manager)" to label
if (!empty($row['relation_type']) && $row['relation_type'] == $managerRoleId) {
$row['relation'] .= '<br />' . '(' . ts('Case Manager') . ')';
}
// view user links
if (!empty($row['cid'])) {
$row['name'] = '<a class="view-contact" title="' . ts('View Contact') . '" href=' . CRM_Utils_System::url('civicrm/contact/view',
'action=view&reset=1&cid=' . $row['cid']) . '>' . $row['name'] . '</a>';
}
// email column links/icon
if ($row['email']) {
$row['email'] = '<a class="crm-hover-button crm-popup" href="' . CRM_Utils_System::url('civicrm/activity/email/add', 'reset=1&action=add&atype=3&cid=' . $row['cid']) . '&caseid=' . $caseID . '" title="' . ts('Send an Email') . '"><i class="crm-i fa-envelope"></i></a>';
}
// edit links
$row['actions'] = '';
if ($hasAccessToAllCases) {
$contactType = empty($row['relation_type']) ? '' : (string) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $row['relation_type'], 'contact_type_b');
$contactType = $contactType == 'Contact' ? '' : $contactType;
switch ($row['source']) {
case 'caseRel':
$row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Reassign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-rel_id="' . $row['rel_id'] . '"data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
'<i class="crm-i fa-pencil"></i>' .
'</a>' .
'<a href="#deleteCaseRoleDialog" title="' . ts('Remove %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-key="' . CRM_Core_Key::get('civicrm/ajax/delcaserole') . '">' .
'<span class="icon delete-icon"></span>' .
'</a>';
break;
case 'caseRoles':
$row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Assign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_a_b" data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
'<i class="crm-i fa-pencil"></i>' .
'</a>';
break;
}
}
unset($row['cid']);
unset($row['relation_type']);
unset($row['rel_id']);
unset($row['client_id']);
unset($row['source']);
array_push($relationships, $row);
}
$params['total'] = count($relationships);
$caseRelationshipsDT = array();
$caseRelationshipsDT['data'] = $relationships;
$caseRelationshipsDT['recordsTotal'] = $params['total'];
$caseRelationshipsDT['recordsFiltered'] = $params['total'];
CRM_Utils_JSON::output($caseRelationshipsDT);
}
public static function convertToCaseActivity() {
$params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
$vals = array();
foreach ($params as $param) {
$vals[$param] = CRM_Utils_Array::value($param, $_POST);
}
CRM_Utils_JSON::output(self::_convertToCaseActivity($vals));
}
/**
* @param array $params
*
* @return array
*/
public static function _convertToCaseActivity($params) {
if (!$params['activityID'] || !$params['caseID']) {
return (array('error_msg' => 'required params missing.'));
}
$otherActivity = new CRM_Activity_DAO_Activity();
$otherActivity->id = $params['activityID'];
if (!$otherActivity->find(TRUE)) {
return (array('error_msg' => 'activity record is missing.'));
}
$actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
// Create new activity record.
$mainActivity = new CRM_Activity_DAO_Activity();
$mainActVals = array();
CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
// Get new activity subject.
if (!empty($params['newSubject'])) {
$mainActVals['subject'] = $params['newSubject'];
}
$mainActivity->copyValues($mainActVals);
$mainActivity->id = NULL;
$mainActivity->activity_date_time = $actDateTime;
// Make sure this is current revision.
$mainActivity->is_current_revision = TRUE;
// Drop all relations.
$mainActivity->parent_id = $mainActivity->original_id = NULL;
$mainActivity->save();
$mainActivityId = $mainActivity->id;
CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
$mainActivity->free();
// Mark previous activity as deleted. If it was a non-case activity
// then just change the subject.
if (in_array($params['mode'], array(
'move',
'file',
))) {
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->case_id = $params['caseID'];
$caseActivity->activity_id = $otherActivity->id;
if ($params['mode'] == 'move' || $caseActivity->find(TRUE)) {
$otherActivity->is_deleted = 1;
}
else {
$otherActivity->subject = ts('(Filed on case %1)', array(
1 => $params['caseID'],
)) . ' ' . $otherActivity->subject;
}
$otherActivity->activity_date_time = $actDateTime;
$otherActivity->save();
$caseActivity->free();
}
$otherActivity->free();
$targetContacts = array();
if (!empty($params['targetContactIds'])) {
$targetContacts = array_unique(explode(',', $params['targetContactIds']));
}
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
$src_params = array(
'activity_id' => $mainActivityId,
'contact_id' => $sourceContactID,
'record_type_id' => $sourceID,
);
CRM_Activity_BAO_ActivityContact::create($src_params);
foreach ($targetContacts as $key => $value) {
$targ_params = array(
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $targetID,
);
CRM_Activity_BAO_ActivityContact::create($targ_params);
}
//CRM-21114 retrieve assignee contacts from original case; allow overriding from params
$assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($params['activityID'], $assigneeID);
if (!empty($params['assigneeContactIds'])) {
$assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
}
foreach ($assigneeContacts as $key => $value) {
$assigneeParams = array(
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $assigneeID,
);
CRM_Activity_BAO_ActivityContact::create($assigneeParams);
}
// Attach newly created activity to case.
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->case_id = $params['caseID'];
$caseActivity->activity_id = $mainActivityId;
$caseActivity->save();
$error_msg = $caseActivity->_lastError;
$caseActivity->free();
$params['mainActivityId'] = $mainActivityId;
CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
return (array('error_msg' => $error_msg, 'newId' => $mainActivity->id));
}
/**
* Get activities for the contact.
*
* @return array
*/
public static function getContactActivity() {
$requiredParameters = array(
'cid' => 'Integer',
);
$optionalParameters = array(
'context' => 'String',
'activity_type_id' => 'Integer',
'activity_type_exclude_id' => 'Integer',
'activity_status_id' => 'String',
'activity_date_relative' => 'String',
'activity_date_low' => 'String',
'activity_date_high' => 'String',
);
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
// To be consistent, the cid parameter should be renamed to contact_id in
// the template file, see templates/CRM/Activity/Selector/Selector.tpl
$params['contact_id'] = $params['cid'];
unset($params['cid']);
// get the contact activities
$activities = CRM_Activity_BAO_Activity::getContactActivitySelector($params);
foreach ($activities['data'] as $key => $value) {
// Check if recurring activity.
if (!empty($value['is_recurring_activity'])) {
$repeat = $value['is_recurring_activity'];
$activities['data'][$key]['activity_type'] .= '<br/><span class="bold">' . ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])) . '</span>';
}
}
// store the activity filter preference CRM-11761
if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
unset($optionalParameters['context']);
foreach ($optionalParameters as $searchField => $dataType) {
$formSearchField = $searchField;
if ($searchField == 'activity_type_id') {
$formSearchField = 'activity_type_filter_id';
}
elseif ($searchField == 'activity_type_exclude_id') {
$formSearchField = 'activity_type_exclude_filter_id';
}
if (!empty($params[$searchField])) {
$activityFilter[$formSearchField] = CRM_Utils_Type::escape($params[$searchField], $dataType);
if (in_array($searchField, array('activity_date_low', 'activity_date_high'))) {
$activityFilter['activity_date_relative'] = 0;
}
elseif ($searchField == 'activity_status_id') {
$activityFilter['status_id'] = explode(',', $activityFilter[$searchField]);
}
}
elseif (in_array($searchField, array('activity_type_id', 'activity_type_exclude_id'))) {
$activityFilter[$formSearchField] = '';
}
}
/**
* @var \Civi\Core\SettingsBag $cSettings
*/
$cSettings = Civi::service('settings_manager')->getBagByContact(CRM_Core_Config::domainID(), $userID);
$cSettings->set('activity_tab_filter', $activityFilter);
}
if (!empty($_GET['is_unit_test'])) {
return array($activities, $activityFilter);
}
CRM_Utils_JSON::output($activities);
}
}

View file

@ -0,0 +1,219 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Main page for viewing activities,
*/
class CRM_Activity_Page_Tab extends CRM_Core_Page {
/**
* Browse all activities for a particular contact.
*/
public function browse() {
$this->assign('admin', FALSE);
$this->assign('context', 'activity');
// also create the form element for the activity filter box
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_ActivityFilter',
ts('Activity Filter'),
NULL,
FALSE, FALSE, TRUE
);
$controller->set('contactId', $this->_contactId);
$controller->setEmbedded(TRUE);
$controller->run();
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId);
}
/**
* Edit tab.
*
* @return mixed
*/
public function edit() {
// used for ajax tabs
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->assign('context', $context);
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
$this->_caseId = CRM_Utils_Request::retrieve('caseid', 'Integer', $this);
$activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
// Email and Create Letter activities use a different form class
$emailTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Email'
);
$letterTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Print PDF Letter'
);
switch ($activityTypeId) {
case $emailTypeValue:
$wrapper = new CRM_Utils_Wrapper();
$arguments = array('attachUpload' => 1);
return $wrapper->run('CRM_Contact_Form_Task_Email', ts('Email a Contact'), $arguments);
case $letterTypeValue:
$wrapper = new CRM_Utils_Wrapper();
$arguments = array('attachUpload' => 1);
return $wrapper->run('CRM_Contact_Form_Task_PDF', ts('Create PDF Letter'), $arguments);
default:
$controller = new CRM_Core_Controller_Simple('CRM_Activity_Form_Activity',
ts('Contact Activities'),
$this->_action,
FALSE, FALSE, FALSE, TRUE
);
}
$controller->setEmbedded(TRUE);
$controller->set('contactId', $this->_contactId);
$controller->set('atype', $activityTypeId);
$controller->set('id', $this->_id);
$controller->set('pid', $this->get('pid'));
$controller->set('action', $this->_action);
$controller->set('context', $context);
$controller->process();
$controller->run();
}
/**
* Heart of the viewing process.
*
* The runner gets all the meta data for the contact and calls the appropriate type of page to view.
*/
public function preProcess() {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->assign('contactId', $this->_contactId);
// FIXME: need to fix this conflict
$this->assign('contactID', $this->_contactId);
// check logged in url permission
CRM_Contact_Page_View::checkUserPermission($this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->assign('action', $this->_action);
// also create the form element for the activity links box
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_ActivityLinks',
ts('Activity Links'),
NULL,
FALSE, FALSE, TRUE
);
$controller->setEmbedded(TRUE);
$controller->run();
}
public function delete() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Activity_Form_Activity',
ts('Activity Record'),
$this->_action
);
$controller->set('id', $this->_id);
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
}
/**
* Perform actions and display for activities.
*/
public function run() {
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$action = CRM_Utils_Request::retrieve('action', 'String', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
// Do check for view/edit operation.
if ($this->_id &&
in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
) {
if (!CRM_Activity_BAO_Activity::checkPermission($this->_id, $action)) {
CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
}
}
if ($context == 'standalone' || (!$contactId && ($action != CRM_Core_Action::DELETE) && !$this->_id)) {
$this->_action = CRM_Core_Action::ADD;
$this->assign('action', $this->_action);
}
else {
// we should call contact view, preprocess only for activity in contact summary
$this->preProcess();
}
// route behaviour of contact/view/activity based on action defined
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::VIEW)
) {
$this->edit();
$activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
// Email and Create Letter activities use a different form class
$emailTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Email'
);
$letterTypeValue = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
'activity_type_id',
'Print PDF Letter'
);
if (in_array($activityTypeId, array(
$emailTypeValue,
$letterTypeValue,
))) {
return;
}
}
elseif ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH)) {
$this->delete();
}
else {
$this->browse();
}
return parent::run();
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is for building event(participation) block on user dashboard.
*/
class CRM_Activity_Page_UserDashboard extends CRM_Contact_Page_View_UserDashBoard {
/**
* List participations for the UF user.
*
* @return bool
*/
public function listActivities() {
$controller
= new CRM_Core_Controller_Simple(
'CRM_Activity_Form_Search', ts('Activities'),
NULL,
FALSE, FALSE, TRUE, FALSE
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('context', 'user');
$controller->set('cid', $this->_contactId);
// Limit to status "Scheduled" and "Available"
$controller->set('status', array('IN' => array(1, 7)));
$controller->set('activity_role', 2);
$controller->set('force', 1);
$controller->process();
$controller->run();
return FALSE;
}
/**
* The main function that is called when the page loads.
*
* It decides the which action has to be taken for the page.
*/
public function run() {
parent::preProcess();
$this->listActivities();
}
}

View file

@ -0,0 +1,546 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used to retrieve and display activities for a contact.
*/
class CRM_Activity_Selector_Activity extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* ContactId - contact id of contact whose activies are displayed
*
* @var int
*/
protected $_contactId;
protected $_admin;
protected $_context;
protected $_activityTypeIDs;
protected $_viewOptions;
/**
* Class constructor.
*
* @param int $contactId
* Contact whose activities we want to display.
* @param int $permission
* The permission we have for this contact.
*
* @param bool $admin
* @param string $context
* @param null $activityTypeIDs
*
* @return \CRM_Activity_Selector_Activity
*/
public function __construct(
$contactId,
$permission,
$admin = FALSE,
$context = 'activity',
$activityTypeIDs = NULL) {
$this->_contactId = $contactId;
$this->_permission = $permission;
$this->_admin = $admin;
$this->_context = $context;
$this->_activityTypeIDs = $activityTypeIDs;
// get all enabled view componentc (check if case is enabled)
$this->_viewOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_view_options', TRUE, NULL, TRUE
);
}
/**
* This method returns the action links that are given for each search row.
* currently the action links added for each row are
*
* - View
*
* @param int $activityTypeId
* @param int $sourceRecordId
* @param bool $accessMailingReport
* @param int $activityId
* @param null $key
* @param null $compContext
*
* @return array
*/
public static function actionLinks(
$activityTypeId,
$sourceRecordId = NULL,
$accessMailingReport = FALSE,
$activityId = NULL,
$key = NULL,
$compContext = NULL) {
static $activityActTypes = NULL;
//CRM-14277 added addtitional param to handle activity search
$extraParams = "&searchContext=activity";
$extraParams .= ($key) ? "&key={$key}" : NULL;
if ($compContext) {
$extraParams .= "&compContext={$compContext}";
}
$showView = TRUE;
$showUpdate = $showDelete = FALSE;
$qsUpdate = NULL;
if (!$activityActTypes) {
$activeActTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
}
$activityTypeName = CRM_Utils_Array::value($activityTypeId, $activeActTypes);
// CRM-7607
// Lets allow to have normal operation for only activity types.
// When activity type is disabled or no more exists give only delete.
switch ($activityTypeName) {
case 'Event Registration':
case 'Change Registration':
$url = 'civicrm/contact/view/participant';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Contribution':
$url = 'civicrm/contact/view/contribution';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Payment':
case 'Refund':
$participantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $sourceRecordId, 'participant_id', 'contribution_id');
if (!empty($participantId)) {
$url = 'civicrm/contact/view/participant';
$qsView = "action=view&reset=1&id={$participantId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
}
break;
case 'Membership Signup':
case 'Membership Renewal':
case 'Change Membership Status':
case 'Change Membership Type':
$url = 'civicrm/contact/view/membership';
$qsView = "action=view&reset=1&id={$sourceRecordId}&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Pledge Reminder':
case 'Pledge Acknowledgment':
$url = 'civicrm/contact/view/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Email':
case 'Bulk Email':
$url = 'civicrm/activity/view';
$delUrl = 'civicrm/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
if ($activityTypeName == 'Email') {
$showDelete = TRUE;
}
break;
case 'Inbound Email':
$url = 'civicrm/contact/view/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
case 'Open Case':
case 'Change Case Type':
case 'Change Case Status':
case 'Change Case Start Date':
$showUpdate = $showDelete = FALSE;
$url = 'civicrm/activity';
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$qsUpdate = "atype={$activityTypeId}&action=update&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
break;
default:
$url = 'civicrm/activity';
$showView = $showDelete = $showUpdate = TRUE;
$qsView = "atype={$activityTypeId}&action=view&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$qsUpdate = "atype={$activityTypeId}&action=update&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
// When type is not available lets hide view and update.
if (empty($activityTypeName)) {
$showView = $showUpdate = FALSE;
}
break;
}
$qsDelete = "atype={$activityTypeId}&action=delete&reset=1&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}";
$actionLinks = array();
if ($showView) {
$actionLinks += array(
CRM_Core_Action::
VIEW => array(
'name' => ts('View'),
'url' => $url,
'qs' => $qsView,
'title' => ts('View Activity'),
),
);
}
if ($showUpdate) {
$updateUrl = 'civicrm/activity/add';
if ($activityTypeName == 'Email') {
$updateUrl = 'civicrm/activity/email/add';
}
elseif ($activityTypeName == 'Print PDF Letter') {
$updateUrl = 'civicrm/activity/pdf/add';
}
if (CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::UPDATE)) {
$actionLinks += array(
CRM_Core_Action::
UPDATE => array(
'name' => ts('Edit'),
'url' => $updateUrl,
'qs' => $qsUpdate,
'title' => ts('Update Activity'),
),
);
}
}
if (
$activityTypeName &&
CRM_Case_BAO_Case::checkPermission($activityId, 'File On Case', $activityTypeId)
) {
$actionLinks += array(
CRM_Core_Action::
ADD => array(
'name' => ts('File on Case'),
'url' => '#',
'extra' => 'onclick="javascript:fileOnCase( \'file\', \'%%id%%\', null, this ); return false;"',
'title' => ts('File on Case'),
),
);
}
if ($showDelete) {
if (!isset($delUrl) || !$delUrl) {
$delUrl = $url;
}
$actionLinks += array(
CRM_Core_Action::
DELETE => array(
'name' => ts('Delete'),
'url' => $delUrl,
'qs' => $qsDelete,
'title' => ts('Delete Activity'),
),
);
}
if ($accessMailingReport) {
$actionLinks += array(
CRM_Core_Action::
BROWSE => array(
'name' => ts('Mailing Report'),
'url' => 'civicrm/mailing/report',
'qs' => "mid={$sourceRecordId}&reset=1&cid=%%cid%%&context=activitySelector",
'title' => ts('View Mailing Report'),
),
);
}
return $actionLinks;
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Activities %%StatusMessage%%');
$params['csvString'] = NULL;
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if ($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) {
$csvHeaders = array(ts('Activity Type'), ts('Description'), ts('Activity Date'));
foreach (self::_getColumnHeaders() as $column) {
if (array_key_exists('name', $column)) {
$csvHeaders[] = $column['name'];
}
}
return $csvHeaders;
}
else {
return self::_getColumnHeaders();
}
}
/**
* Returns total number of rows for the query.
*
* @param string $action
* Action being performed.
*
* @param null $case
*
* @return int
* Total number of rows
*/
public function getTotalCount($action, $case = NULL) {
$params = array(
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
'context' => $this->_context,
'activity_type_id' => $this->_activityTypeIDs,
'offset' => 0,
'rowCount' => 0,
'sort' => NULL,
);
return CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @param null $case
*
* @return int
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $case = NULL) {
$params = array(
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
'context' => $this->_context,
'activity_type_id' => $this->_activityTypeIDs,
'offset' => $offset,
'rowCount' => $rowCount,
'sort' => $sort,
);
$config = CRM_Core_Config::singleton();
$rows = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
if (empty($rows)) {
return $rows;
}
$activityStatus = CRM_Core_PseudoConstant::activityStatus();
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
// CRM-4418
$permissions = array($this->_permission);
if (CRM_Core_Permission::check('delete activities')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
foreach ($rows as $k => $row) {
$row = &$rows[$k];
// DRAFTING: provide a facility for db-stored strings
// localize the built-in activity names for display
// (these are not enums, so we can't use any automagic here)
switch ($row['activity_type']) {
case 'Meeting':
$row['activity_type'] = ts('Meeting');
break;
case 'Phone Call':
$row['activity_type'] = ts('Phone Call');
break;
case 'Email':
$row['activity_type'] = ts('Email');
break;
case 'SMS':
$row['activity_type'] = ts('SMS');
break;
case 'Event':
$row['activity_type'] = ts('Event');
break;
}
// add class to this row if overdue
if (CRM_Utils_Date::overdue(CRM_Utils_Array::value('activity_date_time', $row))
&& CRM_Utils_Array::value('status_id', $row) == 1
) {
$row['overdue'] = 1;
$row['class'] = 'status-overdue';
}
else {
$row['overdue'] = 0;
$row['class'] = 'status-ontime';
}
$row['status'] = $row['status_id'] ? $activityStatus[$row['status_id']] : NULL;
if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $row)) {
$row['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel);
}
// CRM-3553
$accessMailingReport = FALSE;
if (!empty($row['mailingId'])) {
$accessMailingReport = TRUE;
}
$actionLinks = $this->actionLinks(CRM_Utils_Array::value('activity_type_id', $row),
CRM_Utils_Array::value('source_record_id', $row),
$accessMailingReport,
CRM_Utils_Array::value('activity_id', $row),
$this->_key
);
$actionMask = array_sum(array_keys($actionLinks)) & $mask;
if ($output != CRM_Core_Selector_Controller::EXPORT && $output != CRM_Core_Selector_Controller::SCREEN) {
$row['action'] = CRM_Core_Action::formLink($actionLinks,
$actionMask,
array(
'id' => $row['activity_id'],
'cid' => $this->_contactId,
'cxt' => $this->_context,
'caseid' => CRM_Utils_Array::value('case_id', $row),
),
ts('more'),
FALSE,
'activity.selector.action',
'Activity',
$row['activity_id']
);
}
unset($row);
}
return $rows;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('CiviCRM Activity');
}
/**
* Get colunmn headers for search selector.
*
*
* @return array
*/
private static function &_getColumnHeaders() {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Type'),
'sort' => 'activity_type',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Subject'),
'sort' => 'subject',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Added By'),
'sort' => 'source_contact_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('name' => ts('With')),
array('name' => ts('Assigned')),
array(
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Status'),
'sort' => 'status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('desc' => ts('Actions')),
);
}
return self::$_columnHeaders;
}
}

View file

@ -0,0 +1,459 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used to retrieve and display a range of contacts that match the given criteria.
*
* Specifically for results of advanced search options.
*/
class CRM_Activity_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* This defines two actions- View and Edit.
*
* @var array
*/
static $_links = NULL;
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* Properties of contact we're interested in displaying
* @var array
*/
static $_properties = array(
'contact_id',
'contact_type',
'contact_sub_type',
'sort_name',
'display_name',
'activity_id',
'activity_date_time',
'activity_status_id',
'activity_status',
'activity_subject',
'source_record_id',
'activity_type_id',
'activity_type',
'activity_is_test',
'activity_campaign_id',
'activity_engagement_level',
);
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* What context are we being invoked from.
*
* @var string
*/
protected $_context = NULL;
/**
* What component context are we being invoked from.
*
* @var string
*/
protected $_compContext = NULL;
/**
* QueryParams is the array returned by exportValues called on.
* the HTML_QuickForm_Controller for that page.
*
* @var array
*/
public $_queryParams;
/**
* Represent the type of selector.
*
* @var int
*/
protected $_action;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_activityClause = NULL;
/**
* The query object.
*
* @var string
*/
protected $_query;
/**
* Class constructor.
*
* @param array $queryParams
* Array of parameters for query.
* @param \const|int $action - action of search basic or advanced.
* @param string $activityClause
* If the caller wants to further restrict the search (used in activities).
* @param bool $single
* Are we dealing only with one contact?.
* @param int $limit
* How many activities do we want returned.
*
* @param string $context
* @param null $compContext
*
* @return \CRM_Activity_Selector_Search
*/
public function __construct(
&$queryParams,
$action = CRM_Core_Action::NONE,
$activityClause = NULL,
$single = FALSE,
$limit = NULL,
$context = 'search',
$compContext = NULL
) {
// submitted form values
$this->_queryParams = &$queryParams;
$this->_single = $single;
$this->_limit = $limit;
$this->_context = $context;
$this->_compContext = $compContext;
$this->_activityClause = $activityClause;
// CRM-12675
$components = CRM_Core_Component::getNames();
$componentClause = array();
foreach ($components as $componentID => $componentName) {
// CRM-19201: Add support for searching CiviCampaign and CiviCase
// activities. For CiviCase, "access all cases and activities" is
// required here rather than "access my cases and activities" to
// prevent those with only the later permission from seeing a list
// of all cases which might present a privacy issue.
if (!CRM_Core_Permission::access($componentName, TRUE, TRUE)) {
$componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) ";
}
}
if (!empty($componentClause)) {
$componentRestriction = implode(' AND ', $componentClause);
if (empty($this->_activityClause)) {
$this->_activityClause = $componentRestriction;
}
else {
$this->_activityClause .= ' AND ' . $componentRestriction;
}
}
// type of selector
$this->_action = $action;
$this->_query = new CRM_Contact_BAO_Query($this->_queryParams,
CRM_Activity_BAO_Query::selectorReturnProperties(),
NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_ACTIVITY
);
$this->_query->_distinctComponentClause = '( civicrm_activity.id )';
$this->_query->_groupByComponentClause = " GROUP BY civicrm_activity.id ";
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Activities %%StatusMessage%%');
$params['csvString'] = NULL;
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns total number of rows for the query.
*
* @param string $action
*
* @return int
* Total number of rows
*/
public function getTotalCount($action) {
return $this->_query->searchQuery(0, 0, NULL,
TRUE, FALSE,
FALSE, FALSE,
FALSE,
$this->_activityClause
);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* rows in the given offset and rowCount
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$result = $this->_query->searchQuery(
$offset, $rowCount, $sort,
FALSE, FALSE,
FALSE, FALSE,
FALSE,
$this->_activityClause
);
$rows = array();
$mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
$accessCiviMail = CRM_Core_Permission::check('access CiviMail');
// Get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
// Get all activity types
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
while ($result->fetch()) {
$row = array();
// Ignore rows where we dont have an activity id.
if (empty($result->activity_id)) {
continue;
}
$this->_query->convertToPseudoNames($result);
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
$row[$property] = $result->$property;
}
}
$contactId = CRM_Utils_Array::value('contact_id', $row);
if (!$contactId) {
$contactId = CRM_Utils_Array::value('source_contact_id', $row);
}
$row['target_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $targetID);
$row['assignee_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $assigneeID);
list($row['source_contact_name'], $row['source_contact_id']) = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $sourceID, TRUE);
$row['source_contact_name'] = implode(',', array_values($row['source_contact_name']));
$row['source_contact_id'] = implode(',', $row['source_contact_id']);
if ($this->_context == 'search') {
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->activity_id;
}
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
$accessMailingReport = FALSE;
$activityTypeId = $row['activity_type_id'];
if ($row['activity_is_test']) {
$row['activity_type'] = $row['activity_type'] . " (test)";
}
$bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes);
$row['mailingId'] = '';
if (
$accessCiviMail &&
($mailingIDs === TRUE || in_array($result->source_record_id, $mailingIDs)) &&
($bulkActivityTypeID == $activityTypeId)
) {
$row['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
"mid={$result->source_record_id}&reset=1&cid={$contactId}&context=activitySelector"
);
$row['recipients'] = ts('(recipients)');
$row['target_contact_name'] = '';
$row['assignee_contact_name'] = '';
$accessMailingReport = TRUE;
}
$activityActions = new CRM_Activity_Selector_Activity($result->contact_id, NULL);
$actionLinks = $activityActions->actionLinks($activityTypeId,
CRM_Utils_Array::value('source_record_id', $row),
$accessMailingReport,
CRM_Utils_Array::value('activity_id', $row),
$this->_key,
$this->_compContext
);
$row['action'] = CRM_Core_Action::formLink($actionLinks, NULL,
array(
'id' => $result->activity_id,
'cid' => $contactId,
'cxt' => $this->_context,
),
ts('more'),
FALSE,
'activity.selector.row',
'Activity',
$result->activity_id
);
// Carry campaign to selector.
$row['campaign'] = CRM_Utils_Array::value($result->activity_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->activity_campaign_id;
if ($engagementLevel = CRM_Utils_Array::value('activity_engagement_level', $row)) {
$row['activity_engagement_level'] = CRM_Utils_Array::value($engagementLevel,
$engagementLevels, $engagementLevel
);
}
// Check if recurring activity.
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity');
$row['repeat'] = '';
if ($repeat) {
$row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
}
$rows[] = $row;
}
return $rows;
}
/**
* @return array
* which contains an array of strings
*/
public function getQILL() {
return $this->_query->qill();
}
/**
* Returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Type'),
'sort' => 'activity_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Subject'),
'sort' => 'activity_subject',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Added By'),
'sort' => 'source_contact',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('name' => ts('With')),
array('name' => ts('Assigned')),
array(
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Status'),
'sort' => 'activity_status',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'desc' => ts('Actions'),
),
);
}
return self::$_columnHeaders;
}
/**
* @return mixed
*/
public function alphabetQuery() {
return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
}
/**
* @return string
*/
public function &getQuery() {
return $this->_query;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('CiviCRM Activity Search');
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Activity_StateMachine_Search extends CRM_Core_StateMachine {
/**
* The task that the wizard is currently processing.
*
* @var string
*/
protected $_task;
/**
* Class constructor.
*
* @param object $controller
* @param \const|int $action
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$this->_pages = array();
$this->_pages['CRM_Activity_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
$this->_task = $task;
if (is_array($task)) {
foreach ($task as $t) {
$this->_pages[$t] = NULL;
}
}
else {
$this->_pages[$task] = NULL;
}
$this->addSequentialPages($this->_pages, $action);
}
/**
* Determine the form name based on the action. This allows us
* to avoid using conditional state machine, much more efficient
* and simpler
*
* @param CRM_Core_Controller $controller
* The controller object.
*
* @param string $formName
*
* @return string
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
// total hack, check POST vars and then session to determine stuff
$value = CRM_Utils_Array::value('task', $_POST);
if (!isset($value)) {
$value = $this->_controller->get('task');
}
$this->_controller->set('task', $value);
return CRM_Activity_Task::getTask($value);
}
/**
* Return the form name of the task.
*
* @return string
*/
public function getTaskFormName() {
return CRM_Utils_String::getClassName($this->_task);
}
/**
* Should the controller reset the session.
* In some cases, specifically search we want to remember
* state across various actions and want to go back to the
* beginning from the final state, but retain the same session
* values
*
* @return bool
*/
public function shouldReset() {
return FALSE;
}
}

View file

@ -0,0 +1,206 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class to represent the actions that can be performed on a group of contacts used by the search forms.
*/
class CRM_Activity_Task {
const
DELETE_ACTIVITIES = 1,
PRINT_ACTIVITIES = 2,
EXPORT_ACTIVITIES = 3,
BATCH_ACTIVITIES = 4,
EMAIL_CONTACTS = 5,
EMAIL_SMS = 6;
/**
* The task array.
*
* @var array
*/
static $_tasks = NULL;
/**
* The optional task array.
*
* @var array
*/
static $_optionalTasks = NULL;
/**
* These tasks are the core set of tasks that the user can perform
* on a contact / group of contacts.
*
* @return array
* the set of tasks for a group of contacts
*/
public static function &tasks() {
if (!(self::$_tasks)) {
self::$_tasks = array(
1 => array(
'title' => ts('Delete activities'),
'class' => 'CRM_Activity_Form_Task_Delete',
'result' => FALSE,
),
2 => array(
'title' => ts('Print selected rows'),
'class' => 'CRM_Activity_Form_Task_Print',
'result' => FALSE,
),
3 => array(
'title' => ts('Export activities'),
'class' => array(
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
),
'result' => FALSE,
),
4 => array(
'title' => ts('Update multiple activities'),
'class' => array(
'CRM_Activity_Form_Task_PickProfile',
'CRM_Activity_Form_Task_Batch',
),
'result' => FALSE,
),
5 => array(
'title' => ts('Email - send now'),
'class' => array(
'CRM_Activity_Form_Task_PickOption',
'CRM_Activity_Form_Task_Email',
),
'result' => FALSE,
),
6 => array(
'title' => ts('SMS - send reply'),
'class' => 'CRM_Activity_Form_Task_SMS',
'result' => FALSE,
),
7 => array(
'title' => ts('Tag - add to activities'),
'class' => 'CRM_Activity_Form_Task_AddToTag',
'result' => FALSE,
),
8 => array(
'title' => ts('Tag - remove from activities'),
'class' => 'CRM_Activity_Form_Task_RemoveFromTag',
'result' => FALSE,
),
);
$config = CRM_Core_Config::singleton();
if (in_array('CiviCase', $config->enableComponents)) {
if (CRM_Core_Permission::check('access all cases and activities') ||
CRM_Core_Permission::check('access my cases and activities')
) {
self::$_tasks[6] = array(
'title' => ts('File on case'),
'class' => 'CRM_Activity_Form_Task_FileOnCase',
'result' => FALSE,
);
}
}
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete activities')) {
unset(self::$_tasks[1]);
}
CRM_Utils_Hook::searchTasks('activity', self::$_tasks);
asort(self::$_tasks);
}
return self::$_tasks;
}
/**
* These tasks are the core set of task titles on activity.
*
* @return array
* the set of task titles
*/
public static function &taskTitles() {
self::tasks();
$titles = array();
foreach (self::$_tasks as $id => $value) {
$titles[$id] = $value['title'];
}
return $titles;
}
/**
* Show tasks selectively based on the permission level of the user.
*
* @param int $permission
*
* @return array
* set of tasks that are valid for the user
*/
public static function &permissionedTaskTitles($permission) {
$tasks = array();
if ($permission == CRM_Core_Permission::EDIT) {
$tasks = self::taskTitles();
}
else {
$tasks = array(
3 => self::$_tasks[3]['title'],
);
//CRM-4418,
if (CRM_Core_Permission::check('delete activities')) {
$tasks[1] = self::$_tasks[1]['title'];
}
}
return $tasks;
}
/**
* These tasks are the core set of tasks that the user can perform on activity.
*
* @param int $value
*
* @return array
* the set of tasks for a group of activity
*/
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
$value = 2;
}
return array(
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
);
}
}

View file

@ -0,0 +1,121 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class CRM_Member_Tokens
*
* Generate "activity.*" tokens.
*
* This TokenSubscriber was produced by refactoring the code from the
* scheduled-reminder system with the goal of making that system
* more flexible. The current implementation is still coupled to
* scheduled-reminders. It would be good to figure out a more generic
* implementation which is not tied to scheduled reminders, although
* that is outside the current scope.
*/
class CRM_Activity_Tokens extends \Civi\Token\AbstractTokenSubscriber {
/**
* CRM_Activity_Tokens constructor.
*/
public function __construct() {
parent::__construct('activity', array_merge(
array(
'activity_id' => ts('Activity ID'),
'activity_type' => ts('Activity Type'),
'subject' => ts('Activity Subject'),
'details' => ts('Activity Details'),
'activity_date_time' => ts('Activity Date-Time'),
),
CRM_Utils_Token::getCustomFieldTokens('Activity')
));
}
/**
* @inheritDoc
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
return
!empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_activity';
}
/**
* @inheritDoc
*/
public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e) {
if ($e->mapping->getEntity() !== 'civicrm_activity') {
return;
}
// The joint expression for activities needs some extra nuance to handle.
// Multiple revisions of the activity.
// Q: Could we simplify & move the extra AND clauses into `where(...)`?
$e->query->param('casEntityJoinExpr', 'e.id = reminder.entity_id AND e.is_current_revision = 1 AND e.is_deleted = 0');
$e->query->select('e.*'); // FIXME: seems too broad.
$e->query->select('ov.label as activity_type, e.id as activity_id');
$e->query->join("og", "!casMailingJoinType civicrm_option_group og ON og.name = 'activity_type'");
$e->query->join("ov", "!casMailingJoinType civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id");
// if CiviCase component is enabled, join for caseId.
$compInfo = CRM_Core_Component::getEnabledComponents();
if (array_key_exists('CiviCase', $compInfo)) {
$e->query->select("civicrm_case_activity.case_id as case_id");
$e->query->join('civicrm_case_activity', "LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`");
}
}
/**
* @inheritDoc
*/
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$actionSearchResult = $row->context['actionSearchResult'];
if (in_array($field, array('activity_date_time'))) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
elseif (isset($actionSearchResult->$field)) {
$row->tokens($entity, $field, $actionSearchResult->$field);
}
elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
$row->customToken($entity, $cfID, $actionSearchResult->entity_id);
}
else {
$row->tokens($entity, $field, '');
}
}
}

View file

@ -0,0 +1,155 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Base class for admin forms.
*/
class CRM_Admin_Form extends CRM_Core_Form {
/**
* The id of the object being edited / created
*
* @var int
*/
protected $_id;
/**
* The default values for form fields.
*
* @var int
*/
protected $_values;
/**
* The name of the BAO object for this form.
*
* @var string
*/
protected $_BAOName;
/**
* Explicitly declare the form context.
*/
public function getDefaultContext() {
return 'create';
}
/**
* Basic setup.
*/
public function preProcess() {
Civi::resources()->addStyleFile('civicrm', 'css/admin.css');
Civi::resources()->addScriptFile('civicrm', 'js/crm.admin.js');
$this->_id = $this->get('id');
$this->_BAOName = $this->get('BAOName');
$this->_values = array();
if (isset($this->_id)) {
$params = array('id' => $this->_id);
// this is needed if the form is outside the CRM name space
$baoName = $this->_BAOName;
$baoName::retrieve($params, $this->_values);
}
}
/**
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
*
* @return array
*/
public function setDefaultValues() {
// Fetch defaults from the db
if (!empty($this->_id) && empty($this->_values) && CRM_Utils_Rule::positiveInteger($this->_id)) {
$this->_values = array();
$params = array('id' => $this->_id);
$baoName = $this->_BAOName;
$baoName::retrieve($params, $this->_values);
}
$defaults = $this->_values;
// Allow defaults to be set from the url
if (empty($this->_id) && $this->_action & CRM_Core_Action::ADD) {
foreach ($_GET as $key => $val) {
if ($this->elementExists($key)) {
$defaults[$key] = $val;
}
}
}
if ($this->_action == CRM_Core_Action::DELETE &&
isset($defaults['name'])
) {
$this->assign('delName', $defaults['name']);
}
// its ok if there is no element called is_active
$defaults['is_active'] = ($this->_id) ? CRM_Utils_Array::value('is_active', $defaults) : 1;
if (!empty($defaults['parent_id'])) {
$this->assign('is_parent', TRUE);
}
return $defaults;
}
/**
* Add standard buttons.
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::VIEW || $this->_action & CRM_Core_Action::PREVIEW) {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
else {
$this->addButtons(array(
array(
'type' => 'next',
'name' => $this->_action & CRM_Core_Action::DELETE ? ts('Delete') : ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
}
}

View file

@ -0,0 +1,89 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Synchronizing CMS Users
*/
class CRM_Admin_Form_CMSUser extends CRM_Core_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('OK'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Process the form submission.
*/
public function postProcess() {
$result = CRM_Utils_System::synchronizeUsers();
$status = ts('Checked one user record.',
array(
'count' => $result['contactCount'],
'plural' => 'Checked %count user records.',
)
);
if ($result['contactMatching']) {
$status .= '<br />' . ts('Found one matching contact record.',
array(
'count' => $result['contactMatching'],
'plural' => 'Found %count matching contact records.',
)
);
}
$status .= '<br />' . ts('Created one new contact record.',
array(
'count' => $result['contactCreated'],
'plural' => 'Created %count new contact records.',
)
);
CRM_Core_Session::setStatus($status, ts('Synchronize Complete'), 'success');
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
}
}

View file

@ -0,0 +1,149 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for ContactSub Type.
*/
class CRM_Admin_Form_ContactType extends CRM_Admin_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->setPageTitle(ts('Contact Type'));
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$this->applyFilter('__ALL__', 'trim');
$this->add('text', 'label', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_ContactType', 'label'),
TRUE
);
$contactType = $this->add('select', 'parent_id', ts('Basic Contact Type'),
CRM_Contact_BAO_ContactType::basicTypePairs(FALSE, 'id')
);
$enabled = $this->add('checkbox', 'is_active', ts('Enabled?'));
if ($this->_action & CRM_Core_Action::UPDATE) {
$contactType->freeze();
// We'll display actual "name" for built-in types (for reference) when editing their label / image_URL
$contactTypeName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $this->_id, 'name');
$this->assign('contactTypeName', $contactTypeName);
$this->_parentId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $this->_id, 'parent_id');
// Freeze Enabled field for built-in contact types (parent_id is NULL for these)
if (is_null($this->_parentId)) {
$enabled->freeze();
}
}
$this->addElement('text', 'image_URL', ts('Image URL'));
$this->add('text', 'description', ts('Description'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_ContactType', 'description')
);
$this->assign('cid', $this->_id);
$this->addFormRule(array('CRM_Admin_Form_ContactType', 'formRule'), $this);
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
*
* @param $files
* @param $self
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
if ($self->_id) {
$contactName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $self->_id, 'name');
}
else {
$contactName = ucfirst(CRM_Utils_String::munge($fields['label']));
}
if (!CRM_Core_DAO::objectExists($contactName, 'CRM_Contact_DAO_ContactType', $self->_id)) {
$errors['label'] = ts('This contact type name already exists in database. Contact type names must be unique.');
}
$reservedKeyWords = CRM_Core_SelectValues::customGroupExtends();
//restrict "name" from being a reserved keyword when a new contact subtype is created
if (!$self->_id && in_array($contactName, array_keys($reservedKeyWords))) {
$errors['label'] = ts('Contact type names should not use reserved keywords.');
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_Utils_System::flushCache();
if ($this->_action & CRM_Core_Action::DELETE) {
$isDelete = CRM_Contact_BAO_ContactType::del($this->_id);
if ($isDelete) {
CRM_Core_Session::setStatus(ts('Selected contact type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
CRM_Core_Session::setStatus(ts("Selected contact type can not be deleted. Make sure contact type doesn't have any associated custom data or group."), ts('Sorry'), 'error');
}
return;
}
// store the submitted values in an array
$params = $this->exportValues();
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
// Force Enabled = true for built-in contact types to fix problems caused by CRM-6471 (parent_id is NULL for these types)
if (is_null($this->_parentId)) {
$params['is_active'] = 1;
}
}
if ($this->_action & CRM_Core_Action::ADD) {
$params['name'] = ucfirst(CRM_Utils_String::munge($params['label']));
}
$contactType = CRM_Contact_BAO_ContactType::add($params);
CRM_Core_Session::setStatus(ts("The Contact Type '%1' has been saved.",
array(1 => $contactType->label)
), ts('Saved'), 'success');
}
}

View file

@ -0,0 +1,225 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Extensions.
*/
class CRM_Admin_Form_Extensions extends CRM_Admin_Form {
/**
* Form pre-processing.
*/
public function preProcess() {
parent::preProcess();
$mainPage = new CRM_Admin_Page_Extensions();
$localExtensionRows = $mainPage->formatLocalExtensionRows();
$this->assign('localExtensionRows', $localExtensionRows);
$remoteExtensionRows = $mainPage->formatRemoteExtensionRows($localExtensionRows);
$this->assign('remoteExtensionRows', $remoteExtensionRows);
$this->_key = CRM_Utils_Request::retrieve('key', 'String',
$this, FALSE, 0
);
if (!CRM_Utils_Type::validate($this->_key, 'ExtensionKey') && !empty($this->_key)) {
throw new CRM_Core_Exception('Extension Key does not match expected standard');
}
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1&action=browse');
$session->pushUserContext($url);
$this->assign('id', $this->_id);
$this->assign('key', $this->_key);
switch ($this->_action) {
case CRM_Core_Action::ADD:
case CRM_Core_Action::DELETE:
case CRM_Core_Action::ENABLE:
case CRM_Core_Action::DISABLE:
$info = CRM_Extension_System::singleton()->getMapper()->keyToInfo($this->_key);
$extInfo = CRM_Admin_Page_Extensions::createExtendedInfo($info);
$this->assign('extension', $extInfo);
break;
case CRM_Core_Action::UPDATE:
if (!CRM_Extension_System::singleton()->getBrowser()->isEnabled()) {
CRM_Core_Error::fatal(ts('The system administrator has disabled this feature.'));
}
$info = CRM_Extension_System::singleton()->getBrowser()->getExtension($this->_key);
$extInfo = CRM_Admin_Page_Extensions::createExtendedInfo($info);
$this->assign('extension', $extInfo);
break;
default:
CRM_Core_Error::fatal(ts('Unsupported action'));
}
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = array();
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
switch ($this->_action) {
case CRM_Core_Action::ADD:
$buttonName = ts('Install');
$title = ts('Install "%1"?', array(
1 => $this->_key,
));
break;
case CRM_Core_Action::UPDATE:
$buttonName = ts('Download and Install');
$title = ts('Download and Install "%1"?', array(
1 => $this->_key,
));
break;
case CRM_Core_Action::DELETE:
$buttonName = ts('Uninstall');
$title = ts('Uninstall "%1"?', array(
1 => $this->_key,
));
break;
case CRM_Core_Action::ENABLE:
$buttonName = ts('Enable');
$title = ts('Enable "%1"?', array(
1 => $this->_key,
));
break;
case CRM_Core_Action::DISABLE:
$buttonName = ts('Disable');
$title = ts('Disable "%1"?', array(
1 => $this->_key,
));
break;
}
$this->assign('title', $title);
$this->addButtons(array(
array(
'type' => 'next',
'name' => $buttonName,
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param array $self
* This object.
*
* @return bool|array
* true if no errors, else an array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_Utils_System::flushCache();
if ($this->_action & CRM_Core_Action::DELETE) {
try {
CRM_Extension_System::singleton()->getManager()->uninstall(array($this->_key));
CRM_Core_Session::setStatus("", ts('Extension Uninstalled'), "success");
}
catch (CRM_Extension_Exception_DependencyException $e) {
// currently only thrown for payment-processor dependencies
CRM_Core_Session::setStatus(ts('Cannot uninstall this extension - there is at least one payment processor using the payment processor type provided by it.'), ts('Uninstall Error'), 'error');
}
}
if ($this->_action & CRM_Core_Action::ADD) {
civicrm_api3('Extension', 'install', array('keys' => $this->_key));
CRM_Core_Session::setStatus("", ts('Extension Installed'), "success");
}
if ($this->_action & CRM_Core_Action::ENABLE) {
civicrm_api3('Extension', 'enable', array('keys' => $this->_key));
CRM_Core_Session::setStatus("", ts('Extension Enabled'), "success");
}
if ($this->_action & CRM_Core_Action::DISABLE) {
CRM_Extension_System::singleton()->getManager()->disable(array($this->_key));
CRM_Core_Session::setStatus("", ts('Extension Disabled'), "success");
}
if ($this->_action & CRM_Core_Action::UPDATE) {
$result = civicrm_api('Extension', 'download', array(
'version' => 3,
'key' => $this->_key,
));
if (!CRM_Utils_Array::value('is_error', $result, FALSE)) {
CRM_Core_Session::setStatus("", ts('Extension Upgraded'), "success");
}
else {
CRM_Core_Session::setStatus($result['error_message'], ts('Extension Upgrade Failed'), "error");
}
}
CRM_Utils_System::redirect(
CRM_Utils_System::url(
'civicrm/admin/extensions',
'reset=1&action=browse'
)
);
}
}

View file

@ -0,0 +1,242 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class for configuring jobs.
*/
class CRM_Admin_Form_Job extends CRM_Admin_Form {
protected $_id = NULL;
public function preProcess() {
parent::preProcess();
CRM_Utils_System::setTitle(ts('Manage - Scheduled Jobs'));
if ($this->_id) {
$refreshURL = CRM_Utils_System::url('civicrm/admin/job',
"reset=1&action=update&id={$this->_id}",
FALSE, NULL, FALSE
);
}
else {
$refreshURL = CRM_Utils_System::url('civicrm/admin/job',
"reset=1&action=add",
FALSE, NULL, FALSE
);
}
$this->assign('refreshURL', $refreshURL);
}
/**
* Build the form object.
*
* @param bool $check
*/
public function buildQuickForm($check = FALSE) {
parent::buildQuickForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Job');
$this->add('text', 'name', ts('Name'),
$attributes['name'], TRUE
);
$this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
'CRM_Core_DAO_Job',
$this->_id,
));
$this->add('text', 'description', ts('Description'),
$attributes['description']
);
$this->add('text', 'api_entity', ts('API Call Entity'),
$attributes['api_entity'], TRUE
);
$this->add('text', 'api_action', ts('API Call Action'),
$attributes['api_action'], TRUE
);
$this->add('select', 'run_frequency', ts('Run frequency'), CRM_Core_SelectValues::getJobFrequency());
// CRM-17686
$this->add('datepicker', 'scheduled_run_date', ts('Scheduled Run Date'), NULL, FALSE, array('minDate' => time()));
$this->add('textarea', 'parameters', ts('Command parameters'),
"cols=50 rows=6"
);
// is this job active ?
$this->add('checkbox', 'is_active', ts('Is this Scheduled Job active?'));
$this->addFormRule(array('CRM_Admin_Form_Job', 'formRule'));
}
/**
* @param $fields
*
* @return array|bool
* @throws API_Exception
*/
public static function formRule($fields) {
$errors = array();
require_once 'api/api.php';
/** @var \Civi\API\Kernel $apiKernel */
$apiKernel = \Civi::service('civi_api_kernel');
$apiRequest = \Civi\API\Request::create($fields['api_entity'], $fields['api_action'], array('version' => 3), NULL);
try {
$apiKernel->resolve($apiRequest);
}
catch (\Civi\API\Exception\NotImplementedException $e) {
$errors['api_action'] = ts('Given API command is not defined.');
}
if (!empty($errors)) {
return $errors;
}
return empty($errors) ? TRUE : $errors;
}
/**
* @return array
*/
public function setDefaultValues() {
$defaults = array();
if (!$this->_id) {
$defaults['is_active'] = $defaults['is_default'] = 1;
return $defaults;
}
$domainID = CRM_Core_Config::domainID();
$dao = new CRM_Core_DAO_Job();
$dao->id = $this->_id;
$dao->domain_id = $domainID;
if (!$dao->find(TRUE)) {
return $defaults;
}
CRM_Core_DAO::storeValues($dao, $defaults);
// CRM-17686
if (!empty($dao->scheduled_run_date)) {
$ts = strtotime($dao->scheduled_run_date);
$defaults['scheduled_run_date'] = date("Y-m-d H:i:s", $ts);
}
// CRM-10708
// job entity thats shipped with core is all lower case.
// this makes sure camel casing is followed for proper working of default population.
if (!empty($defaults['api_entity'])) {
$defaults['api_entity'] = ucfirst($defaults['api_entity']);
}
return $defaults;
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_Utils_System::flushCache('CRM_Core_DAO_Job');
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_BAO_Job::del($this->_id);
CRM_Core_Session::setStatus("", ts('Scheduled Job Deleted.'), "success");
return;
}
$values = $this->controller->exportValues($this->_name);
$domainID = CRM_Core_Config::domainID();
$dao = new CRM_Core_DAO_Job();
$dao->id = $this->_id;
$dao->domain_id = $domainID;
$dao->run_frequency = $values['run_frequency'];
$dao->parameters = $values['parameters'];
$dao->name = $values['name'];
$dao->api_entity = $values['api_entity'];
$dao->api_action = $values['api_action'];
$dao->description = $values['description'];
$dao->is_active = CRM_Utils_Array::value('is_active', $values, 0);
// CRM-17686
$ts = strtotime($values['scheduled_run_date']);
// if a date/time is supplied and not in the past, then set the next scheduled run...
if ($ts > time()) {
$dao->scheduled_run_date = CRM_Utils_Date::currentDBDate($ts);
// warn about monthly/quarterly scheduling, if applicable
if (($dao->run_frequency == 'Monthly') || ($dao->run_frequency == 'Quarter')) {
$info = getdate($ts);
if ($info['mday'] > 28) {
CRM_Core_Session::setStatus(
ts('Relative month values are calculated based on the length of month(s) that they pass through.
The result will land on the same day of the month except for days 29-31 when the target month contains fewer days than the previous month.
For example, if a job is scheduled to run on August 31st, the following invocation will occur on October 1st, and then the 1st of every month thereafter.
To avoid this issue, please schedule Monthly and Quarterly jobs to run within the first 28 days of the month.'),
ts('Warning'), 'info', array('expires' => 0));
}
}
}
// ...otherwise, if this isn't a new scheduled job, clear the next scheduled run
elseif ($dao->id) {
$job = new CRM_Core_ScheduledJob(array('id' => $dao->id));
$job->clearScheduledRunDate();
}
$dao->save();
// CRM-11143 - Give warning message if update_greetings is Enabled (is_active) since it generally should not be run automatically via execute action or runjobs url.
if ($values['api_action'] == 'update_greeting' && CRM_Utils_Array::value('is_active', $values) == 1) {
// pass "wiki" as 6th param to docURL2 if you are linking to a page in wiki.civicrm.org
$docLink = CRM_Utils_System::docURL2("Managing Scheduled Jobs", NULL, NULL, NULL, NULL, "wiki");
$msg = ts('The update greeting job can be very resource intensive and is typically not necessary to run on a regular basis. If you do choose to enable the job, we recommend you do not run it with the force=1 option, which would rebuild greetings on all records. Leaving that option absent, or setting it to force=0, will only rebuild greetings for contacts that do not currently have a value stored. %1', array(1 => $docLink));
CRM_Core_Session::setStatus($msg, ts('Warning: Update Greeting job enabled'), 'alert');
}
}
}

View file

@ -0,0 +1,250 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright (C) 2011 Marty Wright |
| Licensed to CiviCRM under the Academic Free License version 3.0. |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Label Format Settings.
*/
class CRM_Admin_Form_LabelFormats extends CRM_Admin_Form {
/**
* Label Format ID.
*/
protected $_id = NULL;
/**
* Group name, label format or name badge
*/
protected $_group = NULL;
public function preProcess() {
$this->_id = $this->get('id');
$this->_group = CRM_Utils_Request::retrieve('group', 'String', $this, FALSE, 'label_format');
$this->_values = array();
if (isset($this->_id)) {
$params = array('id' => $this->_id);
CRM_Core_BAO_LabelFormat::retrieve($params, $this->_values, $this->_group);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::COPY)) {
$formatName = CRM_Core_BAO_LabelFormat::getFieldValue('CRM_Core_BAO_LabelFormat', $this->_id, 'label');
$this->assign('formatName', $formatName);
return;
}
$disabled = array();
$required = TRUE;
$is_reserved = $this->_id ? CRM_Core_BAO_LabelFormat::getFieldValue('CRM_Core_BAO_LabelFormat', $this->_id, 'is_reserved') : FALSE;
if ($is_reserved) {
$disabled['disabled'] = 'disabled';
$required = FALSE;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat');
$this->add('text', 'label', ts('Name'), $attributes['label'] + $disabled, $required);
$this->add('text', 'description', ts('Description'), array('size' => CRM_Utils_Type::HUGE));
$this->add('checkbox', 'is_default', ts('Is this Label Format the default?'));
// currently we support only mailing label creation, hence comment below code
/*
$options = array(
'label_format' => ts('Mailing Label'),
'name_badge' => ts('Name Badge'),
);
$labelType = $this->addRadio('label_type', ts('Used For'), $options, null, '&nbsp;&nbsp;');
if ($this->_action != CRM_Core_Action::ADD) {
$labelType->freeze();
}
*/
$this->add('select', 'paper_size', ts('Sheet Size'),
array(
0 => ts('- default -'),
) + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
array(
'onChange' => "selectPaper( this.value );",
) + $disabled
);
$this->add('static', 'paper_dimensions', NULL, ts('Sheet Size (w x h)'));
$this->add('select', 'orientation', ts('Orientation'), CRM_Core_BAO_LabelFormat::getPageOrientations(), FALSE,
array(
'onChange' => "updatePaperDimensions();",
) + $disabled
);
$this->add('select', 'font_name', ts('Font Name'), CRM_Core_BAO_LabelFormat::getFontNames($this->_group));
$this->add('select', 'font_size', ts('Font Size'), CRM_Core_BAO_LabelFormat::getFontSizes());
$this->add('static', 'font_style', ts('Font Style'));
$this->add('checkbox', 'bold', ts('Bold'));
$this->add('checkbox', 'italic', ts('Italic'));
$this->add('select', 'metric', ts('Unit of Measure'), CRM_Core_BAO_LabelFormat::getUnits(), FALSE,
array('onChange' => "selectMetric( this.value );")
);
$this->add('text', 'width', ts('Label Width'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'height', ts('Label Height'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'NX', ts('Labels Per Row'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
$this->add('text', 'NY', ts('Labels Per Column'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
$this->add('text', 'tMargin', ts('Top Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'lMargin', ts('Left Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'SpaceX', ts('Horizontal Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'SpaceY', ts('Vertical Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
$this->add('text', 'lPadding', ts('Left Padding'), array('size' => 8, 'maxlength' => 8), $required);
$this->add('text', 'tPadding', ts('Top Padding'), array('size' => 8, 'maxlength' => 8), $required);
$this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'weight'), TRUE);
$this->addRule('label', ts('Name already exists in Database.'), 'objectExists', array(
'CRM_Core_BAO_LabelFormat',
$this->_id,
));
$this->addRule('NX', ts('Please enter a valid integer.'), 'integer');
$this->addRule('NY', ts('Please enter a valid integer.'), 'integer');
$this->addRule('tMargin', ts('Please enter a valid number.'), 'numeric');
$this->addRule('lMargin', ts('Please enter a valid number.'), 'numeric');
$this->addRule('SpaceX', ts('Please enter a valid number.'), 'numeric');
$this->addRule('SpaceY', ts('Please enter a valid number.'), 'numeric');
$this->addRule('lPadding', ts('Please enter a valid number.'), 'numeric');
$this->addRule('tPadding', ts('Please enter a valid number.'), 'numeric');
$this->addRule('width', ts('Please enter a valid number.'), 'numeric');
$this->addRule('height', ts('Please enter a valid number.'), 'numeric');
$this->addRule('weight', ts('Please enter a valid integer.'), 'integer');
}
/**
* @return int
*/
public function setDefaultValues() {
if ($this->_action & CRM_Core_Action::ADD) {
$defaults['weight'] = CRM_Utils_Array::value('weight', CRM_Core_BAO_LabelFormat::getDefaultValues($this->_group), 0);
}
else {
$defaults = $this->_values;
// Convert field names that are illegal PHP/SMARTY variable names
$defaults['paper_size'] = $defaults['paper-size'];
unset($defaults['paper-size']);
$defaults['font_name'] = $defaults['font-name'];
unset($defaults['font-name']);
$defaults['font_size'] = $defaults['font-size'];
unset($defaults['font-size']);
$defaults['bold'] = (stripos($defaults['font-style'], 'B') !== FALSE);
$defaults['italic'] = (stripos($defaults['font-style'], 'I') !== FALSE);
unset($defaults['font-style']);
}
$defaults['label_type'] = $this->_group;
return $defaults;
}
/**
* Process the form submission.
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
// delete Label Format
CRM_Core_BAO_LabelFormat::del($this->_id, $this->_group);
CRM_Core_Session::setStatus(ts('Selected Label Format has been deleted.'), ts('Record Deleted'), 'success');
return;
}
if ($this->_action & CRM_Core_Action::COPY) {
// make a copy of the Label Format
$labelFormat = CRM_Core_BAO_LabelFormat::getById($this->_id, $this->_group);
$newlabel = ts('Copy of %1', array(1 => $labelFormat['label']));
$list = CRM_Core_BAO_LabelFormat::getList(TRUE, $this->_group);
$count = 1;
while (in_array($newlabel, $list)) {
$count++;
$newlabel = ts('Copy %1 of %2', array(1 => $count, 2 => $labelFormat['label']));
}
$labelFormat['label'] = $newlabel;
$labelFormat['grouping'] = CRM_Core_BAO_LabelFormat::customGroupName();
$labelFormat['is_default'] = 0;
$labelFormat['is_reserved'] = 0;
$bao = new CRM_Core_BAO_LabelFormat();
$bao->saveLabelFormat($labelFormat, NULL, $this->_group);
CRM_Core_Session::setStatus(ts('%1 has been created.', array(1 => $labelFormat['label'])), ts('Saved'), 'success');
return;
}
$values = $this->controller->exportValues($this->getName());
// since we currently support only mailing label format
$values['label_type'] = 'label_format';
$values['is_default'] = isset($values['is_default']);
// Restore field names that were converted because they are illegal PHP/SMARTY variable names
if (isset($values['paper_size'])) {
$values['paper-size'] = $values['paper_size'];
unset($values['paper_size']);
}
if (isset($values['font_name'])) {
$values['font-name'] = $values['font_name'];
unset($values['font_name']);
}
if (isset($values['font_size'])) {
$values['font-size'] = $values['font_size'];
unset($values['font_size']);
}
$style = '';
if (isset($values['bold'])) {
$style .= 'B';
}
if (isset($values['italic'])) {
$style .= 'I';
}
$values['font-style'] = $style;
$bao = new CRM_Core_BAO_LabelFormat();
$bao->saveLabelFormat($values, $this->_id, $values['label_type']);
$status = ts('Your new Label Format titled <strong>%1</strong> has been saved.', array(1 => $values['label']));
if ($this->_action & CRM_Core_Action::UPDATE) {
$status = ts('Your Label Format titled <strong>%1</strong> has been updated.', array(1 => $values['label']));
}
CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
}
}

View file

@ -0,0 +1,127 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Location Type.
*/
class CRM_Admin_Form_LocationType extends CRM_Admin_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->setPageTitle(ts('Location Type'));
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$this->applyFilter('__ALL__', 'trim');
$this->add('text',
'name',
ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_LocationType', 'name'),
TRUE
);
$this->addRule('name',
ts('Name already exists in Database.'),
'objectExists',
array('CRM_Core_DAO_LocationType', $this->_id)
);
$this->addRule('name',
ts('Name can only consist of alpha-numeric characters'),
'variable'
);
$this->add('text', 'display_name', ts('Display Name'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_LocationType', 'display_name'), TRUE);
$this->add('text', 'vcard_name', ts('vCard Name'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_LocationType', 'vcard_name'));
$this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_LocationType', 'description'));
$this->add('checkbox', 'is_active', ts('Enabled?'));
$this->add('checkbox', 'is_default', ts('Default?'));
if ($this->_action & CRM_Core_Action::UPDATE) {
if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', $this->_id, 'is_reserved')) {
$this->freeze(array('name', 'description', 'is_active'));
}
if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', $this->_id, 'is_default')) {
$this->freeze(array('is_default'));
}
}
}
/**
* Process the form submission.
*/
public function postProcess() {
CRM_Utils_System::flushCache('CRM_Core_DAO_LocationType');
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_BAO_LocationType::del($this->_id);
CRM_Core_Session::setStatus(ts('Selected Location type has been deleted.'), ts('Record Deleted'), 'success');
return;
}
// store the submitted values in an array
$params = $this->exportValues();
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
// action is taken depending upon the mode
$locationType = new CRM_Core_DAO_LocationType();
$locationType->name = $params['name'];
$locationType->display_name = $params['display_name'];
$locationType->vcard_name = $params['vcard_name'];
$locationType->description = $params['description'];
$locationType->is_active = $params['is_active'];
$locationType->is_default = $params['is_default'];
if ($params['is_default']) {
$query = "UPDATE civicrm_location_type SET is_default = 0";
CRM_Core_DAO::executeQuery($query);
}
if ($this->_action & CRM_Core_Action::UPDATE) {
$locationType->id = $this->_id;
}
$locationType->save();
CRM_Core_Session::setStatus(ts("The location type '%1' has been saved.",
array(1 => $locationType->name)
), ts('Saved'), 'success');
}
}

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