first global commit

This commit is contained in:
2020-09-23 15:50:29 +02:00
commit 78adf3a099
6052 changed files with 1221183 additions and 0 deletions
@@ -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.
@@ -0,0 +1,45 @@
Views Data Export
=================
Introduction
------------
This module is designed to provide a way to export large amounts of data from
views. It provides a display plugin that can rendered progressively in a batch.
Style plugins are include that support exporting in the following types:
* CSV
* Microsoft XLS
* Microsoft Doc
* Basic txt
* Simple xml.
Using the "Views Data Export" module
------------------------------------
1. Add a new "Data export" display to your view.
2. Change its "Style" to the desired export type. e.g. "CSV file".
3. Configure the options (such as name, quote, etc.). You can go back and do
this at any time by clicking the gear icon next to the style plugin you just
selected.
4. Give it a path in the Feed settings such as "path/to/view/csv".
5. Optionally, you can choose to attach this to another of your displays by
updating the "Attach to:" option in feed settings.
Advanced usage
--------------
This module also exposes a drush command that can execute the view and save its
results to a file.
drush views-data-export [view-name] [display-id] [output-file]
History
-------
This module has its roots in the export module that was part of the views bonus
pack (http://drupal.org/project/views_bonus). However, massive changes were
needed to make the batch export functionality work, and so this fork was
created. See: http://drupal.org/node/805960
Binary file not shown.

After

Width:  |  Height:  |  Size: 637 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 362 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 568 B

@@ -0,0 +1,831 @@
<?php
/**
* @file
* Contains the bulk export display plugin.
*
* This allows views to be rendered in parts by batch API.
*/
/**
* The plugin that batches its rendering.
*
* We are based on a feed display for compatibility.
*
* @ingroup views_display_plugins
*/
class views_data_export_plugin_display_export extends views_plugin_display_feed {
/**
* The batched execution state of the view.
*/
public $batched_execution_state;
/**
* The alias of the weight field in the index table.
*/
var $weight_field_alias = '';
/**
* A map of the index column names to the expected views aliases.
*/
var $field_aliases = array();
/**
* Private variable that stores the filename to save the results to.
*/
var $_output_file = '';
var $views_data_export_cached_view_loaded;
var $errors = array();
/**
* Return the type of styles we require.
*/
function get_style_type() { return 'data_export'; }
/**
* Return the sections that can be defaultable.
*/
function defaultable_sections($section = NULL) {
if (in_array($section, array('items_per_page', 'offset', 'use_pager', 'pager_element',))) {
return FALSE;
}
return parent::defaultable_sections($section);
}
/**
* Define the option for this view.
*/
function option_definition() {
$options = parent::option_definition();
$options['use_batch'] = array('default' => 'no_batch');
$options['items_per_page'] = array('default' => '0');
$options['style_plugin']['default'] = 'views_data_export_csv';
if (isset($options['defaults']['default']['items_per_page'])) {
$options['defaults']['default']['items_per_page'] = FALSE;
}
return $options;
}
/**
* Provide the summary for page options in the views UI.
*
* This output is returned as an array.
*/
function options_summary(&$categories, &$options) {
// It is very important to call the parent function here:
parent::options_summary($categories, $options);
$categories['page']['title'] = t('Data export settings');
$options['use_batch'] = array(
'category' => 'page',
'title' => t('Batched export'),
'value' => ($this->get_option('use_batch') == 'batch' ? t('Yes') : t('No')),
);
if (!$this->is_compatible() && $this->get_option('use_batch')) {
$options['use_batch']['value'] .= ' <strong>' . t('(Warning: incompatible)') . '</strong>';
}
}
/**
* Provide the default form for setting options.
*/
function options_form(&$form, &$form_state) {
// It is very important to call the parent function here:
parent::options_form($form, $form_state);
switch ($form_state['section']) {
case 'use_batch':
$form['#title'] .= t('Batched export');
$form['use_batch'] = array(
'#type' => 'radios',
'#description' => t(''),
'#default_value' => $this->get_option('use_batch'),
'#options' => array(
'no_batch' => t('Export data all in one segment. Possible time and memory limit issues.'),
'batch' => t('Export data in small segments to build a complete export. Recommended for large exports sets (1000+ rows)'),
),
);
if (!$this->is_compatible()) {
$form['use_batch']['#disabled'] = TRUE;
$form['use_batch']['#default_value'] = 'no_batch';
$form['use_batch']['message'] = array (
'#type' => 'markup',
'#markup' => theme('views_data_export_message', array('message' => t('The underlying database (!db_driver) is incompatible with the batched export option and it has been disabled.', array('!db_driver' => $this->_get_database_driver())), 'type' => 'warning')),
'#weight' => -10,
);
}
break;
}
}
/**
* Save the options from the options form.
*/
function options_submit(&$form, &$form_state) {
// It is very important to call the parent function here:
parent::options_submit($form, $form_state);
switch ($form_state['section']) {
case 'use_batch':
$this->set_option('use_batch', $form_state['values']['use_batch']);
break;
}
}
/**
* Determine if this view should run as a batch or not.
*/
function is_batched() {
// The source of this option may change in the future.
return ($this->get_option('use_batch') == 'batch') && empty($this->view->live_preview);
}
/**
* Add HTTP headers for the file export.
*/
function add_http_headers() {
// Ask the style plugin to add any HTTP headers if it wants.
if (method_exists($this->view->style_plugin, 'add_http_headers')) {
$this->view->style_plugin->add_http_headers();
}
}
/**
* Execute this display handler.
*
* This is the main entry point for this display. We do different things based
* on the stage in the rendering process.
*
* If we are being called for the very first time, the user has usually just
* followed a link to our view. For this phase we:
* - Register a new batched export with our parent module.
* - Build and execute the view, redirecting the output into a temporary table.
* - Set up the batch.
*
* If we are being called during batch processing we:
* - Set up our variables from the context into the display.
* - Call the rendering layer.
* - Return with the appropriate progress value for the batch.
*
* If we are being called after the batch has completed we:
* - Remove the index table.
* - Show the complete page with a download link.
* - Transfer the file if the download link was clicked.
*/
function execute() {
if (!$this->is_batched()) {
return parent::execute();
}
// Try and get a batch context if possible.
$eid = !empty($_GET['eid']) ? $_GET['eid'] :
(!empty($this->batched_execution_state->eid) ? $this->batched_execution_state->eid : FALSE);
if ($eid) {
$this->batched_execution_state = views_data_export_get($eid);
}
// First time through
if (empty($this->batched_execution_state)) {
$output = $this->execute_initial();
}
// Call me on the cached version of this view please
// This allows this view to be programatically executed with nothing
// more than the eid in $_GET in order for it to execute the next chunk
// TODO: What is going on here?
/*
Jamsilver tells me this might be useful one day.
if (!$this->views_data_export_cached_view_loaded) {
$view = views_data_export_view_retrieve($this->batched_execution_state->eid);
$view->set_display($this->view->current_display);
$view->display_handler->batched_execution_state->eid = $this->batched_execution_state->eid;
$view->display_handler->views_data_export_cached_view_loaded = TRUE;
$ret = $view->execute_display($this->view->current_display);
$this->batched_execution_state = &$view->display_handler->batched_execution_state;
return $ret;
}*/
// Last time through
if ($this->batched_execution_state->batch_state == VIEWS_DATA_EXPORT_FINISHED) {
$output = $this->execute_final();
}
// In the middle of processing
else {
$output = $this->execute_normal();
}
//Ensure any changes we made to the database sandbox are saved
views_data_export_update($this->batched_execution_state);
return $output;
}
/**
* Initializes the whole export process and starts off the batch process.
*
* Page execution will be ended at the end of this function.
*/
function execute_initial() {
// Register this export with our central table - get a unique eid
// Also store our view in a cache to be retrieved with each batch call
$this->batched_execution_state = views_data_export_new($this->view->name, $this->view->current_display, $this->outputfile_create());
views_data_export_view_store($this->batched_execution_state->eid, $this->view);
// We need to build the index right now, before we lose $_GET etc.
$this->initialize_index();
//$this->batched_execution_state->fid = $this->outputfile_create();
// Initialize the progress counter
$this->batched_execution_state->sandbox['max'] = db_query('SELECT COUNT(*) FROM {' . $this->index_tablename() . '}')->fetchField();
// Record the time we started.
list($usec, $sec) = explode(' ', microtime());
$this->batched_execution_state->sandbox['started'] = (float) $usec + (float) $sec;
// Build up our querystring for the final page callback.
$querystring = array(
'eid' => $this->batched_execution_state->eid,
);
// If we were attached to another view, grab that for the final URL.
if (!empty($_GET['attach']) && isset($this->view->display[$_GET['attach']])) {
// Get the path of the attached display:
$querystring['return-url'] = $this->view->display[$_GET['attach']]->handler->get_path();
}
//Set the batch off
$batch = array(
'operations' => array (
array('_views_data_export_batch_process', array($this->batched_execution_state->eid, $this->view->current_display)),
),
'title' => t('Building export'),
'init_message' => t('Export is starting up.'),
'progress_message' => t('Exporting @percentage% complete,'),
'error_message' => t('Export has encountered an error.'),
);
// We do not return, so update database sandbox now
views_data_export_update($this->batched_execution_state);
$final_destination = $this->view->get_url();
// Provide a way in for others at this point
// e.g. Drush to grab this batch and yet execute it in
// it's own special way
$batch['view_name'] = $this->view->name;
$batch['display_id'] = $this->view->current_display;
$batch['eid'] = $this->batched_execution_state->eid;
$batch_redirect = array($final_destination, array('query' => $querystring));
drupal_alter('views_data_export_batch', $batch, $batch_redirect);
// Modules may have cleared out $batch, indicating that we shouldn't process further.
if (!empty($batch)) {
batch_set($batch);
// batch_process exits
batch_process($batch_redirect);
}
}
/**
* Compiles the next chunk of the output file
*/
function execute_normal() {
// Pass through to our render method,
$output = $this->view->render();
// Append what was rendered to the output file.
$this->outputfile_write($output);
// Store for convenience.
$state = &$this->batched_execution_state;
$sandbox = &$state->sandbox;
// Update progress measurements & move our state forward
switch ($state->batch_state) {
case VIEWS_DATA_EXPORT_BODY:
// Remove rendered results from our index
if (count($this->view->result) && ($sandbox['weight_field_alias'])) {
$last = end($this->view->result);
db_delete($this->index_tablename())
->condition($sandbox['weight_field_alias'], $last->{$sandbox['weight_field_alias']}, '<=')
->execute();
// Update progress.
$progress = db_query('SELECT COUNT(*) FROM {' . $this->index_tablename() . '}')->fetchField();
// TODO: These next few lines are messy, clean them up.
$progress = 0.99 - ($progress / $sandbox['max'] * 0.99);
$progress = ((int)floor($progress * 100000));
$progress = $progress / 100000;
$sandbox['finished'] = $progress;
}
else {
// No more results.
$progress = 0.99;
$state->batch_state = VIEWS_DATA_EXPORT_FOOTER;
}
break;
case VIEWS_DATA_EXPORT_HEADER:
$sandbox['finished'] = 0;
$state->batch_state = VIEWS_DATA_EXPORT_BODY;
break;
case VIEWS_DATA_EXPORT_FOOTER:
$sandbox['finished'] = 1;
$state->batch_state = VIEWS_DATA_EXPORT_FINISHED;
break;
}
// Create a more helpful exporting message.
$sandbox['message'] = $this->compute_time_remaining($sandbox['started'], $sandbox['finished']);
}
/**
* Renders the final page
* We should be free of the batch at this point
*/
function execute_final() {
// Should we download the file.
if (!empty($_GET['download'])) {
// This next method will exit.
$this->transfer_file();
}
else {
// Remove the index table.
$this->remove_index();
return $this->render_complete();
}
}
/**
* Render the display.
*
* We basically just work out if we should be rendering the header, body or
* footer and call the appropriate functions on the style plugins.
*/
function render() {
if (!$this->is_batched()) {
$result = parent::render();
if (empty($this->view->live_preview)) {
$this->add_http_headers();
}
return $result;
}
$this->view->build();
switch ($this->batched_execution_state->batch_state) {
case VIEWS_DATA_EXPORT_BODY:
$output = $this->view->style_plugin->render_body();
break;
case VIEWS_DATA_EXPORT_HEADER:
$output = $this->view->style_plugin->render_header();
break;
case VIEWS_DATA_EXPORT_FOOTER:
$output = $this->view->style_plugin->render_footer();
break;
}
return $output;
}
/**
* Trick views into thinking that we have executed the query and got results.
*
* We are called in the build phase of the view, but short circuit straight to
* getting the results and making the view think it has already executed the
* query.
*/
function query() {
if (!$this->is_batched()) {
return parent::query();
}
// Make the query distinct if the option was set.
if ($this->get_option('distinct')) {
$this->view->query->set_distinct();
}
if (!empty($this->batched_execution_state->batch_state) && !empty($this->batched_execution_state->sandbox['weight_field_alias'])) {
switch ($this->batched_execution_state->batch_state) {
case VIEWS_DATA_EXPORT_BODY:
case VIEWS_DATA_EXPORT_HEADER:
case VIEWS_DATA_EXPORT_FOOTER:
// Tell views its been executed.
$this->view->executed = TRUE;
// Grab our results from the index, and push them into the view result.
// TODO: Handle external databases.
$result = db_query_range('SELECT * FROM {' . $this->index_tablename() . '} ORDER BY ' . $this->batched_execution_state->sandbox['weight_field_alias'] . ' ASC', 0, 100);
$this->view->result = array();
foreach ($result as $item_hashed) {
$item = new stdClass();
// We had to shorten some of the column names in the index, restore
// those now.
foreach ($item_hashed as $hash => $value) {
if (isset($this->batched_execution_state->sandbox['field_aliases'][$hash])) {
$item->{$this->batched_execution_state->sandbox['field_aliases'][$hash]} = $value;
}
else {
$item->{$hash} = $value;
}
}
// Push the restored $item in the views result array.
$this->view->result[] = $item;
}
$this->view->_post_execute();
break;
}
}
}
/**
* Render the 'Export Finished' page with the link to the file on it.
*/
function render_complete() {
$return_path = empty($_GET['return-url']) ? '' : $_GET['return-url'];
$query = array(
'download' => 1,
'eid' => $this->batched_execution_state->eid,
);
return theme('views_data_export_complete_page', array(
'file' => url($this->view->get_url(), array('query' => $query)),
'errors' => $this->errors,
'return_url' => $return_path));
}
/**
* TBD - What does 'preview' mean for bulk exports?
* According to doc:
* "Fully render the display for the purposes of a live preview or
* some other AJAXy reason. [views_plugin_display.inc:1877]"
*
* Not sure it makes sense for Bulk exports to be previewed in this manner?
* We need the user's full attention to run the batch. Suggestions:
* 1) Provide a link to execute the view?
* 2) Provide a link to the last file we generated??
* 3) Show a table of the first 20 results?
*/
function preview() {
if (!$this->is_batched()) {
// Can replace with return parent::preview() when views 2.12 lands.
if (!empty($this->view->live_preview)) {
// Change the items per page.
$this->view->set_items_per_page(20);
// Force a pager to be used.
$this->set_option('pager', array('type' => 'some'));
return '<p>' . t('A maximum of 20 items will be shown here, all results will be shown on export.') . '</p><pre>' . check_plain($this->view->render()) . '</pre>';
}
return $this->view->render();
}
return '';
}
/**
* Transfer the output file to the client.
*/
function transfer_file() {
// Build the view so we can set the headers.
$this->view->build();
// Arguments can cause the style to not get built.
if (!$this->view->init_style()) {
$this->view->build_info['fail'] = TRUE;
}
// Set the headers.
$this->add_http_headers();
file_transfer($this->outputfile_path(), array());
}
/**
* Called on export initialization.
*
* Modifies the view query to insert the results into a table, which we call
* the 'index', this means we essentially have a snapshot of the results,
* which we can then take time over rendering.
*
* This method is essentially all the best bits of the view::execute() method.
*/
protected function initialize_index() {
$view = &$this->view;
// Get views to build the query.
$view->build();
// Change the query object to use our custom one.
$query = new views_data_export_plugin_query_default_batched();
// Copy the query over:
foreach ($view->query as $property => $value) {
$query->$property = $value;
}
// Replace the query object.
$view->query = $query;
$view->execute();
}
/**
* Given a view, construct an map of hashed aliases to aliases.
*
* The keys of the returned array will have a maximum length of 33 characters.
*/
function field_aliases_create(&$view) {
$all_aliases = array();
foreach ($view->query->fields as $field) {
if (strlen($field['alias']) > 32) {
$all_aliases['a' . md5($field['alias'])] = $field['alias'];
}
else {
$all_aliases[$field['alias']] = $field['alias'];
}
}
return $all_aliases;
}
/**
* Create an alias for the weight field in the index.
*
* This method ensures that it isn't the same as any other alias in the
* supplied view's fields.
*/
function _weight_alias_create(&$view) {
$alias = 'vde_weight';
$all_aliases = array();
foreach ($view->query->fields as $field) {
$all_aliases[] = $field['alias'];
}
// Keep appending '_' until we are unique.
while (in_array($alias, $all_aliases)) {
$alias .= '_';
}
return $alias;
}
/**
* Remove the index.
*/
function remove_index() {
$ret = array();
if (db_table_exists($this->index_tablename())) {
db_drop_table($this->index_tablename());
}
}
/**
* Return the name of the unique table to store the index in.
*/
function index_tablename() {
return VIEWS_DATA_EXPORT_INDEX_TABLE_PREFIX . $this->batched_execution_state->eid;
}
/**
* Get the output file path.
*/
function outputfile_path() {
if (empty($this->_output_file) && !empty($this->batched_execution_state->fid)) {
// Return the filename associated with this file.
$this->_output_file = $this->file_load($this->batched_execution_state->fid);
}
return $this->_output_file->uri;
}
/**
* Called on export initialization
* Creates the output file, registers it as a temporary file with Drupal
* and returns the fid
*/
protected function outputfile_create() {
$dir = 'temporary://views_plugin_display';
// Make sure the directory exists first.
if (!file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
$this->abort_export(t('Could not create temporary directory for result export (@dir). Check permissions.', array ('@dir' => $dir)));
}
$path = drupal_tempnam($dir, 'views_data_export');
// Save the file into the DB.
$file = $this->file_save_file($path);
return $file->fid;
}
/**
* Write to the output file.
*/
protected function outputfile_write($string) {
$output_file = $this->outputfile_path();
if (file_put_contents($output_file, $string, FILE_APPEND) === FALSE) {
$this->abort_export(t('Could not write to temporary output file for result export (@file). Check permissions.', array ('@file' => $output_file)));
}
}
function abort_export($errors) {
// Just cause the next batch to do the clean-up
if (!is_array($errors)) {
$errors = array($errors);
}
foreach ($errors as $error) {
drupal_set_message($error . ' ['. t('Export Aborted') . ']', 'error');
}
$this->batched_execution_state->batch_state = VIEWS_DATA_EXPORT_FINISHED;
}
/**
* Load a file from the database.
*
* @param $fid
* A numeric file id or string containing the file path.
* @return
* A file object.
*/
function file_load($fid) {
return file_load($fid);
}
/**
* Save a file into a file node after running all the associated validators.
*
* This function is usually used to move a file from the temporary file
* directory to a permanent location. It may be used by import scripts or other
* modules that want to save an existing file into the database.
*
* @param $filepath
* The local file path of the file to be saved.
* @return
* An array containing the file information, or 0 in the event of an error.
*/
function file_save_file($filepath) {
return file_save_data('', $filepath);
}
/**
* Helper function that computes the time remaining
*/
function compute_time_remaining($started, $finished) {
list($usec, $sec) = explode(' ', microtime());
$now = (float) $usec + (float) $sec;
$diff = round(($now - $started), 0);
// So we've taken $diff seconds to get this far.
if ($finished > 0) {
$estimate_total = $diff / $finished;
$stamp = max(1, $estimate_total - $diff);
// Round up to nearest 30 seconds.
$stamp = ceil($stamp / 30) * 30;
// Set the message in the batch context.
return t('Time remaining: about @interval.', array('@interval' => format_interval($stamp)));
}
}
/**
* Checks the driver of the database underlying
* this query and returns FALSE if it is imcompatible
* with the approach taken in this display.
* Basically mysql & mysqli will be fine, pg will not
*/
function is_compatible() {
$incompatible_drivers = array (
'pgsql',
);
$db_driver = $this->_get_database_driver();
return !in_array($db_driver, $incompatible_drivers);
}
function _get_database_driver() {
$name = !empty($this->view->base_database) ? $this->view->base_database : 'default';
$conn_info = Database::getConnectionInfo($name);
return $conn_info[$name]['driver'];
}
}
class views_data_export_plugin_query_default_batched extends views_plugin_query_default {
/**
* Executes the query and fills the associated view object with according
* values.
*
* Values to set: $view->result, $view->total_rows, $view->execute_time,
* $view->current_page.
*/
function execute(&$view) {
$display_handler = &$view->display_handler;
$external = FALSE; // Whether this query will run against an external database.
$query = $view->build_info['query'];
$count_query = $view->build_info['count_query'];
$query->addMetaData('view', $view);
$count_query->addMetaData('view', $view);
if (empty($this->options['disable_sql_rewrite'])) {
$base_table_data = views_fetch_data($this->base_table);
if (isset($base_table_data['table']['base']['access query tag'])) {
$access_tag = $base_table_data['table']['base']['access query tag'];
$query->addTag($access_tag);
$count_query->addTag($access_tag);
}
}
$items = array();
if ($query) {
$additional_arguments = module_invoke_all('views_query_substitutions', $view);
// Count queries must be run through the preExecute() method.
// If not, then hook_query_node_access_alter() may munge the count by
// adding a distinct against an empty query string
// (e.g. COUNT DISTINCT(1) ...) and no pager will return.
// See pager.inc > PagerDefault::execute()
// http://api.drupal.org/api/drupal/includes--pager.inc/function/PagerDefault::execute/7
// See http://drupal.org/node/1046170.
$count_query->preExecute();
// Build the count query.
$count_query = $count_query->countQuery();
// Add additional arguments as a fake condition.
// XXX: this doesn't work... because PDO mandates that all bound arguments
// are used on the query. TODO: Find a better way to do this.
if (!empty($additional_arguments)) {
// $query->where('1 = 1', $additional_arguments);
// $count_query->where('1 = 1', $additional_arguments);
}
$start = microtime(TRUE);
if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
$this->pager->execute_count_query($count_query);
}
// Let the pager modify the query to add limits.
$this->pager->pre_execute($query);
if (!empty($this->limit) || !empty($this->offset)) {
// We can't have an offset without a limit, so provide a very large limit instead.
$limit = intval(!empty($this->limit) ? $this->limit : 999999);
$offset = intval(!empty($this->offset) ? $this->offset : 0);
$query->range($offset, $limit);
}
try {
// The $query is final and ready to go, we are going to redirect it to
// become an insert into our table, sneaky!
// Our query will look like:
// CREATE TABLE {idx} SELECT @row := @row + 1 AS weight_alias, cl.* FROM
// (-query-) AS cl, (SELECT @row := 0) AS r
// We do some magic to get the row count.
$display_handler->batched_execution_state->sandbox['weight_field_alias'] = $display_handler->_weight_alias_create($view);
$display_handler->batched_execution_state->sandbox['field_aliases'] = $display_handler->field_aliases_create($view);
$select_aliases = array();
foreach ($display_handler->batched_execution_state->sandbox['field_aliases'] as $hash => $alias) {
$select_aliases[] = "cl.$alias AS $hash";
}
// TODO: this could probably be replaced with a query extender and new query type.
$query->preExecute();
$args = $query->getArguments();
$insert_query = 'CREATE TABLE {' . $display_handler->index_tablename() . '} SELECT @row := @row + 1 AS ' . $display_handler->batched_execution_state->sandbox['weight_field_alias'] . ', ' . implode(', ', $select_aliases) . ' FROM (' . (string)$query . ') AS cl, (SELECT @row := 0) AS r';
db_query($insert_query, $args);
$view->result = array();
$this->pager->post_execute($view->result);
if ($this->pager->use_pager()) {
$view->total_rows = $this->pager->get_total_items();
}
// Now create an index for the weight field, otherwise the queries on the
// index will take a long time to execute.
db_add_unique_key($display_handler->index_tablename(), $display_handler->batched_execution_state->sandbox['weight_field_alias'], array($display_handler->batched_execution_state->sandbox['weight_field_alias']));
}
catch (Exception $e) {
$view->result = array();
debug('Exception: ' . $e->getMessage());
}
}
$view->execute_time = microtime(TRUE) - $start;
}
}
@@ -0,0 +1,361 @@
<?php
/**
* @file
* Plugin include file for export style plugin.
*/
/**
* Generalized style plugin for export plugins.
*
* @ingroup views_style_plugins
*/
class views_data_export_plugin_style_export extends views_plugin_style {
/**
* Set options fields and default values.
*
* @return
* An array of options information.
*/
function option_definition() {
$options = parent::option_definition();
$options['attach_text'] = array(
'default' => $this->definition['export feed text'],
'translatable' => TRUE,
);
$options['provide_file'] = array(
'default' => FALSE,
'translatable' => FALSE,
);
$options['filename'] = array(
'default' => $this->definition['export feed file'],
'translatable' => FALSE,
);
$options['parent_sort'] = array(
'default' => FALSE,
'translatable' => FALSE,
);
return $options;
}
/**
* Options form mini callback.
*
* @param $form
* Form array to add additional fields to.
* @param $form_state
* State of the form.
* @return
* None.
*/
function options_form(&$form, &$form_state) {
$form['attach_text'] = array(
'#type' => 'textfield',
'#title' => t('Attach text'),
'#default_value' => $this->options['attach_text'],
'#description' => t('This text is used in building the feed link. By default it is the "alt" text for the feed image.'),
);
$form['provide_file'] = array(
'#type' => 'checkbox',
'#title' => t('Provide as file'),
'#default_value' => $this->options['provide_file'],
'#description' => t('By deselecting this, the xml file will be provided as a feed instead of a file for download.'),
);
$form['filename'] = array(
'#type' => 'textfield',
'#title' => t('Filename'),
'#default_value' => $this->options['filename'],
'#description' => t('The filename that will be suggested to the browser for downloading purposes. You may include replacement patterns from the list below.'),
'#process' => array('ctools_dependent_process'),
'#dependency' => array(
'edit-style-options-provide-file' => array(TRUE),
),
);
// General token replacement.
$output = t('<p>The following substitution patterns are available for this display. Use the pattern shown on the left to display the value indicated on the right.</p>');
$items = array(
'%view == ' . t('View name'),
'%display == ' . t('Display name'),
);
$output .= theme('item_list', array('items' => $items));
// Get a list of the available arguments for token replacement.
$options = array();
$count = 0; // This lets us prepare the key as we want it printed.
foreach ($this->view->display_handler->get_handlers('argument') as $arg => $handler) {
$options[t('Arguments')]['%' . ++$count . '-title'] = t('@argument title', array('@argument' => $handler->ui_name()));
$options[t('Arguments')]['%' . $count . '-value'] = t('@argument value', array('@argument' => $handler->ui_name()));
}
// Append the list with exposed filters stuff.
$options[t('Exposed filters')]['%exposed'] = t('effective exposed filters, like <em>filter1_foo-filter2_bar</em>');
// ...and datestamp.
$time = REQUEST_TIME;
$parts = array(
'full' => 'Y-m-d\TH-i-s',
'yy' => 'y',
'yyyy' => 'Y',
'mm' => 'm',
'mmm' => 'M',
'dd' => 'd',
'ddd' => 'D',
'hh' => 'H',
'ii' => 'i',
'ss' => 's',
);
foreach ($parts as $part => $format) {
$options[t('Timestamp')]['%timestamp-' . $part] = format_date($time, 'custom', $format);
}
// We have some options, so make a list.
if (!empty($options)) {
foreach (array_keys($options) as $type) {
if (!empty($options[$type])) {
$items = array();
foreach ($options[$type] as $key => $value) {
$items[] = $key . ' == ' . $value;
}
$output .= theme('item_list', array('items' => $items, 'title' => $type));
}
}
}
$form['help'] = array(
'#type' => 'fieldset',
'#title' => t('Replacement patterns'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#value' => $output,
'#dependency' => array(
'edit-style-options-provide-file' => array(1),
),
);
$form['parent_sort'] = array(
'#type' => 'checkbox',
'#title' => t('Parent sort'),
'#default_value' => $this->options['parent_sort'],
'#description' => t('Try to apply any additional sorting from the attached display like table sorting to the exported feed.'),
);
}
/**
* Attach this view to another display as a feed.
*
* Provide basic functionality for all export style views like attaching a
* feed image link.
*/
function attach_to($display_id, $path, $title) {
$type = $this->definition['export feed type'];
$theme_pattern = array(
'views_data_export_feed_icon__' . $this->view->name . '__' . $display_id . '__' . $type,
'views_data_export_feed_icon__' . $this->view->name . '__' . $display_id,
'views_data_export_feed_icon__' . $this->view->name . '__' . $type,
'views_data_export_feed_icon__' . $display_id . '__' . $type,
'views_data_export_feed_icon__' . $display_id,
'views_data_export_feed_icon__' . $type,
'views_data_export_feed_icon',
);
$query = $this->view->get_exposed_input();
// Stash the display id we're coming form in the url so we can hijack it later.
if ($this->options['parent_sort']) {
$query['attach'] = $display_id;
}
$this->view->feed_icon .= theme($theme_pattern, array(
'image_path' => $this->definition['export feed icon'],
'url' => $this->view->get_url(NULL, $path),
'query' => $query,
'text' => $this->options['attach_text'],
)
);
}
function build_sort() {
// Bypass doing any sort of testing if parent sorting is disabled.
if (!$this->options['parent_sort']) {
return parent::build_sort();
}
$displays = $this->display->handler->get_option('displays');
// Here is later. We can get the passed argument and use it to know which
// display we can from and then do some addition processing.
// If the display exists and is attached these two tests will succeed.
if (isset($_GET['attach']) && isset($displays[$_GET['attach']]) && $displays[$_GET['attach']]) {
// Setup the second style we're going to be using to sort on.
$plugin_id = $displays[$_GET['attach']];
$parent_display = $this->view->display[$plugin_id];
$style_name = $parent_display->handler->get_option('style_plugin');
$style_options = $parent_display->handler->get_option('style_options');
$this->extra_style = views_get_plugin('style', $style_name);
$this->extra_style->init($this->view, $parent_display, $style_options);
// Call the second styles sort funciton and return the value.
return $this->extra_style->build_sort();
}
}
function build_sort_post() {
// If we found an extra style plugin earlier, pass off the build_sort_post call to it.
if (isset($this->extra_style)) {
return $this->extra_style->build_sort_post();
}
else {
return parent::build_sort_post();
}
}
/**
* Render the display in this style.
*/
function render() {
if ($this->uses_row_plugin() && empty($this->row_plugin)) {
vpr('views_plugin_style_default: Missing row plugin');
return;
}
$output = '';
$rows['header'] = $this->render_header();
$rows['body'] = $this->render_body();
$rows['footer'] = $this->render_footer();
$title = '';
$output .= theme($this->theme_functions(), array('view' => $this->view, 'options' => $this->options, 'rows' => $rows, 'title' => $title));
return $output;
}
function render_header() {
$rows = array();
$title = '';
$output = '';
$output .= theme($this->theme_functions($this->definition['additional themes base'] . '_header'), array('view' => $this->view, 'options' => $this->options, 'rows' => $rows, 'title' => $title));
return $output;
}
function render_footer() {
$rows = array();
$title = '';
$output = '';
$output .= theme($this->theme_functions($this->definition['additional themes base'] . '_footer'), array('view' => $this->view, 'options' => $this->options, 'rows' => $rows, 'title' => $title));
return $output;
}
function render_body() {
if ($this->uses_row_plugin() && empty($this->row_plugin)) {
vpr('views_plugin_style_default: Missing row plugin');
return;
}
// Group the rows according to the grouping field, if specified.
$sets = $this->render_grouping($this->view->result, $this->options['grouping']);
// Render each group separately and concatenate. Plugins may override this
// method if they wish some other way of handling grouping.
$output = '';
foreach ($sets as $title => $records) {
if ($this->uses_row_plugin()) {
$rows = array();
foreach ($records as $row_index => $row) {
$this->view->row_index = $row_index;
$rows[] = $this->row_plugin->render($row);
}
}
else {
$rows = $records;
}
$title = '';
$output .= theme($this->theme_functions($this->definition['additional themes base'] . '_body'), array('view' => $this->view, 'options' => $this->options, 'rows' => $rows, 'title' => $title));
}
unset($this->view->row_index);
return $output;
}
/**
* Provide a full list of possible theme templates used by this style.
*/
function theme_functions($hook = NULL) {
if (is_null($hook)) {
$hook = $this->definition['theme'];
}
return views_theme_functions($hook, $this->view, $this->display);
}
/**
* Add any HTTP headers that this style plugin wants to.
*/
function add_http_headers() {
$view = &$this->view;
drupal_add_http_header('Cache-Control', 'max-age=60, must-revalidate');
if (!empty($this->definition['export headers'])) {
foreach ($this->definition['export headers'] as $name => $value) {
drupal_add_http_header($name, $value);
}
}
if (isset($this->options['filename']) && !empty($this->options['provide_file'])) {
// General tokens.
$tokens = array(
'%view' => check_plain($view->name),
'%display' => check_plain($view->current_display),
);
// Argument tokens.
$count = 0;
foreach ($view->display_handler->get_handlers('argument') as $arg => $handler) {
$token = '%' . ++$count;
$tokens[$token . '-title'] = check_plain($handler->title());
$tokens[$token . '-value'] = isset($view->args[$count - 1]) ? check_plain($view->args[$count - 1]) : '';
}
// Effective exposed filters token.
$exposed = array();
foreach ($view->display_handler->get_handlers('filter') as $arg => $handler) {
if (!$handler->options['exposed']) {
continue;
}
if (!empty($view->exposed_input[$handler->options['expose']['identifier']])) {
$exposed[] = check_plain($handler->options['expose']['identifier']) . '_' . check_plain($view->exposed_input[$handler->options['expose']['identifier']]);
}
}
if (!empty($exposed)) {
$tokens['%exposed'] = implode('-', $exposed);
}
else {
$tokens['%exposed'] = 'default' ;
}
// Timestamp token.
$time = REQUEST_TIME;
$parts = array(
'full' => 'Y-m-d\TH-i-s',
'yy' => 'y',
'yyyy' => 'Y',
'mm' => 'm',
'mmm' => 'M',
'dd' => 'd',
'ddd' => 'D',
'hh' => 'H',
'ii' => 'i',
'ss' => 's',
);
foreach ($parts as $part => $format) {
$tokens['%timestamp-' . $part] = format_date($time, 'custom', $format);
}
$filename = strtr($this->options['filename'], $tokens);
if ($filename) {
drupal_add_http_header('Content-Disposition', 'attachment; filename="'. $filename .'"');
}
}
}
}
@@ -0,0 +1,115 @@
<?php
/**
* @file
* Plugin include file for export style plugin.
*/
/**
* Generalized style plugin for export plugins.
*
* @ingroup views_style_plugins
*/
class views_data_export_plugin_style_export_csv extends views_data_export_plugin_style_export {
/**
* Set options fields and default values.
*
* @return
* An array of options information.
*/
function option_definition() {
$options = parent::option_definition();
$options['separator'] = array(
'default' => ',',
'translatable' => TRUE,
);
$options['quote'] = array(
'default' => TRUE,
'translatable' => TRUE,
);
$options['trim'] = array(
'default' => FALSE,
'translatable' => FALSE,
);
$options['replace_newlines'] = array(
'default' => FALSE,
'translatable' => FALSE,
);
$options['newline_replacement'] = array(
'default' => ', ',
'translatable' => FALSE,
);
$options['header'] = array(
'default' => TRUE,
'translatable' => FALSE,
);
$options['encoding'] = array(
'default' => '',
'translatable' => FALSE,
);
return $options;
}
/**
* Options form mini callback.
*
* @param $form
* Form array to add additional fields to.
* @param $form_state
* State of the form.
* @return
* None.
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['separator'] = array(
'#type' => 'textfield',
'#title' => t('Separator'),
'#default_value' => !empty($this->options['separator']) ? $this->options['separator'] : ',',
'#description' => t('This is the separator that is used to separate fields. CSV implies comma separated fields so this should not be changed unless you have specific requirements'),
);
$form['quote'] = array(
'#type' => 'checkbox',
'#default_value' => !empty($this->options['quote']),
'#title' => t('Quote values. Useful for output that might contain your separator as part of one of the values.'),
);
$form['trim'] = array(
'#type' => 'checkbox',
'#default_value' => !empty($this->options['trim']),
'#title' => t('Trim whitespace from rendered fields. Can be useful for some themes where output results in extra newlines.'),
);
$form['replace_newlines'] = array(
'#type' => 'checkbox',
'#default_value' => !empty($this->options['replace_newlines']),
'#title' => t('Replace newlines in rendered fields.'),
);
$form['newline_replacement'] = array(
'#prefix' => '<div><div id="edit-options-newline-replacement">',
'#suffix' => '</div></div>',
'#type' => 'textfield',
'#title' => t('Replacement'),
'#default_value' => $this->options['newline_replacement'],
'#process' => array('form_process_checkboxes', 'ctools_dependent_process'),
'#dependency' => array('edit-style-options-replace-newlines' => array(TRUE)),
);
$form['header'] = array(
'#type' => 'checkbox',
'#title' => t('Make first row a list of column headers.'),
'#default_value' => !empty($this->options['header']),
);
$form['encoding'] = array(
'#type' => 'select',
'#default_value' => !empty($this->options['encoding']) ? $this->options['encoding'] : '',
'#title' => t('Character encoding conversion'),
'#options' => array (
'' => t('No conversion'),
'ASCII' => t('ASCII'),
),
'#description' => t('Optionally specify a character conversion that some CSV file readers need. Note, using an external tool is always preferred and you should only use this option as a last resort. This feature requires the "iconv" PHP extension.'),
);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* @file
* Plugin include file for export style plugin.
*/
/**
* Generalized style plugin for export plugins.
*
* @ingroup views_style_plugins
*/
class views_data_export_plugin_style_export_xml extends views_data_export_plugin_style_export {
/**
* Set options fields and default values.
*
* @return
* An array of options information.
*/
function option_definition() {
$options = parent::option_definition();
$options['transform'] = array(
'default' => TRUE,
'translatable' => FALSE,
);
$options['transform_type'] = array(
'default' => 'dash',
'translatable' => FALSE,
);
return $options;
}
/**
* Options form mini callback.
*
* @param $form
* Form array to add additional fields to.
* @param $form_state
* State of the form.
* @return
* None.
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['transform'] = array(
'#type' => 'checkbox',
'#title' => t('Transform spaces'),
'#default_value' => $this->options['transform'],
'#description' => t('Transform spaces to valid XML in field labels (spaces create invalid XML markup). Note that invalid XML tag characters will always be converted.'),
);
$form['transform_type'] = array(
'#type' => 'select',
'#title' => t('Transform type'),
'#default_value' => $this->options['transform_type'],
'#options' => array(
'dash' => t('Dash'),
'underline' => t('Underline'),
'camel' => t('camelCase'),
'pascal' => t('PascalCase'),
),
'#process' => array('ctools_dependent_process'),
'#dependency' => array(
'edit-style-options-transform' => array(TRUE),
),
);
}
}
@@ -0,0 +1,6 @@
<?php
// Print out exported items.
foreach ($themed_rows as $count => $item_row):
print implode($separator, $item_row) . "\r\n";
endforeach;
@@ -0,0 +1,5 @@
<?php
/**
* CSV files don't really have a footer.
*/
@@ -0,0 +1,6 @@
<?php
// Print out header row, if option was selected.
if ($options['header']) {
print implode($separator, $header) . "\r\n";
}
@@ -0,0 +1 @@
<?php print $tbody; ?>
@@ -0,0 +1,4 @@
</tbody>
</table>
</body>
</html>
@@ -0,0 +1,8 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<?php print $header_row; ?>
<tbody>
@@ -0,0 +1,24 @@
<?php
/**
* @file views-view-table.tpl.php
* Template to display a view as a table.
*
* - $title : The title of this group of rows. May be empty.
* - $rows: An array of row items. Each row is an array of content
* keyed by field ID.
* - $header: an array of haeaders(labels) for fields.
* - $themed_rows: a array of rows with themed fields.
* @ingroup views_templates
*/
foreach ($themed_rows as $count => $row):
foreach ($row as $field => $content):
?>
[<?php print $header[$field]; ?>]
<?php print strip_tags($content); // strip html so its plain txt. ?>
<?php endforeach; ?>
----------------------------------------
<?php endforeach;
@@ -0,0 +1,5 @@
<?php
/**
* TXT files don't really have a footer.
*/
@@ -0,0 +1,3 @@
<?php
// TXT files don't really have a footer.
@@ -0,0 +1 @@
<?php print $tbody; ?>
@@ -0,0 +1,4 @@
</tbody>
</table>
</body>
</html>
@@ -0,0 +1,8 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<?php print $header_row; ?>
<tbody>
@@ -0,0 +1,20 @@
<?php
/**
* @file views-view-table.tpl.php
* Template to display a view as a table.
*
* - $title : The title of this group of rows. May be empty.
* - $rows: An array of row items. Each row is an array of content
* keyed by field ID.
* - $header: an array of headers(labels) for fields.
* - $themed_rows: a array of rows with themed fields.
* @ingroup views_templates
*/
?>
<?php foreach ($themed_rows as $count => $row): ?>
<<?php print $item_node; ?>>
<?php foreach ($row as $field => $content): ?>
<<?php print $xml_tag[$field]; ?>><?php print $content; ?></<?php print $xml_tag[$field]; ?>>
<?php endforeach; ?>
</<?php print $item_node; ?>>
<?php endforeach; ?>
@@ -0,0 +1 @@
</<?php print $root_node; ?>>
@@ -0,0 +1,18 @@
<?php
/**
* @file views-view-table.tpl.php
* Template to display a view as a table.
*
* - $title : The title of this group of rows. May be empty.
* - $rows: An array of row items. Each row is an array of content
* keyed by field ID.
* - $header: an array of headers(labels) for fields.
* - $themed_rows: a array of rows with themed fields.
* @ingroup views_templates
*/
// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>
<<?php print $root_node; ?>>
@@ -0,0 +1,3 @@
<?php print $header ?>
<?php print $body ?>
<?php print $footer ?>
@@ -0,0 +1,480 @@
<?php
/**
* @file
* Theme related functions for processing our output style plugins.
*
* Views bug: http://drupal.org/node/593336
*/
/**
* Theme a status message
*/
function theme_views_data_export_message($var) {
$output = '';
$output .= '<div class="messages status ' . $var['type'] . '">';
$output .= $var['message'];
$output .= '</div>';
return $output;
}
/**
* Theme a feed link.
*
* This theme function uses the theme pattern system to allow it to be
* overidden in a more specific manner. The options for overiding this include
* providing per display id; per type; per display id and per type.
*
* e.g.
* For the view "export_test" with the display "page_1" and the type "csv" you
* would have the following options.
* views_data_export_feed_icon__export_test__page_1__csv
* views_data_export_feed_icon__export_test__page_1
* views_data_export_feed_icon__export_test__csv
* views_data_export_feed_icon__page_1__csv
* views_data_export_feed_icon__page_1
* views_data_export_feed_icon__csv
* views_data_export_feed_icon
*
* @ingroup themeable
*/
function theme_views_data_export_feed_icon($variables) {
extract($variables, EXTR_SKIP);
$url_options = array('html' => true);
if ($query) {
$url_options['query'] = $query;
}
$image = theme('image', array('path' => $image_path, 'alt' => $text, 'title' => $text));
return l($image, $url, $url_options);
}
/**
* Theme callback for the export complete page.
*
* @param $file
* Link to output file
*/
function theme_views_data_export_complete_page($variables) {
extract($variables, EXTR_SKIP);
drupal_set_title(t('Data export successful'));
drupal_add_html_head(array('#tag' => 'meta', '#attributes' => array('http-equiv' =>"refresh", 'content' => '3;url='. $file)), 'views_data_export_download');
$output = '';
$output .= '<p>';
$output .= t('Your export has been created. View/download the file <a href="@link">here</a> (will automatically download in 3 seconds.)', array('@link' => $file));
$output .= '</p>';
if (!empty($return_url)) {
$output .= '<p>';
$output .= l(t('Return to previous page'), $return_url);
$output .= '</p>';
}
return $output;
}
function template_preprocess_views_data_export(&$vars) {
$vars['header'] = $vars['rows']['header'];
$vars['body'] = $vars['rows']['body'];
$vars['footer'] = $vars['rows']['footer'];
$view = $vars['view'];
$fields = &$view->field;
}
function template_preprocess_views_data_export_csv_header(&$vars) {
_views_data_export_header_shared_preprocess($vars);
// Make sure we catch saved options that are misspelled. LEGACY
if (isset($vars['options']['seperator'])) {
$vars['options']['separator'] = $vars['options']['seperator'];
}
// Support old misspelled templates. LEGACY
$vars['seperator'] =
$vars['separator'] = $vars['options']['separator'];
// Special handling when quoted values are involved.
if ($vars['options']['quote']) {
$wrap = '"';
$replace_value = '""';
}
else {
$wrap = '';
$replace_value = '';
}
// Format header values.
foreach ($vars['header'] as $key => $value) {
$output = decode_entities(strip_tags($value));
if (!empty($vars['options']['trim'])) {
$output = trim($output);
}
if (!empty($vars['options']['encoding']) && function_exists('iconv')) {
switch($vars['options']['encoding']) {
case 'ASCII':
$converted = iconv("UTF-8", "ASCII//TRANSLIT", $output);
if ($converted !== FALSE) {
$output = $converted;
}
break;
}
}
$vars['header'][$key] = $wrap . str_replace('"', $replace_value, $output) . $wrap;
}
}
function template_preprocess_views_data_export_csv_body(&$vars) {
_views_data_export_body_shared_preprocess($vars);
// Make sure we catch saved options that are misspelled. LEGACY
if (isset($vars['options']['seperator'])) {
$vars['options']['separator'] = $vars['options']['seperator'];
}
// Support old misspelled templates. LEGACY
$vars['seperator'] =
$vars['separator'] = $vars['options']['separator'];
// Special handling when quoted values are involved.
if ($vars['options']['quote']) {
$wrap = '"';
$replace_value = '""';
}
else {
$wrap = '';
$replace_value = '';
}
// Format row values.
foreach ($vars['themed_rows'] as $i => $values) {
foreach ($values as $j => $value) {
$output = decode_entities(strip_tags($value));
if (!empty($vars['options']['trim'])) {
$output = trim($output);
}
if (!empty($vars['options']['encoding']) && function_exists('iconv')) {
switch($vars['options']['encoding']) {
case 'ASCII':
$converted = iconv("UTF-8", "ASCII//TRANSLIT", $output);
if ($converted !== FALSE) {
$output = $converted;
}
break;
}
}
if (!empty($vars['options']['replace_newlines'])) {
$output = str_replace("\n", $vars['options']['newline_replacement'], $output);
}
$vars['themed_rows'][$i][$j] = $wrap . str_replace('"', $replace_value, $output) . $wrap;
}
}
}
/**
* Preprocess csv output template.
*/
function template_preprocess_views_data_export_csv(&$vars) {
// TODO Replace items with themed_rows.
_views_data_export_shared_preprocess($vars);
// Make sure we catch saved options that are misspelled. LEGACY
if (isset($vars['options']['separator'])) {
$vars['options']['separator'] = $vars['options']['seperator'];
}
// Support old misspelled templates. LEGACY
$vars['seperator'] =
$vars['separator'] = $vars['options']['separator'];
// Special handling when quoted values are involved.
if ($vars['options']['quote']) {
$wrap = '"';
$replace_value = '""';
}
else {
$wrap = '';
$replace_value = '';
}
// Format header values.
foreach ($vars['header'] as $key => $value) {
$output = decode_entities(strip_tags($value));
if ($vars['options']['trim']) {
$output = trim($output);
}
if (!empty($vars['options']['encoding']) && function_exists('iconv')) {
switch($vars['options']['encoding']) {
case 'ASCII':
$converted = iconv("UTF-8", "ASCII//TRANSLIT", $output);
if ($converted !== FALSE) {
$output = $converted;
}
break;
}
}
$vars['header'][$key] = $wrap . str_replace('"', $replace_value, $output) . $wrap;
}
// Format row values.
foreach ($vars['themed_rows'] as $i => $values) {
foreach ($values as $j => $value) {
$output = decode_entities(strip_tags($value));
if ($vars['options']['trim']) {
$output = trim($output);
}
if (!empty($vars['options']['encoding']) && function_exists('iconv')) {
switch($vars['options']['encoding']) {
case 'ASCII':
$converted = iconv("UTF-8", "ASCII//TRANSLIT", $output);
if ($converted !== FALSE) {
$output = $converted;
}
break;
}
}
$vars['themed_rows'][$i][$j] = $wrap . str_replace('"', $replace_value, $output) . $wrap;
}
}
}
/**
* Preprocess txt output template.
*/
function template_preprocess_views_data_export_txt_body(&$vars) {
_views_data_export_header_shared_preprocess($vars);
_views_data_export_body_shared_preprocess($vars);
}
function template_preprocess_views_data_export_doc_body(&$vars) {
// Pass through the generic MS Office preprocess.
template_preprocess_views_data_export_msoffice_body($vars);
}
function template_preprocess_views_data_export_xls_body(&$vars) {
// Pass through the generic MS Office preprocess.
template_preprocess_views_data_export_msoffice_body($vars);
}
function template_preprocess_views_data_export_msoffice_body(&$vars) {
_views_data_export_header_shared_preprocess($vars);
_views_data_export_body_shared_preprocess($vars);
$output = '';
// Construct the tbody of a table, see theme_table().
$ts = tablesort_init($vars['header']);
$flip = array(
'even' => 'odd',
'odd' => 'even',
);
$class = 'even';
foreach ($vars['themed_rows'] as $number => $row) {
$attributes = array();
// Check if we're dealing with a simple or complex row
if (isset($row['data'])) {
foreach ($row as $key => $value) {
if ($key == 'data') {
$cells = $value;
}
else {
$attributes[$key] = $value;
}
}
}
else {
$cells = $row;
}
if (count($cells)) {
// Add odd/even class
$class = $flip[$class];
if (isset($attributes['class'])) {
$attributes['class'] .= ' ' . $class;
}
else {
$attributes['class'] = $class;
}
// Build row
$output .= ' <tr' . drupal_attributes($attributes) . '>';
$i = 0;
foreach ($cells as $cell) {
$cell = tablesort_cell($cell, $vars['header'], $ts, $i++);
$output .= _theme_table_cell($cell);
}
$output .= " </tr>\n";
}
}
$vars['tbody'] = preg_replace('/<\/?(a|span) ?.*?>/', '', $output); // strip 'a' and 'span' tags
}
function template_preprocess_views_data_export_doc_header(&$vars) {
// Pass through the generic MS Office preprocess.
template_preprocess_views_data_export_msoffice_header($vars);
}
function template_preprocess_views_data_export_xls_header(&$vars) {
// Pass through the generic MS Office preprocess.
template_preprocess_views_data_export_msoffice_header($vars);
}
function template_preprocess_views_data_export_msoffice_header(&$vars) {
_views_data_export_header_shared_preprocess($vars);
// Need to do a little work to construct the table header, see theme_table().
$vars['header_row'] = '';
$vars['header_row'] .= '<thead><tr>';
$ts = tablesort_init($vars['header']);
foreach ($vars['header'] as $cell) {
$cell = tablesort_header($cell, $vars['header'], $ts);
$vars['header_row'] .= _theme_table_cell($cell, TRUE);
}
$vars['header_row'] .= '</tr></thead>';
$vars['header_row'] = preg_replace('/<\/?(a|span) ?.*?>/', '', $vars['header_row']); // strip 'a' and 'span' tags
}
/**
* Preprocess xml output template.
*/
function template_preprocess_views_data_export_xml_header(&$vars) {
// Compute the root XML node, using the base table, and appending an 's' if needed.
$root_node = $vars['view']->base_table;
if (rtrim($root_node, 's') == $root_node) {
$root_node .= 's';
}
$vars['root_node'] = _views_data_export_xml_tag_clean($root_node);
}
/**
* Preprocess xml output template.
*/
function template_preprocess_views_data_export_xml_footer(&$vars) {
// Compute the root XML node, using the base table, and appending an 's' if needed.
$root_node = $vars['view']->base_table;
if (rtrim($root_node, 's') == $root_node) {
$root_node .= 's';
}
$vars['root_node'] = _views_data_export_xml_tag_clean($root_node);
}
/**
* Preprocess xml output template.
*/
function template_preprocess_views_data_export_xml_body(&$vars) {
_views_data_export_header_shared_preprocess($vars);
_views_data_export_body_shared_preprocess($vars);
// Compute the tag name based on the views base table, minus any trailing 's'.
$vars['item_node'] = _views_data_export_xml_tag_clean(rtrim($vars['view']->base_table, 's'));
foreach ($vars['themed_rows'] as $num => $row) {
foreach ($row as $field => $content) {
// Prevent double encoding of the ampersand. Look for the entities produced by check_plain().
$content = preg_replace('/&(?!(amp|quot|#039|lt|gt);)/', '&amp;', $content);
// Convert < and > to HTML entities.
$content = str_replace(
array('<', '>'),
array('&lt;', '&gt;'),
$content);
$vars['themed_rows'][$num][$field] = $content;
}
}
foreach ($vars['header'] as $field => $header) {
// If there is no field label, use 'no name'.
$vars['xml_tag'][$field] = !empty($header) ? $header : 'no name';
if ($vars['options']['transform']) {
switch ($vars['options']['transform_type']) {
case 'dash':
$vars['xml_tag'][$field] = str_replace(' ', '-', $header);
break;
case 'underline':
$vars['xml_tag'][$field] = str_replace(' ', '_', $header);
break;
case 'camel':
$vars['xml_tag'][$field] = str_replace(' ', '', ucwords(strtolower($header)));
// Convert the very first character of the string to lowercase.
$vars['xml_tag'][$field][0] = strtolower($vars['xml_tag'][$field][0]);
break;
case 'pascal':
$vars['xml_tag'][$field] = str_replace(' ', '', ucwords(strtolower($header)));
break;
}
}
// We should always try to output valid XML.
$vars['xml_tag'][$field] = _views_data_export_xml_tag_clean($vars['xml_tag'][$field]);
}
}
/**
* Returns a valid XML tag formed from the given input.
*
* @param $tag The string that should be made into a valid XML tag.
* @return The valid XML tag or an empty string if the string contained no valid
* XML tag characters.
*/
function _views_data_export_xml_tag_clean($tag) {
// This regex matches characters that are not valid in XML tags, and the
// unicode ones that are. We don't bother with unicode, because it would so
// the preg_replace down a lot.
static $invalid_tag_chars_regex = '#[^\:A-Za-z_\-.0-9]+#';
// These characters are not valid at the start of an XML tag:
static $invalid_start_chars = '-.0123456789';
// Convert invalid chars to '-':
$tag = preg_replace($invalid_tag_chars_regex, '-', $tag);
// Need to trim invalid characters from the start of the string:
$tag = ltrim($tag, $invalid_start_chars);
return $tag;
}
/**
* Shared helper function for export preprocess functions.
*/
function _views_data_export_header_shared_preprocess(&$vars) {
$view = $vars['view'];
$fields = &$view->field;
$vars['header'] = array();
foreach ($fields as $key => $field) {
if (empty($field->options['exclude'])) {
$vars['header'][$key] = check_plain($field->label());
}
}
}
/**
* Shared helper function for export preprocess functions.
*/
function _views_data_export_body_shared_preprocess(&$vars) {
$view = $vars['view'];
$fields = &$view->field;
$rows = $vars['rows'];
$vars['themed_rows'] = array();
$keys = array_keys($fields);
foreach ($rows as $num => $row) {
$vars['themed_rows'][$num] = array();
foreach ($keys as $id) {
if (empty($fields[$id]->options['exclude'])) {
$vars['themed_rows'][$num][$id] = $view->style_plugin->rendered_fields[$num][$id];
}
}
}
}
@@ -0,0 +1,362 @@
<?php
/**
* Implementation of hook_drush_command().
*/
function views_data_export_drush_command() {
$items = array();
$items['views-data-export'] = array (
'aliases' => array (
'vde',
),
'description' => 'Fully executes a views_data_export display of a view and writes the output to file.',
'arguments' => array (
'view_name' => 'The name of the view',
'display_id' => 'The id of the views_data_export display to execute on the view',
'output_file' => 'The file to write the results to - will be overwritten if it already exists',
),
'options' => array (
'--format' => 'csv,doc,txt,xls or xml. These options are ignored if the display_id passed is a "views_data_export" display.',
'--separator' => 'csv only: What character separates the fields (default:,)',
'--trim-whitespace' => 'csv only: Trim whitespace from either side of fields (default:1)',
'--header-row' => 'csv only: Make the first row a row of headers (default:1)',
'--quote-values' => 'csv only: Surround each field in quotes (default:1)',
),
'examples' => array (
'drush views-data-export myviewname views_data_export_1 output.csv' => 'Export myviewname:views_data_export_1 and write the output to output.csv in the current directory',
),
'drupal dependencies' => array (
'views_data_export',
),
'core' => array('7'),
);
return $items;
}
/**
* Implementation of hook_drush_help().
*
* This function is called whenever a drush user calls
* 'drush help <name-of-your-command>'
*
* @param
* A string with the help section (prepend with 'drush:')
*
* @return
* A string with the help text for your command.
*/
function views_data_export_drush_help($section) {
switch ($section) {
case 'drush:views-data-export':
return dt("This command may be used to fully execute a views_data_export display of a view, batched if need be, and write the output to a file.");
}
}
/**
* Implementation of drush_hook_COMMAND_validate().
*/
function drush_views_data_export_validate() {
// Because of a bug in the way that Drush 4 computes the name of functions to
// call from a Drush command, we may end up getting called twice, so we just
// don't do anything on subsequent invocations.
static $already_run = FALSE;
if ($already_run) {
return;
}
$already_run = TRUE;
$args = drush_get_arguments();
array_shift($args);
if (count($args) !== 3) {
return drush_set_error('ARGUMENTS_REQUIRED', dt('All arguments are required.'));
}
if (!$view = views_get_view($args[0])) {
return drush_set_error('VIEW_DOES_NOT_EXIST', dt('The view !view does not exist.', array ('!view' => $args[0])));
}
if (!$view->set_display($args[1])) {
return drush_set_error('VIEW_DOES_NOT_EXIST', dt('The view !view does not have the !display display.', array ('!view' => $args[0], '!display' => $args[1])));
}
else {
if ($view->current_display != $args[1]) {
drush_log(dt('Using different display from specified display: @display', array('@display' => $view->current_display)), 'notice');
}
drush_set_option('views_data_export_display_id', $view->current_display);
}
$format = drush_get_option('format');
$valid_formats = array('csv', 'doc', 'txt', 'xls', 'xml');
if (!empty($format) && !in_array($format, $valid_formats)) {
return drush_set_error('VIEWS_DATA_EXPORT_INVALID_OPTION', dt('The "--format" option is invalid, please supply one of the following: !formats', array('!formats' => implode(', ', $valid_formats))));
}
}
/**
* Drush command callback to export a views data to a file.
*
* @see drush_views_data_export_validate().
* @see views_data_export_views_data_export_batch_alter().
*/
function drush_views_data_export($view_name, $display_id, $output_file) {
// Because of a bug in the way that Drush 4 computes the name of functions to
// call from a Drush command, we may end up getting called twice, so we just
// don't do anything on subsequent invocations.
static $already_run = FALSE;
if ($already_run) {
return;
}
$already_run = TRUE;
// Set the display to the one that we computed earlier.
$display_id = drush_get_option('views_data_export_display_id', 'default');
$view = views_get_view($view_name);
// If the given display_id is not views_data_alter then
// we programatically clone it to a views_data_alter display
// and then execute that one instead
if ($view->display[$display_id]->display_plugin != 'views_data_export') {
//drush_log("Display '$display_id' is not views_data_export. Making one that is and executing that instead =).", 'success');
$format = drush_get_option('format');
$settings = array();
switch ($format) {
case 'doc':
case 'xls':
case 'xml':
case 'txt':
$settings['display_options']['style_plugin'] = 'views_data_export_' . $format;
break;
case 'csv':
default:
$settings['display_options']['style_plugin'] = 'views_data_export_csv';
if ($separator = drush_get_option('separator')) {
$settings['display_options']['style_options']['separator'] = $separator;
}
if (!$trim = drush_get_option('trim-whitespace')) {
$settings['display_options']['style_options']['trim'] = 0;
}
if (!$header = drush_get_option('header-row')) {
$settings['display_options']['style_options']['header'] = 0;
}
if (!$quote = drush_get_option('quote-values')) {
$settings['display_options']['style_options']['quote'] = 0;
}
// Seperator
}
$display_id = _drush_views_data_export_clone_display($view, $display_id, $settings);
}
$view->set_display($display_id);
// We execute the view normally, and take advantage
// of an alter function to interject later and batch it ourselves
$options = array (
'output_file' => realpath(drush_get_context('DRUSH_OLDCWD', getcwd())) . '/' . $output_file,
);
_drush_views_data_export_override_batch($view_name, $display_id, $options);
$view->execute_display($display_id);
}
/**
* Helper function that indicates that we want to
* override the batch that the views_data_export view creates
* on it's initial time through.
*
* Also provides a place to stash options that need to stay around
* until the end of the batch
*/
function _drush_views_data_export_override_batch($view = NULL, $display = NULL, $options = TRUE) {
static $_views;
if (isset($view)) {
$_views[$view][$display] = $options;
}
return $_views;
}
/**
* Implementation of hook_views_data_export_batch_alter()
*/
function views_data_export_views_data_export_batch_alter(&$batch, &$final_destination, &$querystring) {
// Copy the batch, because we're going to monkey with it, a lot!
$new_batch = $batch;
$view_name = $new_batch['view_name'];
$display_id = $new_batch['display_id'];
$ok_to_override = _drush_views_data_export_override_batch();
// Make sure we do nothing if we are called not following the execution of
// our drush command. This could happen if the file with this function in it
// is included during the normal execution of the view
if (!$ok_to_override[$view_name][$display_id]) {
return;
}
$options = $ok_to_override[$view_name][$display_id];
// We actually never return from the drupal_alter, but
// use drush's batch system to run the same batch
// Add a final callback
$new_batch['operations'][] = array(
'_drush_views_data_export_batch_finished', array($batch['eid'], $options['output_file']),
);
batch_set($new_batch);
$new_batch =& batch_get();
// Drush handles the different processes, so instruct BatchAPI not to.
$new_batch['progressive'] = FALSE;
// Process the batch using drush.
drush_backend_batch_process();
// Instruct the view display plugin that it shouldn't set a batch.
$batch = array();
}
/**
* Get's called at the end of the drush batch process that generated our export
*/
function _drush_views_data_export_batch_finished($eid, $output_file, &$context) {
// Fetch export info
$export = views_data_export_get($eid);
// Perform cleanup
$view = views_data_export_view_retrieve($eid);
$view->set_display($export->view_display_id);
$view->display_handler->batched_execution_state = $export;
$view->display_handler->remove_index();
// Get path to temp file
$temp_file = $view->display_handler->outputfile_path();
// Copy file over
if (@drush_op('copy', $temp_file, $output_file)) {
drush_log("Data export saved to " . $output_file, 'success');
}
else {
drush_set_error('VIEWS_DATA_EXPORT_COPY_ERROR', dt("The file could not be copied to the selected destination"));
}
}
/**
* Helper function that takes a view and returns a clone of it
* that has cloned a given display to one of type views_data_export
*
* @param &$view
* Modified to contain the new display
*
* @return
* The new display_id
*/
function _drush_views_data_export_clone_display(&$view, $display_id, $settings = array()) {
// Create the new display
$new_display_id = _drush_views_data_export_generate_display_id($view, 'views_data_export');
$view->display[$new_display_id] = clone $view->display[$display_id];
// Ensure we have settings we'll need for our display
$default_settings = array (
'id' => $new_display_id,
'display_plugin' => 'views_data_export',
'position' => 99,
'display_options' => array (
'style_plugin' => 'views_data_export_csv',
'style_options' => array(
'attach_text' => 'CSV',
'provide_file' => 1,
'filename' => 'view-%view.csv',
'parent_sort' => 1,
'separator' => ',',
'quote' => 1,
'trim' => 1,
'header' => 1,
),
'use_batch' => 'batch',
'path' => '',
'displays' => array (
'default' => 'default',
),
),
);
$settings = array_replace_recursive($default_settings, $settings);
$view->display[$new_display_id] = (object)array_replace_recursive((array)$view->display[$new_display_id], $settings);
return $new_display_id;
}
/**
* Generate a display id of a certain plugin type.
* See http://drupal.org/files/issues/348975-clone-display.patch
*
* @param $type
* Which plugin should be used for the new display id.
*/
function _drush_views_data_export_generate_display_id($view, $type) {
// 'default' is singular and is unique, so just go with 'default'
// for it. For all others, start counting.
if ($type == 'default') {
return 'default';
}
// Initial id.
$id = $type . '_1';
$count = 1;
// Loop through IDs based upon our style plugin name until
// we find one that is unused.
while (!empty($view->display[$id])) {
$id = $type . '_' . ++$count;
}
return $id;
}
/**
* If we're using PHP < 5.3.0 then we'll need
* to define this function ourselves.
* See: http://phpmyanmar.com/phpcodes/manual/function.array-replace-recursive.php
*/
if (!function_exists('array_replace_recursive')) {
function array_replace_recursive($array, $array1) {
// Get array arguments
$arrays = func_get_args();
// Define the original array
$original = array_shift($arrays);
// Loop through arrays
foreach ($arrays as $array) {
// Loop through array key/value pairs
foreach ($array as $key => $value) {
// Value is an array
if (is_array($value)) {
// Traverse the array; replace or add result to original array
$original[$key] = array_replace_recursive($original[$key], $array[$key]);
}
// Value is not an array
else {
// Replace or add current value to original array
$original[$key] = $value;
}
}
}
// Return the joined array
return $original;
}
}
@@ -0,0 +1,43 @@
name = Views Data Export
description = "Plugin to export views data into various file formats"
package = Views
core = 7.x
files[] = views_data_export.module
dependencies[] = views
; Plugins
files[] = plugins/views_data_export_plugin_display_export.inc
files[] = plugins/views_data_export_plugin_style_export.inc
files[] = plugins/views_data_export_plugin_style_export_csv.inc
files[] = plugins/views_data_export_plugin_style_export_doc.inc
files[] = plugins/views_data_export_plugin_style_export_txt.inc
files[] = plugins/views_data_export_plugin_style_export_xls.inc
files[] = plugins/views_data_export_plugin_style_export_xml.inc
; Theme
files[] = theme/views_data_export.theme.inc
files[] = theme/views-data-export-csv-body.tpl.php
files[] = theme/views-data-export-csv-footer.tpl.php
files[] = theme/views-data-export-csv-header.tpl.php
files[] = theme/views-data-export-doc-body.tpl.php
files[] = theme/views-data-export-doc-footer.tpl.php
files[] = theme/views-data-export-doc-header.tpl.php
files[] = theme/views-data-export-txt-body.tpl.php
files[] = theme/views-data-export-txt-footer.tpl.php
files[] = theme/views-data-export-txt-header.tpl.php
files[] = theme/views-data-export-xls-body.tpl.php
files[] = theme/views-data-export-xls-footer.tpl.php
files[] = theme/views-data-export-xls-header.tpl.php
files[] = theme/views-data-export-xml-body.tpl.php
files[] = theme/views-data-export-xml-footer.tpl.php
files[] = theme/views-data-export-xml-header.tpl.php
files[] = theme/views-data-export.tpl.php
; Information added by drupal.org packaging script on 2012-05-10
version = "7.x-3.0-beta6"
core = "7.x"
project = "views_data_export"
datestamp = "1336632688"
@@ -0,0 +1,145 @@
<?php
/**
* Implementation of hook_schema()
*/
function views_data_export_schema() {
$schema = array();
$schema['views_data_export'] = array(
'description' => t('Keep track of currently executing exports.'),
'fields' => array(
'eid' => array(
'description' => 'Unique id for each on-going export.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'view_name' => array(
'type' => 'varchar',
'length' => '32',
'default' => '',
'not null' => TRUE,
'description' => 'The unique name of the view. This is the primary field views are loaded from, and is used so that views may be internal and not necessarily in the database. May only be alphanumeric characters plus underscores.',
),
'view_display_id' => array(
'type' => 'varchar',
'length' => '32',
'default' => '',
'not null' => TRUE,
'description' => 'The unique name of the view. This is the primary field views are loaded from, and is used so that views may be internal and not necessarily in the database. May only be alphanumeric characters plus underscores.',
),
'time_stamp' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'The time this export started',
),
'fid' => array(
'description' => 'Files ID.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE
),
'batch_state' => array(
'type' => 'varchar',
'length' => '32',
'default' => 'init',
'not null' => TRUE,
'description' => 'The current state of the batch.',
),
'sandbox' => array(
'type' => 'blob',
'not null' => FALSE,
'size' => 'big',
'serialize' => TRUE,
),
),
'primary key' => array('eid'),
);
$schema['views_data_export_object_cache'] = array(
'description' => 'A modified version of the views_object_cache that ignores session id.',
'fields' => array(
'eid' => array(
'type' => 'varchar',
'length' => '64',
'description' => 'The export ID this view equates too.',
),
'updated' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'The time this cache was created or updated.',
),
'data' => array(
'type' => 'text',
'size' => 'big',
'description' => 'Serialized data being stored.',
'serialize' => TRUE,
),
),
'indexes' => array(
'eid' => array('eid'),
'updated' => array('updated'),
),
);
return $schema;
}
/**
* Implementation of hook_uninstall()
*/
function views_data_export_uninstall() {
// Clean up any tables we may have left around.
module_load_include('module', 'views_data_export');
views_data_export_garbage_collect(0, -1);
}
/**
* Convert the data column in the object cache.
*/
function views_data_export_update_7100() {
$new_field = array(
'type' => 'text',
'size' => 'big',
'description' => 'Serialized data being stored.',
'serialize' => TRUE,
);
// Drop and re-add this field because there is a bug in
// db_change_field that causes this to fail when trying to cast the data.
db_drop_field('views_data_export_object_cache', 'data');
db_add_field('views_data_export_object_cache', 'data', $new_field);
}
/**
* Implements hook_requirements().
*/
function views_data_export_requirements($phase) {
$requirements = array();
// Ensure translations don't break at install time
$t = get_t();
switch ($phase) {
case 'runtime':
// Check the max allowed packet size.
$max_allowed_packet = db_query('SHOW VARIABLES WHERE variable_name = :name', array(':name' => 'max_allowed_packet'))->fetchField(1);
if (is_numeric($max_allowed_packet)) {
if ($max_allowed_packet < (16 * 1024 * 1024)) {
$requirements['views_data_export'] = array(
'title' => $t('MySQL - max allowed packet'),
'value' => format_size($max_allowed_packet),
'description' => $t("Your MySQL 'max_allowed_packet' setting may be too low for Views data export to function correctly, Drupal's requirements recommend setting it to at least 16M. See: !link", array('!link' => l('http://drupal.org/requirements', 'http://drupal.org/requirements'))),
'severity' => REQUIREMENT_WARNING,
);
}
}
break;
}
return $requirements;
}
@@ -0,0 +1,273 @@
<?php
/**
* @file
* Provides the ability to export to specific
*/
define('VIEWS_DATA_EXPORT_HEADER', 'header');
define('VIEWS_DATA_EXPORT_BODY', 'body');
define('VIEWS_DATA_EXPORT_FOOTER', 'footer');
define('VIEWS_DATA_EXPORT_FINISHED', 'finished');
define('VIEWS_DATA_EXPORT_INDEX_TABLE_PREFIX', 'views_data_export_index_');
/**
* Implements hook_init().
*/
function views_data_export_init() {
// We have to include our theme preprocessors here until:
// http://drupal.org/node/1096770 is fixed.
module_load_include('inc', 'views_data_export', 'theme/views_data_export.theme');
}
/**
* Implementation of hook_views_api().
*/
function views_data_export_views_api() {
return array(
'api' => 2,
);
}
/**
* Implementation of hook_theme().
*/
function views_data_export_theme() {
// Make sure that views picks up the preprocess functions.
module_load_include('inc', 'views_data_export', 'theme/views_data_export.theme');
$hooks = array();
$hooks['views_data_export_feed_icon'] = array(
'pattern' => 'views_data_export_feed_icon__',
'variables' => array(
'image_path' => NULL,
'url' => NULL,
'query' => '',
'text' => '',
),
'file' => 'theme/views_data_export.theme.inc',
);
$hooks['views_data_export_complete_page'] = array (
'variables' => array(
'file' => '',
'errors' => array(),
'return_url'=> '',
),
'file' => 'theme/views_data_export.theme.inc',
);
$hooks['views_data_export_message'] = array (
'variables' => array(
'message' => '',
'type' => 'info',
),
'file' => 'theme/views_data_export.theme.inc',
);
return $hooks;
}
/**
* Implementation of hook_cron().
*/
function views_data_export_cron() {
views_data_export_garbage_collect();
}
/**
* Removes any temporary index tables that have been left
* behind. This is caused by batch processes which are
* started but never finished.
*
* Removes all trace of exports from the database that
* were created more than $expires seconds ago
*
* @param $expires
* Seconds ago. Defaults to that given in the settings.
* @param $chunk
* The number of tables to test for and delete.
* Defaults to that given in the settings. Pass -1
* for this setting to remove any restriction and to
* garbage collect all exports.
*/
function views_data_export_garbage_collect($expires = NULL, $chunk = NULL) {
if (!isset($expires)) {
$expires = variable_get('views_data_export_gc_expires', 604800); // one week
}
if (!isset($chunk)) {
$chunk = variable_get('views_data_export_gc_chunk', 30);
}
if ($chunk == -1) {
$result = db_query("SELECT eid FROM {views_data_export} WHERE time_stamp <= :timestamp ORDER BY time_stamp ASC", array(':timestamp' => REQUEST_TIME - $expires));
}
else {
$result = db_query_range("SELECT eid FROM {views_data_export} WHERE time_stamp <= :timestamp ORDER BY time_stamp ASC", 0, $chunk, array(':timestamp' => REQUEST_TIME - $expires));
}
$eids_to_clear = array();
foreach ($result as $row) {
$eids_to_clear[] = $row->eid;
}
// We do two things to exports we want to garbage collect
// 1. Delete the index table for it, if it is still around
// 2. Delete the row from the exports table
// 3. Delete the view from the object_cache
if (count($eids_to_clear)) {
foreach ($eids_to_clear as $eid) {
// 1. Delete index table, if it is still around for some reason
$table = VIEWS_DATA_EXPORT_INDEX_TABLE_PREFIX . $eid;
if (db_table_exists($table)) {
db_drop_table($table);
}
}
// 2. Delete the entries in the exports table.
db_delete('views_data_export')
->condition('eid', $eids_to_clear, 'IN')
->execute();
// 3. Clear the cached views
views_data_export_view_clear($eids_to_clear);
}
}
/**
* Batch API callback.
* Handles all batching operations by executing the appropriate view.
*/
function _views_data_export_batch_process($export_id, $display_id, &$context) {
// Don't show the admin menu on batch page, some people don't like it.
if (module_exists('admin_menu')) {
module_invoke('admin_menu', 'suppress');
}
// Fetch the view in question from our cache
$view = views_data_export_view_retrieve($export_id);
$view->set_display($display_id);
// Inform the data_export display which export it corresponds to and execute
if (!isset($view->display_handler->batched_execution_state)) {
$view->display_handler->batched_execution_state = new stdClass();
}
$view->display_handler->batched_execution_state->eid = $export_id;
$view->display_handler->views_data_export_cached_view_loaded = TRUE;
$view->execute_display($display_id);
// Update batch api progress information
$sandbox = $view->display_handler->batched_execution_state->sandbox;
$context['finished'] = $sandbox['finished'];
$context['message'] = $sandbox['message'];
views_data_export_view_store($export_id, $view);
}
/**********/
/** CRUD **/
/**********/
/**
* Save a new export into the database.
*/
function views_data_export_new($view_name, $view_display_id, $file) {
// Insert new row into exports table
$record = (object) array(
'view_name' => $view_name,
'view_display_id' => $view_display_id,
'time_stamp' => REQUEST_TIME,
'fid' => $file,
'batch_state' => VIEWS_DATA_EXPORT_HEADER,
'sandbox' => array(),
);
drupal_write_record('views_data_export', $record);
return $record;
}
/**
* Update an export row in the database
*/
function views_data_export_update($state) {
// Note, drupal_write_record handles serializing
// the sandbox field as per our schema definition
drupal_write_record('views_data_export', $state, 'eid');
}
/**
* Get the information about a previous export.
*/
function views_data_export_get($export_id) {
$object = db_query("SELECT * FROM {views_data_export} WHERE eid = :eid", array(':eid' => (int)$export_id))->fetch();
if ($object) {
$object->sandbox = unserialize($object->sandbox);
}
return $object;
}
/**
* Remove the information about an export.
*/
function views_data_export_clear($export_id) {
db_delete('views_data_export')
->condition('eid', $export_id)
->execute();
views_data_export_view_clear($export_id);
}
/**
* Store a view in the object cache.
*/
function views_data_export_view_store($export_id, $view) {
// Store a clean copy of the view.
$_view = $view->clone_view();
views_data_export_view_clear($export_id);
$record = array(
'eid' => $export_id,
'data' => $_view,
'updated' => REQUEST_TIME,
);
drupal_write_record('views_data_export_object_cache', $record);
}
/**
* Retrieve a view from the object cache.
*/
function views_data_export_view_retrieve($export_id) {
views_include('view');
$data = db_query("SELECT * FROM {views_data_export_object_cache} WHERE eid = :eid", array(':eid' => $export_id))->fetch();
if ($data) {
$view = unserialize($data->data);
}
return $view;
}
/**
* Clear a view from the object cache.
*
* @param $export_id
* An export ID or an array of export IDs to clear from the object cache.
*/
function views_data_export_view_clear($export_id) {
if (is_array($export_id)) {
db_delete('views_data_export_object_cache')
->condition('eid', $export_id, 'IN')
->execute();
}
else {
db_delete('views_data_export_object_cache')
->condition('eid', $export_id)
->execute();
}
}
@@ -0,0 +1,136 @@
<?php
/**
* @file
* Views include file with views hooks.
*/
/**
* Implementation of hook_views_plugins().
*/
function views_data_export_views_plugins() {
$path = drupal_get_path('module', 'views_data_export');
$style_defaults = array(
'path' => $path . '/plugins',
'parent' => 'views_data_export',
'theme' => 'views_data_export',
'theme path' => $path . '/theme',
'theme file' => 'views_data_export.theme.inc',
'uses row plugin' => FALSE,
'uses fields' => TRUE,
'uses options' => TRUE,
'type' => 'data_export',
);
return array(
'display' => array (
'views_data_export' => array(
'title' => t('Data export'),
'help' => t('Export the view results to a file. Can handle very large result sets.'),
'path' => $path . '/plugins',
'handler' => 'views_data_export_plugin_display_export',
'parent' => 'feed',
'uses hook menu' => TRUE,
'use ajax' => FALSE,
'use pager' => FALSE,
'accept attachments' => FALSE,
'admin' => t('Data export'),
'help topic' => 'display-data-export',
),
),
'style' => array(
'views_data_export' => array(
// this isn't really a display but is necessary so the file can
// be included.
'no ui' => TRUE,
'handler' => 'views_data_export_plugin_style_export',
'path' => $path . '/plugins',
'theme path' => $path . '/theme',
'theme file' => 'views_data_export.theme.inc',
'type' => 'normal',
),
'views_data_export_csv' => array(
'title' => t('CSV file'),
'help' => t('Display the view as a comma separated list.'),
'handler' => 'views_data_export_plugin_style_export_csv',
// Views Data Export element that will be used to set additional headers when serving the feed.
'export headers' => array('Content-type' => 'text/csv; charset=utf-8'),
// Views Data Export element mostly used for creating some additional classes and template names.
'export feed type' => 'csv',
'export feed text' => 'CSV',
'export feed file' => '%view.csv',
'export feed icon' => drupal_get_path('module', 'views_data_export') . '/images/csv.png',
'additional themes' => array(
'views_data_export_csv_header' => 'style',
'views_data_export_csv_body' => 'style',
'views_data_export_csv_footer' => 'style',
),
'additional themes base' => 'views_data_export_csv',
) + $style_defaults,
'views_data_export_doc' => array(
'title' => t('DOC file'),
'help' => t('Display the view as a doc file.'),
'handler' => 'views_data_export_plugin_style_export',
'export headers' => array('Content-Type' => 'application/msword'),
'export feed type' => 'doc',
'export feed text' => 'Word Document',
'export feed file' => '%view.doc',
'export feed icon' => drupal_get_path('module', 'views_data_export') . '/images/doc.png',
'additional themes' => array(
'views_data_export_doc_header' => 'style',
'views_data_export_doc_body' => 'style',
'views_data_export_doc_footer' => 'style',
),
'additional themes base' => 'views_data_export_doc',
) + $style_defaults,
'views_data_export_txt' => array(
'title' => t('TXT file'),
'help' => t('Display the view as a txt file.'),
'handler' => 'views_data_export_plugin_style_export',
'export headers' => array('Content-Type' => 'text/plain'),
'export feed type' => 'txt',
'export feed text' => 'Plain Text Document',
'export feed file' => '%view.txt',
'export feed icon' => drupal_get_path('module', 'views_data_export') . '/images/txt.png',
'additional themes' => array(
'views_data_export_txt_header' => 'style',
'views_data_export_txt_body' => 'style',
'views_data_export_txt_footer' => 'style',
),
'additional themes base' => 'views_data_export_txt',
) + $style_defaults,
'views_data_export_xls' => array(
'title' => t('XLS file'),
'help' => t('Display the view as a xls file.'),
'handler' => 'views_data_export_plugin_style_export',
'export headers' => array('Content-Type' => 'application/vnd.ms-excel'),
'export feed type' => 'xls',
'export feed text' => 'XLS',
'export feed file' => '%view.xls',
'export feed icon' => drupal_get_path('module', 'views_data_export') . '/images/xls.png',
'additional themes' => array(
'views_data_export_xls_header' => 'style',
'views_data_export_xls_body' => 'style',
'views_data_export_xls_footer' => 'style',
),
'additional themes base' => 'views_data_export_xls',
) + $style_defaults,
'views_data_export_xml' => array(
'title' => t('XML file'),
'help' => t('Display the view as a txt file.'),
'handler' => 'views_data_export_plugin_style_export_xml',
'export headers' => array('Content-Type' => 'text/xml'),
'export feed type' => 'xml',
'export feed text' => 'XML',
'export feed file' => '%view.xml',
'export feed icon' => drupal_get_path('module', 'views_data_export') . '/images/xml.png',
'additional themes' => array(
'views_data_export_xml_header' => 'style',
'views_data_export_xml_body' => 'style',
'views_data_export_xml_footer' => 'style',
),
'additional themes base' => 'views_data_export_xml',
) + $style_defaults,
),
);
}