comparison views_calc.module @ 0:0651c02e6ed7

views_calc 1.3
author Franck Deroche <franck@defr.org>
date Wed, 05 Aug 2009 18:20:29 +0200
parents
children b0a976e17cc7
comparison
equal deleted inserted replaced
-1:000000000000 0:0651c02e6ed7
1 <?php
2
3 /**
4 * @file
5 * This module will allow you to add calculated fields to views tables
6 * and compute (SUM, COUNT, AVG, etc) columns of numeric data in a views table.
7 */
8 function views_calc_views_api() {
9 return array(
10 'api' => 2,
11 'path' => drupal_get_path('module', 'views_calc'),
12 );
13 }
14
15 function views_calc_theme() {
16 $path = drupal_get_path('module', 'views_calc');
17 return array(
18 'views_calc_ui_table' => array(
19 'arguments' => array('form' => NULL),
20 'file' => 'theme.inc',
21 ),
22 );
23 }
24
25 /**
26 * Implementation of hook_help().
27 */
28 function views_calc_help($section, $arg) {
29 switch ($section) {
30 case 'admin/settings/views_calc':
31 case 'admin/settings/views_calc/fields':
32 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>');
33 case 'admin/settings/views_calc/settings':
34 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.');
35 case 'admin/help#views_calc':
36 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>');
37 }
38 }
39
40 /**
41 * Default SQL operator alternatives.
42 *
43 * The ones allowed in this system are stored in the
44 * variable views_calc_operators, and can be changed
45 * at admin/settings/views_calc.
46 *
47 */
48 function _views_calc_operators() {
49 $default = array('+', '-', '*', '/', '(', ')', ',', "'", 'CONCAT', 'MIN', 'MAX', 'ROUND', 'NOW()');
50 $operators = variable_get('views_calc_operators', implode("\n", $default));
51 return explode("\n", $operators);
52
53 }
54
55 /**
56 * Column calculation alternatives
57 */
58 function _views_calc_calc_options() {
59 return array('COUNT' => 'Count', 'SUM' => 'Sum', 'AVG' => 'Average', 'MIN' => 'Minimum', 'MAX' => 'Maximum');
60 }
61
62 /**
63 * Result format options
64 */
65 function _views_calc_format_options() {
66 $options = array(
67 'none' => '',
68 'integer' => 'intval',
69 'decimal (1)' => 'number_format:1',
70 'decimal (2)' => 'number_format:2',
71 'shortdate' => 'format_date:small',
72 'mediumdate' => 'format_date',
73 'longdate' => 'format_date:large',
74 'custom' => '',
75 );
76 return $options;
77 }
78
79 /**
80 * Implementation of hook_perm().
81 *
82 * The permission 'administer views calc' has rights to alter the SQL
83 * operators that can be used in calculations.
84 *
85 * The permission 'create views calc' has rights to create calculated
86 * fields and set calculation columns on views.
87 */
88 function views_calc_perm() {
89 return array('create views calc', 'administer views calc');
90 }
91
92 function views_calc_menu() {
93
94 $items = array();
95 $items['admin/settings/views_calc'] = array(
96 'title' => t('Views Calc'),
97 'description' => t('Set Views Calc fields and columns.'),
98 'type' => MENU_NORMAL_ITEM,
99 'weight' => 10,
100 'priority' => 1,
101 'page callback' => 'drupal_get_form',
102 'page arguments' => array('views_calc_fields_form'),
103 'access arguments' => array('create views calc'),
104 );
105 $items['admin/settings/views_calc/fields'] = array(
106 'title' => t('Fields'),
107 'type' => MENU_DEFAULT_LOCAL_TASK,
108 'weight' => 5,
109 'priority' => 1,
110 'page callback' => 'drupal_get_form',
111 'page arguments' => array('views_calc_fields_form'),
112 'access arguments' => array('create views calc'),
113 );
114 $items['admin/settings/views_calc/settings'] = array(
115 'title' => t('Settings'),
116 'type' => MENU_LOCAL_TASK,
117 'weight' => 10,
118 'priority' => 1,
119 'page callback' => 'drupal_get_form',
120 'page arguments' => array('views_calc_settings_form'),
121 'access arguments' => array('administer views calc'),
122 );
123 return $items;
124 }
125
126 /**
127 * Implementation of hook_settings()
128 */
129 function views_calc_settings_form() {
130 drupal_set_title(t('Views Calc'));
131 $operators = _views_calc_operators();
132 $form['views_calc_operators'] = array(
133 '#type' => 'textarea',
134 '#default_value' => implode("\n", $operators),
135 '#title' => t('Allowable functions and operators'),
136 '#rows' => intval(sizeof($operators) + 2),
137 );
138 $form['submit'] = array(
139 '#type' => 'submit',
140 '#value' => t('Save'),
141 );
142 return $form;
143 }
144
145 function views_calc_settings_form_submit($form, &$form_state) {
146 $form_values = $form_state['values'];
147 variable_set('views_calc_operators', $form_values['views_calc_operators']);
148 }
149
150 /**
151 * Views Calc Fields tab on views list.
152 */
153 function views_calc_fields_form() {
154 $i = 0;
155 $substitutions = _views_calc_substitutions();
156 $reverse = array_flip($substitutions);
157
158 // display current views calcs fields
159 $fields = _views_calc_fields();
160 while ($field = db_fetch_array($fields)) {
161 $form[] = views_calc_field_form_item($i, $field, $substitutions);
162 $i++;
163 }
164 // add blank fields for more calcs
165 for ($x = $i + 1; $x < $i + 2; $x++) {
166 $field = array();
167 $form[] = views_calc_field_form_item($i, $field, $substitutions);
168 }
169 $form['#prefix'] = '<div class="views-calc-field-settings">';
170 $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>';
171 $form['submit'] = array(
172 '#type' => 'submit',
173 '#value' => t('Save'),
174 );
175 return $form;
176 }
177
178 /**
179 * A form element for an individual calculated field.
180 */
181 function views_calc_field_form_item($i, $field, $substitutions) {
182 if (empty($field)) {
183 $field = array('cid' => 0, 'label' => '', 'tablelist' => '', 'calc' => '', 'format' => '', 'custom' => '');
184 }
185 $form['group'][$i] = array(
186 '#type' => 'fieldset',
187 '#tree' => TRUE,
188 '#title' => t('Field: ') . !empty($field['label']) ? $field['label'] : t('New'),
189 '#collapsible' => TRUE,
190 '#collapsed' => FALSE,
191 );
192 $form['group'][$i]['cid'] = array(
193 '#type' => 'hidden',
194 '#value' => intval($field['cid']),
195 );
196 $form['group'][$i]['tablelist'] = array(
197 '#type' => 'hidden',
198 '#value' => $field['tablelist'],
199 );
200 $form['group'][$i]['label'] = array(
201 '#type' => 'textfield',
202 '#title' => t('Label'),
203 '#field_prefix' => 'ViewsCalc: ',
204 '#default_value' => str_replace('ViewsCalc: ', '', $field['label']),
205 '#description' => t('The views field name for this field (i.e. Views Calc: My Calculation).'),
206 );
207 $form['group'][$i]['calc'] = array(
208 '#type' => 'textarea',
209 '#title' => t('Calculation'),
210 '#default_value' => strtr($field['calc'], $substitutions),
211 '#description' => t('<p>The query operation to be performed, using numbers, field substitutions, and '. implode(' ', _views_calc_operators()) .'.</p>'),
212 );
213 $form['group'][$i]['format'] = array(
214 '#type' => 'select',
215 '#title' => t('Format'),
216 '#default_value' => $field['format'],
217 '#options' => drupal_map_assoc(array_keys(_views_calc_format_options())),
218 '#description' => t('The format of the result of this calculation.'),
219 );
220 $form['group'][$i]['custom'] = array(
221 '#type' => 'textfield',
222 '#title' => t('Custom function'),
223 '#default_value' => $field['custom'],
224 '#description' => t('The function to call for a custom format.'),
225 );
226 return $form;
227 }
228
229 /**
230 * Validate the views calc settings
231 */
232 function views_calc_fields_form_validate($form, &$form_state) {
233 $form_values = $form_state['values'];
234 $edit = $form_values;
235 foreach ($edit as $delta => $item) {
236 if ($item['calc'] == '' || !is_numeric($delta)) {
237 // remove blank fields, don't save them
238 unset($form_values[$delta]);
239 } else {
240 // Remove all valid values from calc, if anything is left over, it is invalid.
241
242 // First, remove all field names.
243 $repl = array();
244 $patterns = array();
245 foreach (_views_calc_substitutions() as $key => $value) {
246 $key = trim($value);
247 $count = strlen($value);
248 $replace = preg_quote($value);
249 $patterns[] = "`(^|[^\\\\\\\\])". $replace ."`";
250 $repl[] = '${1}';
251 }
252 $remaining = trim(preg_replace($patterns, $repl, $item['calc']));
253 // Next, remove functions and numbers.
254 $repl = array();
255 $patterns = array();
256 foreach (_views_calc_replacements() as $value) {
257 $patterns[] = "`(^|[^\\\\\\\\])". preg_quote(trim($value)) ."`";
258 $repl[] = '${1}';
259 }
260 $remaining = trim(preg_replace($patterns, $repl, $remaining));
261 if (!empty($remaining)) {
262 form_set_error($form_values[$delta]['calc'], t('The values %remaining in %field are not allowed.', array('%remaining' => $remaining, '%field' => $item['label'])));
263 }
264 }
265 }
266 }
267
268 /**
269 * Save the views calc field settings
270 */
271 function views_calc_fields_form_submit($form, &$form_state) {
272 $form_values = $form_state['values'];
273 $edit = $form_values;
274 foreach ($edit as $delta => $value) {
275 if ($value['calc'] == '' || !is_numeric($delta)) {
276 // remove blank fields, don't save them
277 unset($form_values[$delta]);
278
279 }
280 else {
281 $tables = array();
282 $form_values[$delta]['label'] = $value['label'];
283 $form_values[$delta]['format'] = $value['format'];
284 $form_values[$delta]['custom'] = $value['custom'];
285 $form_values[$delta]['calc'] = $value['calc'];
286
287 // Substitute field names back into the calculation.
288 $matches = array();
289 foreach (_views_calc_substitutions() as $key => $value) {
290 $label_patterns[] = "`(^|[^\\\\\\\\])". preg_quote($value) ."`";
291 $value_patterns[] = "`(^|[^\\\\\\\\])". preg_quote($key) ."`";
292 $repl[] = '${1}'. $key;
293 }
294 $form_values[$delta]['calc'] = preg_replace($label_patterns, $repl, $form_values[$delta]['calc']);
295
296 // Extract the fields and table names from the calculation.
297 $tables = array();
298 $fields = array();
299 foreach ($value_patterns as $pattern) {
300 if (preg_match($pattern, $form_values[$delta]['calc'], $results)) {
301 $fields[] = trim($results[0]);
302 $tmp = explode('.', trim($results[0]));
303 if (trim($tmp[0])) {
304 $tables[trim($tmp[0])] = trim($tmp[0]);
305 }
306 }
307 }
308 $form_values[$delta]['tablelist'] = implode(',', $tables);
309 $form_values[$delta]['fieldlist'] = implode(',', $fields);
310 }
311 }
312 foreach ($form_values as $delta => $value) {
313 if ($value['cid'] == 0) {
314 drupal_write_record('views_calc_fields', $value);
315 }
316 else {
317 drupal_write_record('views_calc_fields', $value, array('cid'));
318 }
319 }
320 views_invalidate_cache();
321 drupal_set_message(t('Views Calc fields were updated.'));
322 }
323
324 /**
325 * Wrapper function to make sure this function will always work.
326 */
327 function views_calc_views_fetch_fields($base, $type) {
328 if (!module_exists('views')) {
329 return array();
330 }
331 require_once('./'. drupal_get_path('module', 'views') .'/includes/admin.inc');
332 return views_fetch_fields($base, $type);
333 }
334
335 /**
336 * Field substitutions for calculations.
337 */
338 function _views_calc_substitutions($base = 'node') {
339 $fields = views_calc_views_fetch_fields($base, 'field');
340 $substitutions['node.nid'] = '%Node.nid';
341 $substitutions['node.uid'] = '%Node.uid';
342 foreach ($fields as $key => $field) {
343 // For now, omit calculated fields from available fields list.
344 // Doing caculations on calculated fields will require some
345 // complex additional logic, especially if they are nested
346 // several levels deep.
347 if (substr($key, 0, 4) != '.cid') {
348 $substitutions[$key] = '%'. str_replace(' ', '', $key);
349 }
350 }
351 return $substitutions;
352 }
353
354 /**
355 * Views calc fields result object
356 */
357 function _views_calc_fields() {
358 return db_query("SELECT * FROM {views_calc_fields}");
359 }
360
361 /**
362 * An array of allowable calculation values.
363 */
364 function _views_calc_replacements() {
365 $operators = array_filter(_views_calc_operators(), 'trim');
366 $numbers = range(0, 9);
367 return array_merge($operators, $numbers);
368 }