changeset 0:0651c02e6ed7

views_calc 1.3
author Franck Deroche <franck@defr.org>
date Wed, 05 Aug 2009 18:20:29 +0200
parents
children cedf71edacf5 b0a976e17cc7
files CHANGELOG.txt LICENSE.txt theme.inc views-calc-table.tpl.php views_calc.css views_calc.info views_calc.install views_calc.module views_calc.views.inc views_calc_field_handler.inc views_calc_plugin_style_chart.inc views_calc_table.inc
diffstat 12 files changed, 1826 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CHANGELOG.txt	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,33 @@
+// $Id: CHANGELOG.txt,v 1.15 2009/05/17 11:27:42 karens Exp $
+
+Version 6.1-dev
+=================
+
+Version 6.1-3
+=================
+
+- #464568 Remove charts integration now that Charts module does it.
+
+Version 6.1-2
+=================
+
+- #442874 Don't print subtotal when there is only one page.
+- #441722 Make sure only the requested calculations are displayed.
+
+Version 6.1-1
+=================
+
+- Add option to either hide or show the detailed rows along with calculated totals.
+- #406686 Make sure tables for computed fields are not removed from the query.
+- #368221 Make sure you can do column calculations on a custom calculated field.
+- Make sure preview picks up recent, unsaved, changes in calculation options.
+- Simplify the code by making this an extension of the Views table style instead of the base style.
+- Add sub-totals for paged views that show both the page and the grand totals.
+- Add 'justification' setting to right, left, or center-justify values.
+- Change execute_display() to execute() to avoid breaking exposed filters.
+- Make sure totals are passed through field themes so they get the right formatting.
+- Add charts support to create chart out of aggregated data.
+- Add schema to install.
+- #309202 Fix substitution list.
+- Add UI to select columns to total.
+- Basic, rough upgrade to Drupal 6 and Views 2.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LICENSE.txt	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,274 @@
+GNU GENERAL PUBLIC LICENSE
+
+              Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
+Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
+verbatim copies of this license document, but changing it is not allowed.
+
+                  Preamble
+
+The licenses for most software are designed to take away your freedom to
+share and change it. By contrast, the GNU General Public License is
+intended to guarantee your freedom to share and change free software--to
+make sure the software is free for all its users. This General Public License
+applies to most of the Free Software Foundation's software and to any other
+program whose authors commit to using it. (Some other Free Software
+Foundation software is covered by the GNU Library General Public License
+instead.) You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our
+General Public Licenses are designed to make sure that you have the
+freedom to distribute copies of free software (and charge for this service if
+you wish), that you receive source code or can get it if you want it, that you
+can change the software or use pieces of it in new free programs; and that
+you know you can do these things.
+
+To protect your rights, we need to make restrictions that forbid anyone to
+deny you these rights or to ask you to surrender the rights. These restrictions
+translate to certain responsibilities for you if you distribute copies of the
+software, or if you modify it.
+
+For example, if you distribute copies of such a program, whether gratis or for
+a fee, you must give the recipients all the rights that you have. You must make
+sure that they, too, receive or can get the source code. And you must show
+them these terms so they know their rights.
+
+We protect your rights with two steps: (1) copyright the software, and (2)
+offer you this license which gives you legal permission to copy, distribute
+and/or modify the software.
+
+Also, for each author's protection and ours, we want to make certain that
+everyone understands that there is no warranty for this free software. If the
+software is modified by someone else and passed on, we want its recipients
+to know that what they have is not the original, so that any problems
+introduced by others will not reflect on the original authors' reputations.
+
+Finally, any free program is threatened constantly by software patents. We
+wish to avoid the danger that redistributors of a free program will individually
+obtain patent licenses, in effect making the program proprietary. To prevent
+this, we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+The precise terms and conditions for copying, distribution and modification
+follow.
+
+           GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
+               MODIFICATION
+
+0. This License applies to any program or other work which contains a notice
+placed by the copyright holder saying it may be distributed under the terms
+of this General Public License. The "Program", below, refers to any such
+program or work, and a "work based on the Program" means either the
+Program or any derivative work under copyright law: that is to say, a work
+containing the Program or a portion of it, either verbatim or with
+modifications and/or translated into another language. (Hereinafter, translation
+is included without limitation in the term "modification".) Each licensee is
+addressed as "you".
+
+Activities other than copying, distribution and modification are not covered
+by this License; they are outside its scope. The act of running the Program is
+not restricted, and the output from the Program is covered only if its contents
+constitute a work based on the Program (independent of having been made
+by running the Program). Whether that is true depends on what the Program
+does.
+
+1. You may copy and distribute verbatim copies of the Program's source
+code as you receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice and
+disclaimer of warranty; keep intact all the notices that refer to this License
+and to the absence of any warranty; and give any other recipients of the
+Program a copy of this License along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and you
+may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Program or any portion of it,
+thus forming a work based on the Program, and copy and distribute such
+modifications or work under the terms of Section 1 above, provided that you
+also meet all of these conditions:
+
+a) You must cause the modified files to carry prominent notices stating that
+you changed the files and the date of any change.
+
+b) You must cause any work that you distribute or publish, that in whole or in
+part contains or is derived from the Program or any part thereof, to be
+licensed as a whole at no charge to all third parties under the terms of this
+License.
+
+c) If the modified program normally reads commands interactively when run,
+you must cause it, when started running for such interactive use in the most
+ordinary way, to print or display an announcement including an appropriate
+copyright notice and a notice that there is no warranty (or else, saying that
+you provide a warranty) and that users may redistribute the program under
+these conditions, and telling the user how to view a copy of this License.
+(Exception: if the Program itself is interactive but does not normally print such
+an announcement, your work based on the Program is not required to print
+an announcement.)
+
+These requirements apply to the modified work as a whole. If identifiable
+sections of that work are not derived from the Program, and can be
+reasonably considered independent and separate works in themselves, then
+this License, and its terms, do not apply to those sections when you distribute
+them as separate works. But when you distribute the same sections as part
+of a whole which is a work based on the Program, the distribution of the
+whole must be on the terms of this License, whose permissions for other
+licensees extend to the entire whole, and thus to each and every part
+regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to
+work written entirely by you; rather, the intent is to exercise the right to
+control the distribution of derivative or collective works based on the
+Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of a
+storage or distribution medium does not bring the other work under the scope
+of this License.
+
+3. You may copy and distribute the Program (or a work based on it, under
+Section 2) in object code or executable form under the terms of Sections 1
+and 2 above provided that you also do one of the following:
+
+a) Accompany it with the complete corresponding machine-readable source
+code, which must be distributed under the terms of Sections 1 and 2 above
+on a medium customarily used for software interchange; or,
+
+b) Accompany it with a written offer, valid for at least three years, to give
+any third party, for a charge no more than your cost of physically performing
+source distribution, a complete machine-readable copy of the corresponding
+source code, to be distributed under the terms of Sections 1 and 2 above on
+a medium customarily used for software interchange; or,
+
+c) Accompany it with the information you received as to the offer to distribute
+corresponding source code. (This alternative is allowed only for
+noncommercial distribution and only if you received the program in object
+code or executable form with such an offer, in accord with Subsection b
+above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source code
+means all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation and
+installation of the executable. However, as a special exception, the source
+code distributed need not include anything that is normally distributed (in
+either source or binary form) with the major components (compiler, kernel,
+and so on) of the operating system on which the executable runs, unless that
+component itself accompanies the executable.
+
+If distribution of executable or object code is made by offering access to
+copy from a designated place, then offering equivalent access to copy the
+source code from the same place counts as distribution of the source code,
+even though third parties are not compelled to copy the source along with the
+object code.
+
+4. You may not copy, modify, sublicense, or distribute the Program except as
+expressly provided under this License. Any attempt otherwise to copy,
+modify, sublicense or distribute the Program is void, and will automatically
+terminate your rights under this License. However, parties who have received
+copies, or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+5. You are not required to accept this License, since you have not signed it.
+However, nothing else grants you permission to modify or distribute the
+Program or its derivative works. These actions are prohibited by law if you
+do not accept this License. Therefore, by modifying or distributing the
+Program (or any work based on the Program), you indicate your acceptance
+of this License to do so, and all its terms and conditions for copying,
+distributing or modifying the Program or works based on it.
+
+6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the original
+licensor to copy, distribute or modify the Program subject to these terms and
+conditions. You may not impose any further restrictions on the recipients'
+exercise of the rights granted herein. You are not responsible for enforcing
+compliance by third parties to this License.
+
+7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues), conditions
+are imposed on you (whether by court order, agreement or otherwise) that
+contradict the conditions of this License, they do not excuse you from the
+conditions of this License. If you cannot distribute so as to satisfy
+simultaneously your obligations under this License and any other pertinent
+obligations, then as a consequence you may not distribute the Program at all.
+For example, if a patent license would not permit royalty-free redistribution
+of the Program by all those who receive copies directly or indirectly through
+you, then the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply and
+the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or
+other property right claims or to contest validity of any such claims; this
+section has the sole purpose of protecting the integrity of the free software
+distribution system, which is implemented by public license practices. Many
+people have made generous contributions to the wide range of software
+distributed through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing to
+distribute software through any other system and a licensee cannot impose
+that choice.
+
+This section is intended to make thoroughly clear what is believed to be a
+consequence of the rest of this License.
+
+8. If the distribution and/or use of the Program is restricted in certain
+countries either by patents or by copyrighted interfaces, the original copyright
+holder who places the Program under this License may add an explicit
+geographical distribution limitation excluding those countries, so that
+distribution is permitted only in or among countries not thus excluded. In such
+case, this License incorporates the limitation as if written in the body of this
+License.
+
+9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will be
+similar in spirit to the present version, but may differ in detail to address new
+problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies
+a version number of this License which applies to it and "any later version",
+you have the option of following the terms and conditions either of that
+version or of any later version published by the Free Software Foundation. If
+the Program does not specify a version number of this License, you may
+choose any version ever published by the Free Software Foundation.
+
+10. If you wish to incorporate parts of the Program into other free programs
+whose distribution conditions are different, write to the author to ask for
+permission. For software which is copyrighted by the Free Software
+Foundation, write to the Free Software Foundation; we sometimes make
+exceptions for this. Our decision will be guided by the two goals of
+preserving the free status of all derivatives of our free software and of
+promoting the sharing and reuse of software generally.
+
+               NO WARRANTY
+
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE,
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT
+PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE
+STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
+WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
+PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
+NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR
+AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR
+ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
+LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
+SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OR INABILITY TO USE THE
+PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA
+OR DATA BEING RENDERED INACCURATE OR LOSSES
+SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
+PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN
+IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.
+
+          END OF TERMS AND CONDITIONS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/theme.inc	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,229 @@
+<?php
+// $Id: theme.inc,v 1.9 2009/04/23 18:32:48 karens Exp $
+
+/**
+ * @file theme.inc
+ *
+ * An array of preprocessors to fill variables for templates and helper
+ * functions to make theming easier.
+ */
+/**
+ * Theme the form for the table style plugin
+ */
+function theme_views_calc_ui_table($form) {
+  $output = drupal_render($form['description_markup']);
+
+  $header = array(
+    t('Field'),
+    t('Justification'),
+    t('Column calculations'),
+    t('Column'),
+    t('Separator'),
+    array(
+      'data' => t('Sortable'),
+      'align' => 'center',
+    ),
+    array(
+      'data' => t('Default sort'),
+      'align' => 'center',
+    ),
+  );
+  $rows = array();
+  foreach (element_children($form['columns']) as $id) {
+    $row = array();
+    $row[] = drupal_render($form['info'][$id]['name']);
+    $row[] = drupal_render($form['info'][$id]['justification']);
+    $row[] = drupal_render($form['info'][$id]['has_calc']) . drupal_render($form['info'][$id]['calc']);
+    $row[] = drupal_render($form['columns'][$id]);
+    $row[] = drupal_render($form['info'][$id]['separator']);
+    if (!empty($form['info'][$id]['sortable'])) {
+      $row[] = array(
+        'data' => drupal_render($form['info'][$id]['sortable']),
+        'align' => 'center',
+      );
+      $row[] = array(
+        'data' => drupal_render($form['default'][$id]),
+        'align' => 'center',
+      );
+    }
+    else {
+      $row[] = '';
+      $row[] = '';
+    }
+    $rows[] = $row;
+  }
+
+  // Add the special 'None' row.
+  $rows[] = array(t('None'), '', '', '', '', array('align' => 'center', 'data' => drupal_render($form['default'][-1])));
+
+  $output .= theme('table', $header, $rows);
+  $output .= drupal_render($form);
+  return $output;
+}
+
+
+/**
+ * Display a view as a table style.
+ */
+function template_preprocess_views_calc_table(&$vars) {
+  $view     = $vars['view'];
+  if (!empty($view->views_calc_calculation)) {
+    $vars['rows'] = array();
+    return;
+  }
+  
+  drupal_add_css(drupal_get_path('module', 'views_calc') .'/views_calc.css');
+  
+  // We need the raw data for this grouping, which is passed in as $vars['rows'].
+  // However, the template also needs to use for the rendered fields.  We
+  // therefore swap the raw data out to a new variable and reset $vars['rows']
+  // so that it can get rebuilt.
+  $result   = $vars['rows'];
+  $vars['rows'] = array();
+  $totals   = $view->totals;
+  $sub_totals = $view->sub_totals;
+    
+  $options  = $view->style_plugin->options;
+  $handler  = $view->style_plugin;
+  $vars['options'] = $options;
+  $hide_details = $options['detailed_values'];
+  
+  $fields   = &$view->field;
+  $columns  = $handler->sanitize_columns($options['columns'], $fields);
+
+  $active   = !empty($handler->active) ? $handler->active : '';
+  $order    = !empty($handler->order) ? $handler->order : 'asc';
+
+  $query    = tablesort_get_querystring();
+  if ($query) {
+    $query = '&' . $query;
+  }
+
+  foreach ($columns as $field => $column) {
+    // render the header labels
+    if ($field == $column && empty($fields[$field]->options['exclude'])) {
+      $label = check_plain(!empty($fields[$field]) ? $fields[$field]->label() : '');
+      if (empty($options['info'][$field]['sortable'])) {
+        $vars['header'][$field] = $label;
+      }
+      else {
+        // @todo -- make this a setting
+        $initial = 'asc';
+
+        if ($active == $field && $order == 'asc') {
+          $initial = 'desc';
+        }
+
+        $image = theme('tablesort_indicator', $initial);
+        $title = t('sort by @s', array('@s' => $label));
+        $link_options = array(
+          'html' => true,
+          'attributes' => array('title' => $title),
+          'query' => 'order=' . urlencode($field) . '&sort=' . $initial . $query,
+        );
+        $vars['header'][$field] = l($label . $image, $_GET['q'], $link_options);
+      }
+    }
+
+    // Create a second variable so we can easily find what fields we have and what the
+    // CSS classes should be.
+    $vars['fields'][$field] = views_css_safe($field);
+    if ($active == $field) {
+      $vars['fields'][$field] .= ' active';
+    }
+
+    // Render each field into its appropriate column.
+    foreach ($result as $num => $row) {
+      if (!empty($fields[$field]) && empty($fields[$field]->options['exclude'])) {
+        $field_output = $fields[$field]->theme($row);
+
+        // Don't bother with separators and stuff if the field does not show up.
+        if (!isset($field_output) && isset($vars['rows'][$num][$column])) {
+          continue;
+        }
+        
+        if ($hide_details) {
+          continue;
+        }
+
+        // Place the field into the column, along with an optional separator.
+        if (isset($vars['rows'][$num][$column])) {
+          if (!empty($options['info'][$column]['separator'])) {
+            $vars['rows'][$num][$column] .= filter_xss_admin($options['info'][$column]['separator']);
+          }
+        }
+        else {
+          $vars['rows'][$num][$column] = '';
+        }
+
+        $vars['rows'][$num][$column] .= $field_output;
+      }
+    }
+  }
+  
+  // Add totals.
+  if($view->total_rows > $view->pager['items_per_page']) {
+    $process_available = array('sub_totals', 'totals');  
+  }
+  else{
+    $process_available = array('totals');
+    $vars['sub_totals'] = array(); //if don't set, error in template
+  }
+  foreach ($process_available as $process) {
+    $vars[$process] = array();
+    $added_label = array();
+    foreach ($columns as $field => $column) {
+      $field_alias = $fields[$field]->field_alias;
+      if ($field == $column && empty($fields[$field]->options['exclude'])) {
+        foreach ($$process as $num => $row) {
+          $type = '';
+          foreach ($row as $item) {
+            if (in_array($item, array_keys(_views_calc_calc_options()))) {
+              $type = $item;
+              break;
+            }
+          }
+          if (!empty($row->$field_alias) || (isset($row->$field_alias) && $row->$field_alias === 0)) {
+    
+            // COUNT is always a numeric value, no matter what kind of field it is.
+            if ($type == 'COUNT') {
+              $vars[$process][$type][$column] =  $row->$field_alias;
+            }
+            // Calculations other than COUNT should run the value through the field's theme.
+            // This will allow dates and numeric values to apply the right formatting to the result.
+            else {
+              $vars[$process][$type][$column] =  $fields[$field]->theme($row);
+            }
+          }
+          elseif (!empty($type)) {
+            // Add the calc type label into the first empty column.
+            // Identify which is the sub total and which the grand total
+            // when both are provided.
+            if (empty($added_label[$type])) {
+              if ($process == 'sub_totals') {
+                $label = t("Page !Calculation", array("!Calculation" => $type));
+              }
+              else {
+                $label = t("Total !Calculation", array("!Calculation" => $type));
+              }
+              $vars[$process][$type][$column] = $label;
+              $added_label[$type] = TRUE;
+            }
+            else {
+              $vars[$process][$type][$column] = '';
+            }
+          }
+        }
+      }
+    }
+  }
+
+  $vars['class'] = 'views-table';
+  if (!empty($options['sticky'])) {
+    drupal_add_js('misc/tableheader.js');
+    $vars['class'] .= " sticky-enabled";
+  }
+  
+  return;
+     
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views-calc-table.tpl.php	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,65 @@
+<?php
+// $Id: views-calc-table.tpl.php,v 1.5 2009/04/21 13:09:16 karens Exp $
+/**
+ * @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.
+ * - $header: An array of header labels keyed by field id.
+ * - $fields: An array of CSS IDs to use for each field id.
+ * - $class: A class or classes to apply to the table, based on settings.
+ * - $rows: An array of row items. Each row is an array of content
+ * - $totals: An array of calculated totals. Each row contains the total for one calculation.
+ *   keyed by field ID.
+ * @ingroup views_templates
+ */
+if (empty($rows) && empty($totals)) {
+  return;
+}
+?>
+<table class="<?php print $class; ?>">
+  <?php if (!empty($title)) : ?>
+    <caption><?php print $title; ?></caption>
+  <?php endif; ?>
+  <thead>
+    <tr>
+      <?php foreach ($header as $field => $label): ?>
+        <th class="views-field views-field-<?php print $fields[$field]; ?> <?php print $options['info'][$field]['justification'] ?>">
+          <?php print $label; ?>
+        </th>
+      <?php endforeach; ?>
+    </tr>
+  </thead>
+  <tbody>
+    <?php foreach ($rows as $count => $row): ?>
+      <tr class="<?php print ($count % 2 == 0) ? 'even' : 'odd';?>">
+        <?php foreach ($row as $field => $content): ?>
+          <td class="views-field views-field-<?php print $fields[$field]; ?>  <?php print $options['info'][$field]['justification'] ?>">
+            <?php print $content; ?>
+          </td>
+        <?php endforeach; ?>
+      </tr>
+    <?php endforeach; ?>
+  </tbody>
+  <tfoot>
+    <?php foreach ($sub_totals as $type => $row): ?>
+      <tr class="view-subfooter-number">
+        <?php foreach ($row as $field => $content): ?>
+          <td class="view-subfooter views-field views-field-<?php print $fields[$field]; ?>  <?php print $options['info'][$field]['justification'] ?>">
+            <?php print $content; ?>
+          </td>
+        <?php endforeach; ?>
+      </tr>
+    <?php endforeach; ?>
+    <?php foreach ($totals as $type => $row): ?>
+      <tr class="view-footer-number">
+        <?php foreach ($row as $field => $content): ?>
+          <td class="view-footer views-field views-field-<?php print $fields[$field]; ?>  <?php print $options['info'][$field]['justification'] ?>">
+            <?php print $content; ?>
+          </td>
+        <?php endforeach; ?>
+      </tr>
+    <?php endforeach; ?>
+  </tfoot>
+  
+</table>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc.css	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,47 @@
+td.view-footer, 
+td.view-footer-number, 
+td.view-total, 
+td.view-total-number {
+  font-weight:bold;
+  background-color:#eaeaea;
+  }
+
+td.view-footer, 
+td.view-footer-number {
+  border-bottom:3px #000 double;
+  border-top:1px #000 solid;
+  }
+td.view-subfooter, 
+td.view-subfooter-number {
+  font-weight:normal;
+  background-color:#fff;
+  }
+
+td.view-subfooter, 
+td.view-subfooter-number {
+  border-bottom:1px #000 solid;
+  border-top:1px #000 solid;
+  }
+
+.views-calc-field-settings {
+  width:60%;
+  float:left;
+}
+.views-calc-field-names {
+  width:38%;
+  float:left;
+  margin-left:2%;
+  overflow:auto;
+}
+.views_calc_justify_left {
+  text-align:left;
+}
+.views_calc_justify_right {
+  text-align:right;
+}
+.views_calc_justify_center {
+  text-align:center;
+}
+.views_calc_justify_none {
+  text-align:none;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc.info	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,13 @@
+; $Id: views_calc.info,v 1.3 2008/09/15 18:11:11 karens Exp $
+name = Views Calc
+description = This module will allow you to add calculated fields to views tables and compute columns of numeric data in a views table.
+core = 6.x
+package = Views
+dependencies[] = views
+
+; Information added by drupal.org packaging script on 2009-05-17
+version = "6.x-1.3"
+core = "6.x"
+project = "views_calc"
+datestamp = "1242559869"
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc.install	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,144 @@
+<?php
+// $Id: views_calc.install,v 1.3 2008/09/16 18:03:08 karens Exp $
+/**
+ * Implementation of hook_schema().
+ */
+function views_calc_schema() {
+  $schema['views_calc_fields'] = array(
+    'fields' => array(
+      'cid' => array('type' => 'serial', 'not null' => TRUE, 'disp-width' => '10'),
+      'label' => array('type' => 'varchar', 'length' => '255', 'not null' => TRUE, 'default' => ''),
+      'format' => array('type' => 'varchar', 'length' => '255', 'not null' => TRUE, 'default' => ''),
+      'custom' => array('type' => 'varchar', 'length' => '255', 'not null' => TRUE, 'default' => ''),
+      'tablelist' => array('type' => 'text', 'not null' => TRUE),
+      'fieldlist' => array('type' => 'text', 'not null' => TRUE),
+      'calc' => array('type' => 'text', 'not null' => TRUE),
+      ),
+    'primary key' => array('cid'),
+    'indexes' => array(
+      'cid' => array('cid'))
+  );
+  return $schema;
+}
+
+function views_calc_install() {
+  drupal_install_schema('views_calc');
+}
+
+function views_calc_uninstall() {
+  db_query("DROP TABLE {views_calc_fields}");
+}
+
+/**
+ * Convert the queryname stored in the variable to the fullname
+ * so we can access both the fieldname and the tablename from
+ * the selections.
+ *
+ * Change the calc 'AVERAGE' to 'AVG' to match the db function.
+ */
+function views_calc_update_1() {
+  $ret = array();
+  include_once(drupal_get_path('module', 'views') .'/views.module');
+  include_once(drupal_get_path('module', 'views_calc') .'/views_calc.module');
+  $view_calcs = (array) variable_get('views_calc_vid','');
+  foreach ($view_calcs as $view_id) {
+    if ($view = views_get_view($view_id)) {
+      $cols = (array) variable_get('views_calc_'. $view->vid .'_col','');
+      $new_cols = array();
+      foreach ($cols as $col) {
+        foreach ($view->field as $field) {
+          if ($field['queryname'] == $col) {
+            $new_cols[] = $field['fullname'];
+          }
+        }
+      }
+      variable_set('views_calc_'. $view->vid .'_col', $new_cols);
+      $rows = (array) variable_get('views_calc_'. $view->vid. '_row','');
+      $new_rows = array();
+      foreach ($rows as $row) {
+        foreach ($view->field as $field) {
+          if ($field['queryname'] == $col) {
+            $new_rows[] = $field['fullname'];
+          }
+        }
+      }
+      variable_set('views_calc_'. $view->vid .'_row', $new_rows);
+      $col_calc   = (array) variable_get('views_calc_'.$view->vid.'_col_calc','');
+      foreach ($col_calc as $calc) {
+        if ($calc == 'AVERAGE') {
+          $new_calcs[] = 'AVG';
+        }
+        else {
+          $new_calcs[] = $calc;
+        }
+      }
+      variable_set('views_calc_'. $view->vid .'_col_calc', $new_calcs);
+      $row_calc   = (array) variable_get('views_calc_'.$view->vid.'_row_calc','');
+      foreach ($row_calc as $calc) {
+        if ($calc == 'AVERAGE') {
+          $new_calcs[] = 'AVG';
+        }
+        else {
+          $new_calcs[] = $calc;
+        }
+      }
+      variable_set('views_calc_'. $view->vid .'_row_calc', $new_calcs);
+    }
+  }
+  return $ret;
+}
+
+/**
+ * Create a table to store custom views calculation fields.
+ */
+function views_calc_update_2() {
+  $ret = array();
+  global $db_type;
+
+  switch ($db_type) {
+    case 'mysql':
+    case 'mysqli':
+      $ret[] = update_sql("CREATE TABLE if not exists {views_calc_fields} (
+        cid int(10) unsigned NOT NULL default '0',
+        label varchar(255),
+        format varchar(255),
+        custom varchar(255),
+        tablelist text,
+        fieldlist text,
+        calc text,
+        KEY (cid)
+      ) /*!40100 DEFAULT CHARACTER SET utf8 */");
+      break;
+    case 'postgres':
+      $ret[] = update_sql("CREATE TABLE if not exists {views_calc_fields} (
+        cid int(10) unsigned NOT NULL default '0',
+        label varchar(255),
+        format varchar(255),
+        custom varchar(255),
+        tablelist text,
+        fieldlist text,
+        calc text,
+        KEY (cid)
+      ) ");
+     break;
+  }
+  return $ret;
+}
+
+/**
+ * TODO
+ * Use these values to create new default views, then delete them.
+ *
+function views_calc_update_6000() {
+  $view_calcs = (array) variable_get('views_calc_vid','');
+  foreach ($view_calcs as $view_id) {
+    variable_del('views_calc_'. $view_id .'_col');
+    variable_del('views_calc_'. $view_id .'_col_calc');
+    variable_del('views_calc_'. $view_id .'_row');
+    variable_del('views_calc_'. $view_id .'_row_calc');
+  }
+  variable_del('views_calc_vid');
+  variable_del('views_calc_operators');
+  
+}
+ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc.module	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,368 @@
+<?php
+
+/**
+ * @file
+ * This module will allow you to add calculated fields to views tables
+ * and compute (SUM, COUNT, AVG, etc) columns of numeric data in a views table.
+ */
+function views_calc_views_api() {
+  return array(
+    'api' => 2,
+    'path' => drupal_get_path('module', 'views_calc'),
+  );
+}
+
+function views_calc_theme() {
+  $path = drupal_get_path('module', 'views_calc');
+  return array(
+    'views_calc_ui_table' => array(
+      'arguments' => array('form' => NULL),
+      'file' => 'theme.inc',
+    ),
+  );
+}
+
+/**
+ * Implementation of hook_help().
+ */
+function views_calc_help($section, $arg) {
+  switch ($section) {
+    case 'admin/settings/views_calc':
+    case 'admin/settings/views_calc/fields':
+      return t('<p>Set up calculation fields. Calculation fields will be displayed in the views fields list and can be added to any view.</p>');
+    case 'admin/settings/views_calc/settings':
+      return t('Put one operator on each line. To avoid the possibility of SQL injection, calculation text will only allow these values, numbers, and field names. Make sure this list includes any text other than field names that should be allowed in the calculation fields.');
+    case 'admin/help#views_calc':
+      return t('<ul> <li>Go to admin/settings/views_calc to create calculations.</li> <li>The \'Fields\' tab will allow you to create calculated fields that can be inserted into any view. The calculations can include the value of any Views field, combined with numbers, arithmatic operations, and common SQL functions like ROUND() or MIN(). Each available field has a shortcut name like %Node:Title. Create SQL snippets like (%Node:Field1 + 84600) or ROUND(%Node:Field2 / 3). </li> <li>The \'Columns\' tab allows you to set column calculations. The column totals are added in the view itself by using the style \'Views Calc Table\' and setting the fields in the table that should have column totals.</li> <li>The \'Settings\' tab allows you to add new functions to the list of allowable functions. </ul>');
+  }
+}
+
+/**
+ * Default SQL operator alternatives.
+ *
+ * The ones allowed in this system are stored in the
+ * variable views_calc_operators, and can be changed
+ * at admin/settings/views_calc.
+ *
+ */
+function _views_calc_operators() {
+  $default = array('+', '-', '*', '/', '(', ')', ',', "'", 'CONCAT', 'MIN', 'MAX', 'ROUND', 'NOW()');
+  $operators = variable_get('views_calc_operators', implode("\n", $default));
+  return explode("\n", $operators);
+
+}
+
+/**
+ *  Column calculation alternatives
+ */
+function _views_calc_calc_options() {
+  return array('COUNT' => 'Count', 'SUM' => 'Sum', 'AVG' => 'Average', 'MIN' => 'Minimum', 'MAX' => 'Maximum');
+}
+
+/**
+ *  Result format options
+ */
+function _views_calc_format_options() {
+  $options = array(
+    'none' => '',
+    'integer' => 'intval',
+    'decimal (1)' => 'number_format:1',
+    'decimal (2)' => 'number_format:2',
+    'shortdate' => 'format_date:small',
+    'mediumdate' => 'format_date',
+    'longdate' => 'format_date:large',
+    'custom' => '',
+    );
+  return $options;
+}
+
+/**
+ * Implementation of hook_perm().
+ *
+ * The permission 'administer views calc' has rights to alter the SQL
+ * operators that can be used in calculations.
+ *
+ * The permission 'create views calc' has rights to create calculated
+ * fields and set calculation columns on views.
+ */
+function views_calc_perm() {
+  return array('create views calc', 'administer views calc');
+}
+
+function views_calc_menu() {
+
+  $items = array();
+  $items['admin/settings/views_calc'] = array(
+    'title' => t('Views Calc'),
+    'description' => t('Set Views Calc fields and columns.'),
+    'type' => MENU_NORMAL_ITEM,
+    'weight' => 10,
+    'priority' => 1,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('views_calc_fields_form'),
+    'access arguments' => array('create views calc'),
+    );
+  $items['admin/settings/views_calc/fields'] = array(
+    'title' => t('Fields'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => 5,
+    'priority' => 1,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('views_calc_fields_form'),
+    'access arguments' => array('create views calc'),
+    );
+  $items['admin/settings/views_calc/settings'] = array(
+    'title' => t('Settings'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 10,
+    'priority' => 1,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('views_calc_settings_form'),
+    'access arguments' => array('administer views calc'),
+    );
+  return $items;
+}
+
+/**
+ *  Implementation of hook_settings()
+ */
+function views_calc_settings_form() {
+  drupal_set_title(t('Views Calc'));
+  $operators = _views_calc_operators();
+  $form['views_calc_operators'] = array(
+    '#type' => 'textarea',
+    '#default_value' => implode("\n", $operators),
+    '#title' => t('Allowable functions and operators'),
+    '#rows' => intval(sizeof($operators) + 2),
+    );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save'),
+    );
+  return $form;
+}
+
+function views_calc_settings_form_submit($form, &$form_state) {
+  $form_values = $form_state['values'];
+  variable_set('views_calc_operators', $form_values['views_calc_operators']);
+}
+
+/**
+ * Views Calc Fields tab on views list.
+ */
+function views_calc_fields_form() {
+  $i = 0;
+  $substitutions = _views_calc_substitutions();
+  $reverse       = array_flip($substitutions);
+
+  // display current views calcs fields
+  $fields = _views_calc_fields();
+  while ($field = db_fetch_array($fields)) {
+    $form[] = views_calc_field_form_item($i, $field, $substitutions);
+    $i++;
+  }
+  // add blank fields for more calcs
+  for ($x = $i + 1; $x < $i + 2; $x++) {
+    $field = array();
+    $form[] = views_calc_field_form_item($i, $field, $substitutions);
+  }
+  $form['#prefix'] = '<div class="views-calc-field-settings">';
+  $form['#suffix'] = '</div><div class="views-calc-field-names"><strong>Field Substitutions</strong><div class="form-item">'. theme('item_list', _views_calc_substitutions()) .'</div></div>';
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save'),
+    );
+  return $form;
+}
+
+/**
+ * A form element for an individual calculated field.
+ */
+function views_calc_field_form_item($i, $field, $substitutions) {
+  if (empty($field)) {
+    $field = array('cid' => 0, 'label' => '', 'tablelist' => '', 'calc' => '', 'format' => '', 'custom' => '');
+  }
+  $form['group'][$i] = array(
+    '#type' => 'fieldset',
+    '#tree' => TRUE,
+    '#title' => t('Field: ') . !empty($field['label']) ? $field['label'] : t('New'),
+    '#collapsible' => TRUE,
+    '#collapsed'   => FALSE,
+    );
+  $form['group'][$i]['cid'] = array(
+    '#type' => 'hidden',
+    '#value' => intval($field['cid']),
+    );
+  $form['group'][$i]['tablelist'] = array(
+    '#type' => 'hidden',
+    '#value' => $field['tablelist'],
+    );
+  $form['group'][$i]['label'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Label'),
+    '#field_prefix' => 'ViewsCalc: ',
+    '#default_value' => str_replace('ViewsCalc: ', '', $field['label']),
+    '#description' => t('The views field name for this field (i.e. Views Calc: My Calculation).'),
+    );
+  $form['group'][$i]['calc'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Calculation'),
+    '#default_value' => strtr($field['calc'], $substitutions),
+    '#description' => t('<p>The query operation to be performed, using numbers, field substitutions, and '. implode(' ', _views_calc_operators()) .'.</p>'),
+    );
+  $form['group'][$i]['format'] = array(
+    '#type' => 'select',
+    '#title' => t('Format'),
+    '#default_value' => $field['format'],
+    '#options' => drupal_map_assoc(array_keys(_views_calc_format_options())),
+    '#description' => t('The format of the result of this calculation.'),
+    );
+  $form['group'][$i]['custom'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Custom function'),
+    '#default_value' => $field['custom'],
+    '#description' => t('The function to call for a custom format.'),
+    );
+  return $form;
+}
+
+/**
+ *  Validate the views calc settings
+ */
+function views_calc_fields_form_validate($form, &$form_state) {
+  $form_values = $form_state['values'];
+  $edit = $form_values;
+  foreach ($edit as $delta => $item) {
+    if ($item['calc'] == '' || !is_numeric($delta)) {
+      // remove blank fields, don't save them
+      unset($form_values[$delta]);
+    } else {
+      // Remove all valid values from calc, if anything is left over, it is invalid.
+
+      // First, remove all field names.
+      $repl = array();
+      $patterns = array();
+      foreach (_views_calc_substitutions() as $key => $value) {
+        $key = trim($value);
+        $count = strlen($value);
+        $replace = preg_quote($value);
+        $patterns[] = "`(^|[^\\\\\\\\])". $replace ."`";
+        $repl[] = '${1}';
+      }
+      $remaining = trim(preg_replace($patterns, $repl, $item['calc']));
+      // Next, remove functions and numbers.
+      $repl = array();
+      $patterns = array();
+      foreach (_views_calc_replacements() as $value) {
+        $patterns[] = "`(^|[^\\\\\\\\])". preg_quote(trim($value)) ."`";
+        $repl[] = '${1}';
+      }
+      $remaining = trim(preg_replace($patterns, $repl, $remaining));
+      if (!empty($remaining)) {
+        form_set_error($form_values[$delta]['calc'], t('The values %remaining in %field are not allowed.', array('%remaining' => $remaining, '%field' => $item['label'])));
+      }
+    }
+  }
+}
+
+/**
+ *  Save the views calc field settings
+ */
+function views_calc_fields_form_submit($form, &$form_state) {
+  $form_values = $form_state['values'];
+  $edit = $form_values;
+  foreach ($edit as $delta => $value) {
+    if ($value['calc'] == '' || !is_numeric($delta)) {
+      // remove blank fields, don't save them
+      unset($form_values[$delta]);
+
+    } 
+    else {
+      $tables = array();
+      $form_values[$delta]['label']  = $value['label'];
+      $form_values[$delta]['format'] = $value['format'];
+      $form_values[$delta]['custom'] = $value['custom'];
+      $form_values[$delta]['calc']   = $value['calc'];
+
+      // Substitute field names back into the calculation.
+      $matches = array();
+      foreach (_views_calc_substitutions() as $key => $value) {
+        $label_patterns[] = "`(^|[^\\\\\\\\])". preg_quote($value) ."`";
+        $value_patterns[] = "`(^|[^\\\\\\\\])". preg_quote($key) ."`";
+        $repl[] = '${1}'. $key;
+      }
+      $form_values[$delta]['calc'] = preg_replace($label_patterns, $repl, $form_values[$delta]['calc']);
+
+      // Extract the fields and table names from the calculation.
+      $tables = array();
+      $fields = array();
+      foreach ($value_patterns as $pattern) {
+        if (preg_match($pattern, $form_values[$delta]['calc'], $results)) {
+          $fields[] = trim($results[0]);
+          $tmp = explode('.', trim($results[0]));
+          if (trim($tmp[0])) {
+            $tables[trim($tmp[0])] = trim($tmp[0]);
+          }
+        }
+      }
+      $form_values[$delta]['tablelist'] = implode(',', $tables);
+      $form_values[$delta]['fieldlist'] = implode(',', $fields);
+    }
+  }
+  foreach ($form_values as $delta => $value) {
+    if ($value['cid'] == 0) {
+      drupal_write_record('views_calc_fields', $value);
+    } 
+    else {
+      drupal_write_record('views_calc_fields', $value, array('cid'));
+    }
+  }
+  views_invalidate_cache();
+  drupal_set_message(t('Views Calc fields were updated.'));
+}
+
+/**
+ * Wrapper function to make sure this function will always work.
+ */
+function views_calc_views_fetch_fields($base, $type) {
+  if (!module_exists('views')) {
+    return array();
+  }
+  require_once('./'. drupal_get_path('module', 'views') .'/includes/admin.inc');
+  return views_fetch_fields($base, $type);
+}
+
+/**
+ *  Field substitutions for calculations.
+ */
+function _views_calc_substitutions($base = 'node') {
+  $fields = views_calc_views_fetch_fields($base, 'field');
+  $substitutions['node.nid'] = '%Node.nid';
+  $substitutions['node.uid'] = '%Node.uid';
+  foreach ($fields as $key => $field) {
+    // For now, omit calculated fields from available fields list.
+    // Doing caculations on calculated fields will require some
+    // complex additional logic, especially if they are nested
+    // several levels deep.
+    if (substr($key, 0, 4) != '.cid') {
+      $substitutions[$key] = '%'. str_replace(' ', '', $key);
+    }
+  }
+  return $substitutions;
+}
+
+/**
+ *  Views calc fields result object
+ */
+function _views_calc_fields() {
+  return db_query("SELECT * FROM {views_calc_fields}");
+}
+
+/**
+ *  An array of allowable calculation values.
+ */
+function _views_calc_replacements() {
+  $operators     = array_filter(_views_calc_operators(), 'trim');
+  $numbers       = range(0, 9);
+  return array_merge($operators, $numbers);
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc.views.inc	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,78 @@
+<?php
+// $Id: views_calc.views.inc,v 1.7 2009/05/17 11:11:17 karens Exp $
+/**
+ * Implementation of hook_views_handlers().
+ */
+function views_calc_views_handlers() {
+  return array(
+    'info' => array(
+      'path' => drupal_get_path('module', 'views_calc'),
+    ),
+    'handlers' => array(
+      'views_calc_field_handler' => array(
+        'parent' => 'views_handler_field',
+      ),
+    ),
+  );
+}
+
+/**
+ *  Implementation of hook_views_data().
+ *
+ *  Add calc fields to views field list.
+ */
+function views_calc_views_data() {
+  $data = array();
+  $results = _views_calc_fields();
+  while($field = db_fetch_array($results)) {
+    $data['node']['cid'. $field['cid']] = array(
+      'group' => t('Views Calc'),
+      'title' => t($field['label']),
+      'help' =>  $field['calc'],
+      'field' => array(
+        'field' => 'cid'. $field['cid'],
+        'table' => 'node',
+        'handler' => 'views_calc_field_handler',
+        'click sortable' => TRUE,
+        'allow empty' => TRUE,
+        'cid'     => $field['cid'],
+        'format'  => $field['format'],
+        'custom'  => $field['custom'],
+        'calc'  => $field['calc'],
+      ),
+    );
+  }
+  return $data;
+}
+
+/**
+ * Implementation of hook_views_plugins
+ */
+function views_calc_views_plugins() {
+  $path = drupal_get_path('module', 'views_calc');
+  $views_path = drupal_get_path('module', 'views');
+  require_once "./$path/theme.inc";
+
+  $data = array(
+    'module' => 'views_calc', // This just tells our themes are elsewhere.
+    'style' => array(
+      // Style plugin for the navigation.
+      'views_calc' => array(
+        'title' => t('Views Calc Table'),
+        'help' => t('Creates a table with column calculations.'),
+        'handler' => 'views_calc_table',
+        'path' => $path,
+        'parent' => 'table',
+        'theme' => 'views_calc_table',
+        'theme file' => 'theme.inc',
+        'theme path' => "$path",
+        'uses row plugin' => FALSE,
+        'uses fields' => TRUE,
+        'uses options' => TRUE,
+        'type' => 'normal',
+        'even empty' => FALSE,
+      ),
+    )
+  );
+  return $data;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc_field_handler.inc	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,103 @@
+<?php
+// $Id: views_calc_field_handler.inc,v 1.3 2009/04/21 12:15:28 karens Exp $
+/**
+ * @file
+ * Copied from the basic 'node' field handler.
+ */
+
+/**
+ * Field handler to provide simple renderer that allows linking to a node.
+ */
+class views_calc_field_handler extends views_handler_field {
+  /**
+   * Constructor to provide additional field to add.
+   */
+  function construct() {
+    parent::construct();
+    $this->additional_fields['nid'] = 'nid';
+  }
+
+  function option_definition() {
+    $options = parent::option_definition();
+    $options['link_to_node'] = array('default' => FALSE);
+    return $options;
+  }
+
+  /**
+   * Provide link to node option
+   */
+  function options_form(&$form, &$form_state) {
+    parent::options_form($form, $form_state);
+    $form['link_to_node'] = array(
+      '#title' => t('Link this field to its node'),
+      '#type' => 'checkbox',
+      '#default_value' => !empty($this->options['link_to_node']),
+    );
+  }
+
+  /**
+   * Render whatever the data is as a link to the node.
+   *
+   * Data should be made XSS safe prior to calling this function.
+   */
+  function render_link($data, $values) {
+    if (!empty($this->options['link_to_node'])) {
+      return l($data, "node/" . $values->{$this->aliases['nid']}, array('html' => TRUE));
+    }
+    else {
+      return $data;
+    }
+  }
+
+  /**
+   * Find the right calculation and add it to the query as
+   * an aliased field.
+   */
+  function query() {
+    $results = _views_calc_fields();
+    while ($calc_field = db_fetch_array($results)) {
+      if ($this->definition['cid'] == $calc_field['cid']) {
+        foreach (explode(',', $calc_field['tablelist']) as $table) {
+          $this->view->query->add_table($table);
+        }
+        $this->view->query->add_field(NULL, "({$calc_field['calc']})", "cid". $calc_field['cid']);
+        return;
+      }
+    }    
+  }
+  
+  function pre_query() {
+    $this->field_alias = "cid{$this->definition['cid']}";
+    parent::pre_query();
+  }
+  
+  /**
+   * Use the requested format function to render the raw alias value.
+   */
+  function render($values) {
+    $field_alias = "cid{$this->definition['cid']}";
+    
+    $value = $values->$field_alias;
+    $formats = _views_calc_format_options();
+    $format = $formats[$this->definition['format']];
+    $tmp = explode(':', $format);
+    $function = trim($tmp[0]);
+    $vars     = count($tmp) == 2 ? $tmp[1] : '';
+    if ($function == 'custom') {
+      $tmp = explode(':', $this->definition['custom']);
+      $function = trim($tmp[0]);
+      $vars     = count($tmp) == 2 ? $tmp[1] : '';
+    }
+    if (empty($function) || $function == 'none') {
+      $function = 'check_plain';
+    }
+    $raw = $function($value, $vars);
+
+    // This needs to be set for the $this->render_link() to work. It would
+    // have been set in the query, if we hadn't bypassed the normal query.
+    // TODO there may be a better way to do this.
+    $this->aliases['nid'] = 'nid';
+
+    return $this->render_link($raw, $values);
+  }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc_plugin_style_chart.inc	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,228 @@
+<?php
+// $Id: views_calc_plugin_style_chart.inc,v 1.7 2009/04/20 19:38:42 karens Exp $
+
+/**
+ * @file
+ * Contains the chart style plugin.
+ */
+
+/**
+ * Style plugin to render view as a chart.
+ *
+ * @ingroup views_style_plugins
+ */
+class views_calc_plugin_style_chart extends views_plugin_style {
+  // Set default options.
+  function options(&$options) {
+    $options['format'] = 'pie2D';
+    $options['height'] = 200;
+    $options['width'] = 400;
+    $options['color'] = 'ffffff';
+    $options['aggregation_field'] = '';
+    $options['calc_fields'] = array();
+    $options['calc'] = 'COUNT';
+    $options['precision'] = 2;
+  }
+
+  // Generate a form for setting options.
+  function options_form(&$form, &$form_state) {
+    parent::options_form($form, $form_state);
+    
+    $form['format'] = array(
+      '#type'    => 'select',
+      '#title'   => t('Chart format'),
+      '#options' => array(
+        'line2D'  => t('Line 2D'),
+        'hbar2D'  => t('Horizontal Bar 2D'),
+        'vbar2D'  => t('Vertical Bar 2D'),
+        'pie2D'   => t('Pie 2D'),
+        'pie3D'   => t('Pie 3D'),
+        'venn'    => t('Venn'),
+        'scatter' => t('Scatter Plot')
+      ),
+      '#default_value' => $this->options['format'],
+    );
+    $form['height'] = array(
+      '#type'          => 'textfield',
+      '#title'         => t('Chart height'),
+      '#default_value' => $this->options['height'],
+      '#required'      => TRUE, // Google charts breaks if it is empty.
+      '#description'   => t('An integer value, the number of pixels of height for this chart.'),
+    );
+    $form['width'] = array(
+      '#type'          => 'textfield',
+      '#title'         => t('Chart width'),
+      '#default_value' => $this->options['width'],
+      '#required'      => TRUE, // Google charts breaks if it is empty.
+      '#description'   => t('An integer value, the number of pixels of width for this chart.'),
+    );
+    $form['color'] = array(
+      '#type'          => 'textfield',
+      '#title'         => t('Background color'),
+      '#default_value' => $this->options['color'],
+      '#description'   => t('In hexadecimal format (RRGGBB). Do not use the # symbol.'),
+      '#required'      => TRUE, // Google charts breaks if it is empty.
+    );
+    $form['show_legend'] = array(
+      '#type'          => 'checkbox',
+      '#title'         => t('Show legend'),
+      '#default_value' => $this->options['show_legend'],
+      '#description'   => t('Display legend next to the chart.'),
+    );
+      
+    $form['aggregation_field'] = array(
+      '#type' => 'select',
+      '#title' => t('Aggregation field'),
+      '#options' => $this->aggregated_field_options(),
+      '#default_value' => $this->options['aggregation_field'],
+      '#description' => t('Select a field to aggreagate the results on.')
+      );
+    // TODO Charts module cannot currently handle more than one series, 
+    // update Multiple to TRUE if that changes.
+    $form['calc_fields'] = array(
+      '#type' => 'select',
+      '#title' => t('Computation field'),
+      '#options' => $this->aggregated_field_options(),
+      '#default_value' => $this->calc_fields(),
+      '#multiple' => FALSE, 
+      '#description' => t('Select field to perform computations on.')
+      );
+    $form['calc'] = array(
+      '#type' => 'select',
+      '#title' => t('Computation to perform'),
+      '#options' => $this->calc_options(),
+      '#default_value' => $this->options['calc'],
+      );
+    $form['precision'] = array(
+      '#type' => 'select',
+      '#title' => t('Precision'),
+      '#options' => range(0, 4),
+      '#default_value' => $this->options['precision'],
+      '#description' => t('Decimal points to use in computed values.'),
+      );   
+  }
+
+  function calc_options() {
+    return array(
+      '' => t('None'), 
+      'SUM' => t('Sum'), 
+      'COUNT' => t('Count'), 
+      'AVG' => t('Average'), 
+      'MIN' => t('Minimum'), 
+      'MAX' => t('Maximum'),
+      );
+  }
+
+  /**
+   * Create an options array of available fields from this view.
+   */
+  function aggregated_field_options() {
+    $field_names = array();
+    $handlers = $this->display->handler->get_handlers('field');
+    foreach ($handlers as $field => $handler) {
+      if ($label = $handler->label()) {
+        $field_names[$field] = $label;
+      }
+      else {
+        $field_names[$field] = $handler->ui_name();
+      }
+    }
+    return $field_names;    
+  }
+  
+  /**
+   * Make sure calc_fields is always an array, even when not multiple.
+   */
+  function calc_fields() {
+    $calc_fields = (array) $this->options['calc_fields'];
+    return array_values($calc_fields);
+  }
+  
+  // Define and display a chart from the grouped values.
+  function render() {
+    // Scan all Views data and insert them into a series.
+    $data = array();
+    
+    // Get values from rows.
+    foreach ($this->calc_fields() as $calc) {
+      foreach ($this->view->result as $row) {
+        foreach ($this->view->field as $key => $field) {
+          if ($key == $this->options['aggregation_field']) {
+            $legend_field = array_key_exists($calc, $this->view->field) ? $this->view->field[$calc] : NULL;
+            $legend = !empty($legend_field->options['label']) ? $legend_field->options['label'] : NULL;
+            if ($this->options['show_legend']) {
+              $data[$calc]['#legend'] = $legend;
+            }
+            $value['#label'] = strip_tags(theme_views_view_field($this->view, $this->view->field[$key], $row)); // .': '. $row->$calc;
+            $value['#value'] = $row->$calc;
+            $data[$calc][] = $value;
+          }
+        }
+      }
+    }
+      
+    // Get chart settings from options form.
+    $legend_field = $this->view->field[$this->options['aggregation_field']];
+    $chart = array(
+      '#type'   => $this->options['format'],
+      '#height' => $this->options['height'],
+      '#width'  => $this->options['width'],
+      '#color'  => $this->options['color'],
+    );
+
+    // Use the view title as the chart title.
+    $chart['#title'] = $this->view->get_title();
+    
+    // Insert series into the chart array.
+    foreach ($data as $series) {
+      $chart[] = $series;
+    }
+    
+    // Print the chart.
+    return charts_chart($chart);
+  }
+  
+  function query() {
+    parent::query();
+        
+    // Clear the fields out, we'll replace them with calculated values.
+    $this->view->query->clear_fields();
+    // Clear out any sorting, it can create unexpected results
+    // when Views adds aggregation values for the sorts.
+    $this->view->query->orderby = array();
+    
+    // Add the grouping information to the query.
+    // Field setting of array('aggregate' => TRUE) tells Views not to force 
+    // another aggregation in for this field.
+            
+    foreach ($this->view->field as $field) {
+      $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table .'.'. $field->field;
+      $query_alias = $field->field_alias;
+      
+      // Add the aggregation.
+      if ($field->field == $this->options['aggregation_field']) {
+        $this->view->query->add_orderby(NULL, NULL, 'asc', $query_alias);
+        $this->view->query->add_groupby($query_field);
+        if (substr($field->field, 0, 3) == 'cid') {
+          $this->view->query->add_field(NULL, $query_field, $field->field, array('aggregate' => TRUE));
+        }
+        else {
+          $this->view->query->add_field($field->table, $field->field, NULL, array('aggregate' => TRUE));
+        }
+      }
+      // Add computed values.
+      if (in_array($field->field, $this->calc_fields())) {
+        $sql = "ROUND(". $this->options['calc'] ."($query_field), ". $this->options['precision'] .")";
+        $this->view->query->add_field(NULL, $sql, $field->field, array('aggregate' => TRUE));
+        
+        // TODO This part is not relationship-safe, needs additional work
+        // to join in the right table if the computation is done
+        // on a field that comes from a relationship.
+        
+        // Make sure the table with the right alias name is available 
+        // (it might have been dropped during Views optimizations.)
+        $this->view->query->add_table($field->table);
+      }
+    }
+  }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views_calc_table.inc	Wed Aug 05 18:20:29 2009 +0200
@@ -0,0 +1,244 @@
+<?php
+// $Id: views_calc_table.inc,v 1.15 2009/04/22 02:21:41 karens Exp $
+/**
+ * @file
+ * Copied from the table style plugin.
+ */
+
+/**
+ * Style plugin to render each item as a row in a table.
+ *
+ * @ingroup views_style_plugins
+ */
+class views_calc_table extends views_plugin_style_table {
+ 
+  function option_definition() {
+    $options = parent::option_definition();
+
+    $options['detailed_values'] = array('default' => 0);
+    return $options;
+  }
+   
+  /**
+   * Render the given style.
+   */
+  function options_form(&$form, &$form_state) {
+    parent::options_form($form, $form_state);
+    $form['#theme'] = 'views_calc_ui_table';
+
+    $form['detailed_values'] = array(
+      '#title' => t('Show details'),
+      '#type' => 'select',
+      '#options' => array(0 => t('Yes'), 1 => t('No')),
+      '#default_value' => $this->options['detailed_values'],
+      '#description' => t("Select 'Yes' to show detailed values followed by column calculations, 'No' to surpress details and show only calculated column totals."),
+    );
+    
+    $handlers = $this->display->handler->get_handlers('field');
+    $columns = $this->sanitize_columns($this->options['columns']);
+        
+    foreach ($columns as $field => $column) {
+      $safe = str_replace(array('][', '_', ' '), '-', $field);
+      $id = 'edit-style-options-columns-' . $safe;
+      $form['info'][$field]['justification'] = array(
+        '#type' => 'select',
+        '#default_value' => isset($this->options['info'][$field]['justification']) ? $this->options['info'][$field]['justification'] : 'views_calc_justify_none',
+        '#options' => array(
+          'views_calc_justify_none' => t('None'), 
+          'views_calc_justify_left' => t('Left'), 
+          'views_calc_justify_right' => t('Right'), 
+          'views_calc_justify_center' => t('Center'),
+          ),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array($id => array($field)),
+      );
+      $form['info'][$field]['has_calc'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Display calculation'),
+        '#default_value' => isset($this->options['info'][$field]['has_calc']) ? $this->options['info'][$field]['has_calc'] : 0,
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array($id => array($field)),
+      );
+      
+      $options = _views_calc_calc_options();
+      $form['info'][$field]['calc'] = array(
+        '#type' => 'select',
+        '#options' => $options,
+        '#default_value' => isset($this->options['info'][$field]['calc']) ? $this->options['info'][$field]['calc'] : array(),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array('edit-style-options-info-'. $safe .'-has-calc' => array(TRUE)),
+        '#multiple' => TRUE,
+      );
+    }
+  }
+
+  /**
+   * TODO
+   * figure out what changes are needed so Views field groups will work.
+   */
+  function pre_render($results) {
+    parent::pre_render($results);
+       
+    // If there are no calc fields, do nothing.
+    if (!$calc_fields = $this->get_calc_fields()) {
+      return;
+    }
+    // If we're not getting a summary row, do nothing.
+    if (!empty($this->view->views_calc_calculation)) {
+      return;
+    }
+   
+    $this->view->totals = array();
+    $this->view->sub_totals = array();
+      
+    // Subtotals and pager totals require a list of the specific
+    // values to include.
+    $paged = FALSE;
+    if (!empty($this->view->pager) 
+    && !empty($this->view->pager['use_pager']) 
+    && !empty($this->view->pager['items_per_page'])) {
+      $nids = array();
+      foreach ($this->view->result as $delta => $value) {
+        $nids[] = $value->nid;
+      }
+      // Add sub_total rows to the results.
+      foreach ($calc_fields as $calc => $field) {
+        if ($summary_view = views_get_view($this->view->name)) {
+          $summary_view->set_display($this->view->current_display);
+          $summary_view->set_arguments($this->view->args);
+          $summary_view->views_calc_calculation = $calc;
+          $summary_view->views_calc_nids = $nids;
+          $summary_view->views_calc_sub_total = TRUE;
+          $summary_view->is_cacheable = FALSE;
+          $summary_view->execute();
+          $this->view->sub_totals[] = array_shift($summary_view->result);
+        }
+      }
+    }
+    
+    // Add grand totals to the results.
+    foreach ($calc_fields as $calc => $field) {
+      if ($summary_view = views_get_view($this->view->name)) {
+        $summary_view->set_display($this->view->current_display);
+        $summary_view->set_arguments($this->view->args);
+        $summary_view->pager['items_per_page'] = 0;
+        $summary_view->views_calc_calculation = $calc;
+        $summary_view->views_calc_nids = array();
+        $summary_view->views_calc_sub_total = FALSE;
+        $summary_view->is_cacheable = FALSE;
+        $summary_view->execute();
+        $this->view->totals[] = array_shift($summary_view->result);
+      }
+    }
+  }
+
+  function query() {
+    parent::query();
+    
+    // If we're not getting a summary row, do nothing.
+    if (empty($this->view->views_calc_calculation)) {
+      return;
+    }
+    // If there are no calc fields, do nothing.
+    if (!$calc_fields = $this->get_calc_fields()) {
+      return;
+    }
+
+    if (!empty($this->view->views_calc_sub_total)) {
+      $this->query_sub_total();
+    }
+    else {
+      $this->query_total();
+    }
+  }
+  
+  /**
+   * 
+   */
+  function query_sub_total() {
+    // Create summary rows.
+    $calc_fields = $this->get_calc_fields();
+    $calc = $this->view->views_calc_calculation;
+    $fields = $calc_fields[$calc];
+    
+    // Empty out any fields that have been added to the query,
+    // we don't need them for the summary totals.
+    $this->view->query->fields = array();
+    foreach ($this->view->field as $field) {
+      $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table .'.'. $field->field;
+      $query_alias = $field->field_alias;
+      if (in_array($field->field, $fields)) {
+        // Calculated fields.
+        $this->view->query->add_field(NULL, "$calc($query_field)", $query_alias);
+        $this->view->query->add_table($field->table, NULL, NULL, $field->table);
+      }
+      else {
+        // Empty fields that have no calculations.
+        $this->view->query->add_field(NULL, "MAX('')", $query_alias);
+      }
+      // Add a dummy field for the groupby.
+      $this->view->query->add_field(NULL, "MAX('". $calc ."')", "TOTAL_". $calc);
+    }
+    // TODO This won't work right with relationships, need a fix here.
+    if (!empty($this->view->views_calc_nids)) {
+      $this->view->query->add_where(NULL, "node.nid IN (%s)", implode(',', $this->view->views_calc_nids));
+    }
+  }
+  
+  /**
+   * The grand total can be computed using GROUPBY without regard
+   * to pager values.
+   */
+  function query_total() {
+    // Create summary rows.
+    $calc_fields = $this->get_calc_fields();
+    $calc = $this->view->views_calc_calculation;
+    $fields = $calc_fields[$calc];
+    
+    // Empty out any fields that have been added to the query,
+    // we don't need them for the summary totals.
+    $this->view->query->fields = array();
+    // Clear out any sorting and grouping, it can create unexpected results
+    // when Views adds aggregation values for the sorts.
+    $this->view->query->orderby = array();
+    $this->view->query->groupby = array();
+
+    foreach ($this->view->field as $field) {
+      $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table .'.'. $field->field;
+      $query_alias = $field->field_alias;
+      $this->view->query->add_table($field->table, NULL, NULL, $field->table);
+      if (!empty($fields) && in_array($field->field, $fields)) {
+        // Calculated fields.
+        $this->view->query->add_field(NULL, "$calc($query_field)", $query_alias);
+      }
+      else {
+        // Empty fields that have no calculations.
+        $this->view->query->add_field(NULL, "MAX('')", $query_alias);
+      }
+      // Add a dummy field for the groupby.
+      $this->view->query->add_field(NULL, "MAX('". $calc ."')", "TOTAL_". $calc);
+    }
+  }
+
+  function get_calc_fields() {
+    $options  = $this->view->style_plugin->options;
+    $handler  = $this->view->style_plugin;
+    $fields   = $this->view->field;
+    $columns  = $handler->sanitize_columns($options['columns'], $fields);
+    $calcs = array_keys(_views_calc_calc_options());
+    
+    $calc_fields = array();
+    foreach ($columns as $field => $column) {
+      if ($field == $column && empty($fields[$field]->options['exclude'])) {
+        if ($options['info'][$field]['has_calc']) {
+          foreach ($calcs as $calc) {
+            if (isset($this->options['info'][$field]['calc'][$calc])) {
+              $calc_fields[$calc][] = $field;
+            }
+          }
+        }
+      }
+    }
+    return $calc_fields;
+  }
+}
\ No newline at end of file