#153714 by Magnus: Imported translation to localization server and removed CVS file.
[project/views.git] / includes / handlers.inc
1 <?php
2 // $Id$
3 /**
4 * @file handlers.inc
5 * Defines the various handler objects to help build and display views.
6 */
7
8 /**
9 * Instantiate and construct a new handler
10 */
11 function _views_create_handler($definition, $type = 'handler') {
12 // vpr('Instantiating handler ' . $definition['handler']);
13 if (empty($definition['handler'])) {
14 return;
15 }
16
17 if (!class_exists($definition['handler']) && !views_include_handler($definition, $type)) {
18 return;
19 }
20
21 $handler = new $definition['handler'];
22 $handler->set_definition($definition);
23 // let the handler have something like a constructor.
24 $handler->construct();
25
26 return $handler;
27 }
28
29 /**
30 * Attempt to find the include file for a given handler from its definition.
31 *
32 * This will also attempt to include all parents, though we're maxing the
33 * parent chain to 10 to prevent infinite loops.
34 */
35 function views_include_handler($definition, $type, $count = 0) {
36 // Do not proceed if the class already exists.
37 if (isset($definition['handler']) && class_exists($definition['handler'])) {
38 return TRUE;
39 }
40
41 // simple infinite loop prevention.
42 if ($count > 10) {
43 vpr(t('Handler @handler include tried to loop infinitely!', array('@handler' => $definition['handler'])));
44 return FALSE;
45 }
46
47 if (!isset($definition['path'])) {
48 if ($type == 'handler') {
49 $definition += views_fetch_handler_data($definition['handler']);
50 }
51 else {
52 $definition += views_fetch_plugin_data($type, $definition['handler']);
53 }
54 }
55
56 if (!empty($definition['parent'])) {
57 if ($type == 'handler') {
58 $parent = views_fetch_handler_data($definition['parent']);
59 }
60 else {
61 $parent = views_fetch_plugin_data($type, $definition['parent']);
62 }
63
64 if ($parent) {
65 $rc = views_include_handler($parent, $type, $count + 1);
66 // If the parent chain cannot be included, don't try; this will
67 // help alleviate problems with modules with cross dependencies.
68 if (!$rc) {
69 return FALSE;
70 }
71 }
72 }
73
74 if (isset($definition['path']) && $definition['file']) {
75 $filename = './' . $definition['path'] . '/' . $definition['file'];
76 if (file_exists($filename)) {
77 require_once $filename;
78 }
79 }
80
81 return class_exists($definition['handler']);
82 }
83
84 /**
85 * Prepare a handler's data by checking defaults and such.
86 */
87 function _views_prepare_handler($definition, $data, $field) {
88 foreach (array('group', 'title', 'title short', 'help', 'real field') as $key) {
89 if (!isset($definition[$key])) {
90 // First check the field level
91 if (!empty($data[$field][$key])) {
92 $definition[$key] = $data[$field][$key];
93 }
94 // Then if that doesn't work, check the table level
95 else if (!empty($data['table'][$key])) {
96 $definition[$key] = $data['table'][$key];
97 }
98 }
99 }
100
101 return _views_create_handler($definition);
102 }
103
104 /**
105 * Fetch the handler data from cache.
106 */
107 function views_fetch_handler_data($handler = NULL) {
108 static $cache = NULL;
109 if (!isset($cache)) {
110 $start = views_microtime();
111
112 $cache = views_discover_handlers();
113
114 vpr('Views handlers build time: ' . (views_microtime() - $start) * 1000 . ' ms');
115 }
116
117 if (!$handler) {
118 return $cache;
119 }
120 else if (isset($cache[$handler])) {
121 return $cache[$handler];
122 }
123
124 // Return an empty array if there is no match.
125 return array();
126 }
127
128 /**
129 * Builds and return a list of all handlers available in the system.
130 *
131 * @return Nested array of handlers
132 */
133 function views_discover_handlers() {
134 $cache = array();
135 // Get handlers from all modules.
136 foreach (module_implements('views_handlers') as $module) {
137 $function = $module . '_views_handlers';
138 $result = $function();
139 if (!is_array($result)) {
140 continue;
141 }
142
143 $module_dir = isset($result['info']['module']) ? $result['info']['module'] : $module;
144 $path = isset($result['info']['path']) ? $result['info']['path'] : drupal_get_path('module', $module_dir);
145
146 foreach ($result['handlers'] as $handler => $def) {
147 if (!isset($def['module'])) {
148 $def['module'] = $module_dir;
149 }
150 if (!isset($def['path'])) {
151 $def['path'] = $path;
152 }
153 if (!isset($def['file'])) {
154 $def['file'] = "$handler.inc";
155 }
156 if (!isset($def['handler'])) {
157 $def['handler'] = $handler;
158 }
159 // merge the new data in
160 $cache[$handler] = $def;
161 }
162 }
163 return $cache;
164 }
165
166 /**
167 * Fetch a handler to join one table to a primary table from the data cache
168 */
169 function views_get_table_join($table, $base_table) {
170 $data = views_fetch_data($table);
171 if (isset($data['table']['join'][$base_table])) {
172 $h = $data['table']['join'][$base_table];
173 if (!empty($h['handler']) && class_exists($h['handler'])) {
174 $handler = new $h['handler'];
175 }
176 else {
177 $handler = new views_join();
178 }
179
180 // Fill in some easy defaults
181 $handler->definition = $h;
182 if (empty($handler->definition['table'])) {
183 $handler->definition['table'] = $table;
184 }
185 // If this is empty, it's a direct link.
186 if (empty($handler->definition['left_table'])) {
187 $handler->definition['left_table'] = $base_table;
188 }
189
190 if (isset($h['arguments'])) {
191 call_user_func_array(array(&$handler, 'construct'), $h['arguments']);
192 }
193 else {
194 $handler->construct();
195 }
196
197 return $handler;
198 }
199 // DEBUG -- identify missing handlers
200 vpr("Missing join: $table $base_table");
201 }
202
203 /**
204 * Base handler, from which all the other handlers are derived.
205 * It creates a common interface to create consistency amongst
206 * handlers and data.
207 *
208 * This class would be abstract in PHP5, but PHP4 doesn't understand that.
209 *
210 * Definition terms:
211 * - table: The actual table this uses; only specify if different from
212 * the table this is attached to.
213 * - real field: The actual field this uses; only specify if different from
214 * the field this item is attached to.
215 * - group: A text string representing the 'group' this item is attached to,
216 * for display in the UI. Examples: "Node", "Taxonomy", "Comment",
217 * "User", etc. This may be inherited from the parent definition or
218 * the 'table' definition.
219 * - title: The title for this handler in the UI. This may be inherited from
220 * the parent definition or the 'table' definition.
221 * - help: A more informative string to give to the user to explain what this
222 * field/handler is or does.
223 * - access callback: If this field should have access control, this could
224 * be a function to use. 'user_access' is a common
225 * function to use here. If not specified, no access
226 * control is provided.
227 * - access arguments: An array of arguments for the access callback.
228 */
229 class views_handler extends views_object {
230 /**
231 * init the handler with necessary data.
232 * @param $view
233 * The $view object this handler is attached to.
234 * @param $options
235 * The item from the database; the actual contents of this will vary
236 * based upon the type of handler.
237 */
238 function init(&$view, $options) {
239 $this->view = &$view;
240 $this->unpack_options($this->options, $options);
241
242 // This exist on most handlers, but not all. So they are still optional.
243 if (isset($options['table'])) {
244 $this->table = $options['table'];
245 }
246
247 if (isset($this->definition['real field'])) {
248 $this->real_field = $this->definition['real field'];
249 }
250
251 if (isset($this->definition['field'])) {
252 $this->real_field = $this->definition['field'];
253 }
254
255 if (isset($options['field'])) {
256 $this->field = $options['field'];
257 if (!isset($this->real_field)) {
258 $this->real_field = $options['field'];
259 }
260 }
261
262 $this->query = &$view->query;
263 }
264
265 /**
266 * Return a string representing this handler's name in the UI.
267 */
268 function ui_name($short = FALSE) {
269 $title = ($short && isset($this->definition['title short'])) ? $this->definition['title short'] : $this->definition['title'];
270 return t('!group: !title', array('!group' => $this->definition['group'], '!title' => $title));
271 }
272
273 /**
274 * Provide a form for setting options.
275 */
276 function options_form(&$form, &$form_state) { }
277
278 /**
279 * Validate the options form.
280 */
281 function options_validate($form, &$form_state) { }
282
283 /**
284 * Perform any necessary changes to the form values prior to storage.
285 * There is no need for this function to actually store the data.
286 */
287 function options_submit($form, &$form_state) { }
288
289 /**
290 * If a handler has 'extra options' it will get a little settings widget and
291 * another form called extra_options.
292 */
293 function has_extra_options() { return FALSE; }
294
295 /**
296 * Provide defaults for the handler.
297 */
298 function extra_options(&$option) { }
299
300 /**
301 * Provide a form for setting options.
302 */
303 function extra_options_form(&$form, &$form_state) { }
304
305 /**
306 * Validate the options form.
307 */
308 function extra_options_validate($form, &$form_state) { }
309
310 /**
311 * Perform any necessary changes to the form values prior to storage.
312 * There is no need for this function to actually store the data.
313 */
314 function extra_options_submit($form, &$form_state) { }
315
316 /**
317 * Set new exposed option defaults when exposed setting is flipped
318 * on.
319 */
320 function expose_options() { }
321 /**
322 * Render our chunk of the exposed filter form when selecting
323 */
324 function exposed_form(&$form, &$form_state) { }
325
326 /**
327 * Validate the exposed filter form
328 */
329 function exposed_validate(&$form, &$form_state) { }
330
331 /**
332 * Submit the exposed filter form
333 */
334 function exposed_submit(&$form, &$form_state) { }
335
336 /**
337 * Get information about the exposed form for the form renderer.
338 *
339 * @return
340 * An array with the following keys:
341 * - operator: The $form key of the operator. Set to NULL if no operator.
342 * - value: The $form key of the value. Set to NULL if no value.
343 * - label: The label to use for this piece.
344 */
345 function exposed_info() { }
346
347 /**
348 * Check whether current user has access to this handler.
349 *
350 * @return boolean
351 */
352 function access() {
353 if (isset($this->definition['access callback']) && function_exists($this->definition['access callback'])) {
354 if (isset($this->definition['access arguments']) && is_array($this->definition['access arguments'])) {
355 return call_user_func_array($this->definition['access callback'], $this->definition['access arguments']);
356 }
357 return $this->definition['access callback']();
358 }
359
360 return TRUE;
361 }
362
363 /**
364 * Run before the view is built.
365 *
366 * This gives all the handlers some time to set up before any handler has
367 * been fully run.
368 */
369 function pre_query() { }
370
371 /**
372 * Called just prior to query(), this lets a handler set up any relationship
373 * it needs.
374 */
375 function set_relationship() {
376 // Ensure this gets set to something.
377 $this->relationship = NULL;
378
379 // Don't process non-existant relationships.
380 if (empty($this->options['relationship']) || $this->options['relationship'] == 'none') {
381 return;
382 }
383
384 $relationship = $this->options['relationship'];
385
386 // Ignore missing/broken relationships.
387 if (empty($this->view->relationship[$relationship])) {
388 return;
389 }
390
391 // Check to see if the relationship has already processed. If not, then we
392 // cannot process it.
393 if (empty($this->view->relationship[$relationship]->alias)) {
394 return;
395 }
396
397 // Finally!
398 $this->relationship = $this->view->relationship[$relationship]->alias;
399 }
400
401 /**
402 * Add this handler into the query.
403 *
404 * If we were using PHP5, this would be abstract.
405 */
406 function query() { }
407
408 /**
409 * Ensure the main table for this handler is in the query. This is used
410 * a lot.
411 */
412 function ensure_my_table() {
413 if (!isset($this->table_alias)) {
414 if (!method_exists($this->query, 'ensure_table')) { vpr_trace(); exit; }
415 $this->table_alias = $this->query->ensure_table($this->table, $this->relationship);
416 }
417 return $this->table_alias;
418 }
419
420 /**
421 * Provide text for the administrative summary
422 */
423 function admin_summary() { }
424
425 /**
426 * Determine if the argument needs a style plugin.
427 *
428 * @return TRUE/FALSE
429 */
430 function needs_style_plugin() { return FALSE; }
431
432 /**
433 * Determine if this item is 'exposed', meaning it provides form elements
434 * to let users modify the view.
435 *
436 * @return TRUE/FALSE
437 */
438 function is_exposed() {
439 return !empty($this->options['exposed']);
440 }
441
442 /**
443 * Take input from exposed filters and assign to this handler, if necessary.
444 */
445 function accept_exposed_input($input) { return TRUE; }
446
447 /**
448 * If set to remember exposed input in the session, store it there.
449 */
450 function store_exposed_input($input, $status) { return TRUE; }
451
452 /**
453 * Get the join object that should be used for this handler.
454 *
455 * This method isn't used a great deal, but it's very handy for easily
456 * getting the join if it is necessary to make some changes to it, such
457 * as adding an 'extra'.
458 */
459 function get_join() {
460 // get the join from this table that links back to the base table.
461 // Determine the primary table to seek
462 if (empty($this->query->relationships[$this->relationship])) {
463 $base_table = $this->query->base_table;
464 }
465 else {
466 $base_table = $this->query->relationships[$this->relationship]['base'];
467 }
468
469 $join = views_get_table_join($this->table, $base_table);
470 if ($join) {
471 return drupal_clone($join);
472 }
473 }
474
475 /**
476 * Validates the handler against the complete View.
477 *
478 * This is called when the complete View is being validated. For validating
479 * the handler options form use options_validate().
480 *
481 * @see views_handler::options_validate()
482 *
483 * @return
484 * Empty array if the handler is valid; an array of error strings if it is not.
485 */
486 function validate() { return array(); }
487
488 /**
489 * Determine if the handler is considered 'broken', meaning it's a
490 * a placeholder used when a handler can't be found.
491 */
492 function broken() { }
493 }
494
495 /**
496 * This many to one helper object is used on both arguments and filters.
497 *
498 * @todo This requires extensive documentation on how this class is to
499 * be used. For now, look at the arguments and filters that use it. Lots
500 * of stuff is just pass-through but there are definitely some interesting
501 * areas where they interact.
502 *
503 * Any handler that uses this can have the following possibly additional
504 * definition terms:
505 * - numeric: If true, treat this field as numeric, using %d instead of %s in
506 * queries.
507 *
508 */
509 class views_many_to_one_helper {
510 function views_many_to_one_helper(&$handler) {
511 $this->handler = &$handler;
512 }
513
514 function option_definition(&$options) {
515 $options['reduce_duplicates'] = array('default' => FALSE);
516 }
517
518 function options_form(&$form, &$form_state) {
519 $form['reduce_duplicates'] = array(
520 '#type' => 'checkbox',
521 '#title' => t('Reduce duplicates'),
522 '#description' => t('This filter can cause items that have more than one of the selected options to appear as duplicate results. If this filter causes duplicate results to occur, this checkbox can reduce those duplicates; however, the more terms it has to search for, the less performant the query will be, so use this with caution. Shouldn\'t be set on single-value fields, as it may cause values to disappear from display, if used on an incompatible field.'),
523 '#default_value' => !empty($this->handler->options['reduce_duplicates']),
524 );
525 }
526
527 /**
528 * Sometimes the handler might want us to use some kind of formula, so give
529 * it that option. If it wants us to do this, it must set $helper->formula = TRUE
530 * and implement handler->get_formula();
531 */
532 function get_field() {
533 if (!empty($this->formula)) {
534 return $this->handler->get_formula();
535 }
536 else {
537 return $this->handler->table_alias . '.' . $this->handler->real_field;
538 }
539 }
540
541 /**
542 * Add a table to the query.
543 *
544 * This is an advanced concept; not only does it add a new instance of the table,
545 * but it follows the relationship path all the way down to the relationship
546 * link point and adds *that* as a new relationship and then adds the table to
547 * the relationship, if necessary.
548 */
549 function add_table($join = NULL, $alias = NULL) {
550 // This is used for lookups in the many_to_one table.
551 $field = $this->handler->table . '.' . $this->handler->field;
552
553 if (empty($join)) {
554 $join = $this->get_join();
555 }
556
557 // See if there's a chain between us and the base relationship. If so, we need
558 // to create a new relationship to use.
559 $relationship = $this->handler->relationship;
560
561 // Determine the primary table to seek
562 if (empty($this->handler->query->relationships[$relationship])) {
563 $base_table = $this->handler->query->base_table;
564 }
565 else {
566 $base_table = $this->handler->query->relationships[$relationship]['base'];
567 }
568
569 // Cycle through the joins. This isn't as error-safe as the normal
570 // ensure_path logic. Perhaps it should be.
571 $r_join = drupal_clone($join);
572 while ($r_join->left_table != $base_table) {
573 $r_join = views_get_table_join($r_join->left_table, $base_table);
574 }
575 // If we found that there are tables in between, add the relationship.
576 if ($r_join->table != $join->table) {
577 $relationship = $this->handler->query->add_relationship($this->handler->table . '_' . $r_join->table, $r_join, $r_join->table, $this->handler->relationship);
578 }
579
580 // And now add our table, using the new relationship if one was used.
581 $alias = $this->handler->query->add_table($this->handler->table, $relationship, $join, $alias);
582
583 // Store what values are used by this table chain so that other chains can
584 // automatically discard those values.
585 if (empty($this->handler->view->many_to_one_tables[$field])) {
586 $this->handler->view->many_to_one_tables[$field] = $this->handler->value;
587 }
588 else {
589 $this->handler->view->many_to_one_tables[$field] = array_merge($this->handler->view->many_to_one_tables[$field], $this->handler->value);
590 }
591
592 return $alias;
593 }
594
595 function get_join() {
596 return $this->handler->get_join();
597 }
598
599 /**
600 * Provide the proper join for summary queries. This is important in part because
601 * it will cooperate with other arguments if possible.
602 */
603 function summary_join() {
604 $field = $this->handler->table . '.' . $this->handler->field;
605 $join = $this->get_join();
606
607 // shortcuts
608 $options = $this->handler->options;
609 $view = &$this->handler->view;
610 $query = &$this->handler->query;
611
612 if (!empty($options['require_value'])) {
613 $join->type = 'INNER';
614 }
615
616 if (empty($options['add_table']) || empty($view->many_to_one_tables[$field])) {
617 return $query->ensure_table($this->handler->table, $this->handler->relationship, $join);
618 }
619 else {
620 if (!empty($view->many_to_one_tables[$field])) {
621 foreach ($view->many_to_one_tables[$field] as $value) {
622 $join->extra = array(
623 array(
624 'field' => $this->handler->real_field,
625 'operator' => '!=',
626 'value' => $value,
627 'numeric' => !empty($this->definition['numeric']),
628 ),
629 );
630 }
631 }
632 return $this->add_table($join);
633 }
634 }
635
636 /**
637 * Override ensure_my_table so we can control how this joins in.
638 * The operator actually has influence over joining.
639 */
640 function ensure_my_table() {
641 if (!isset($this->handler->table_alias)) {
642 // For 'or' if we're not reducing duplicates, we get the absolute simplest:
643 $field = $this->handler->table . '.' . $this->handler->field;
644 if ($this->handler->operator == 'or' && empty($this->handler->options['reduce_duplicates'])) {
645 if (empty($this->handler->options['add_table']) && empty($this->handler->view->many_to_one_tables[$field])) {
646 // query optimization, INNER joins are slightly faster, so use them
647 // when we know we can.
648 $join = $this->get_join();
649 $join->type = 'INNER';
650 $this->handler->table_alias = $this->handler->query->ensure_table($this->handler->table, $this->handler->relationship, $join);
651 $this->handler->view->many_to_one_tables[$field] = $this->handler->value;
652 }
653 else {
654 $join = $this->get_join();
655 $join->type = 'LEFT';
656 if (!empty($this->handler->view->many_to_one_tables[$field])) {
657 foreach ($this->handler->view->many_to_one_tables[$field] as $value) {
658 $join->extra = array(
659 array(
660 'field' => $this->handler->real_field,
661 'operator' => '!=',
662 'value' => $value,
663 'numeric' => !empty($this->handler->definition['numeric']),
664 ),
665 );
666 }
667 }
668
669 $this->handler->table_alias = $this->add_table($join);
670 }
671
672 return $this->handler->table_alias;
673 }
674
675 if ($this->handler->operator != 'not') {
676 // If it's an and or an or, we do one join per selected value.
677 // Clone the join for each table:
678 $this->handler->table_aliases = array();
679 foreach ($this->handler->value as $value) {
680 $join = $this->get_join();
681 if ($this->handler->operator == 'and') {
682 $join->type = 'INNER';
683 }
684 $join->extra = array(
685 array(
686 'field' => $this->handler->real_field,
687 'value' => $value,
688 'numeric' => !empty($this->handler->definition['numeric']),
689 ),
690 );
691
692 // The table alias needs to be unique to this value across the
693 // multiple times the filter or argument is called by the view.
694 if (!isset($this->handler->view->many_to_one_aliases[$field][$value])) {
695 if (!isset($this->handler->view->many_to_one_count[$this->handler->table])) {
696 $this->handler->view->many_to_one_count[$this->handler->table] = 0;
697 }
698 $this->handler->view->many_to_one_aliases[$field][$value] = $this->handler->table . '_value_' . ($this->handler->view->many_to_one_count[$this->handler->table]++);
699 }
700 $alias = $this->handler->table_aliases[$value] = $this->add_table($join, $this->handler->view->many_to_one_aliases[$field][$value]);
701
702 // and set table_alias to the first of these.
703 if (empty($this->handler->table_alias)) {
704 $this->handler->table_alias = $alias;
705 }
706 }
707 }
708 else {
709 // For not, we just do one join. We'll add a where clause during
710 // the query phase to ensure that $table.$field IS NULL.
711 $join = $this->get_join();
712 $join->type = 'LEFT';
713 $join->extra = array();
714 $join->extra_type = 'OR';
715 foreach ($this->handler->value as $value) {
716 $join->extra[] = array(
717 'field' => $this->handler->real_field,
718 'value' => $value,
719 'numeric' => !empty($this->handler->definition['numeric']),
720 );
721 }
722
723 $this->handler->table_alias = $this->add_table($join);
724 }
725 }
726 return $this->handler->table_alias;
727 }
728
729 function add_filter() {
730 if (empty($this->handler->value)) {
731 return;
732 }
733 $this->handler->ensure_my_table();
734
735 // Shorten some variables:
736 $field = $this->get_field();
737 $options = $this->handler->options;
738 $operator = $this->handler->operator;
739 if (empty($options['group'])) {
740 $options['group'] = 0;
741 }
742
743 $placeholder = !empty($this->handler->definition['numeric']) ? '%d' : "'%s'";
744
745 if ($operator == 'not') {
746 $this->handler->query->add_where($options['group'], "$field IS NULL");
747 }
748 else if ($operator == 'or' && empty($options['reduce_duplicates'])) {
749 if (count($this->handler->value) > 1) {
750 $replace = array_fill(0, sizeof($this->handler->value), $placeholder);
751 $in = '(' . implode(", ", $replace) . ')';
752 $this->handler->query->add_where($options['group'], "$field IN $in", $this->handler->value);
753 }
754 else {
755 $this->handler->query->add_where($options['group'], "$field = $placeholder", $this->handler->value);
756 }
757 }
758 else {
759 $field = $this->handler->real_field;
760 $clauses = array();
761 foreach ($this->handler->table_aliases as $value => $alias) {
762 $clauses[] = "$alias.$field = $placeholder";
763 }
764
765 $group = empty($options['group']) ? 0 : $options['group'];
766
767 // implode on either AND or OR.
768 $this->handler->query->add_where($group, implode(' ' . strtoupper($operator) . ' ', $clauses), $this->handler->value);
769 }
770 }
771 }
772
773 /*
774 * Break x,y,z and x+y+z into an array. Numeric only.
775 *
776 * @param $str
777 * The string to parse.
778 * @param $filter
779 * The filter object to use as a base. If not specified one will
780 * be created.
781 *
782 * @return $filter
783 * The new filter object.
784 */
785 function views_break_phrase($str, $filter = NULL) {
786 if (!$filter) {
787 $filter = new stdClass();
788 }
789
790 // Set up defaults:
791
792 if (!isset($filter->value)) {
793 $filter->value = array();
794 }
795
796 if (!isset($filter->operator)) {
797 $filter->operator = 'or';
798 }
799
800 if (empty($str)) {
801 return $filter;
802 }
803
804 if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {
805 // The '+' character in a query string may be parsed as ' '.
806 $filter->operator = 'or';
807 $filter->value = preg_split('/[+ ]/', $str);
808 }
809 else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
810 $filter->operator = 'and';
811 $filter->value = explode(',', $str);
812 }
813
814 // Keep an 'error' value if invalid strings were given.
815 if (!empty($str) && (empty($filter->value) || !is_array($filter->value))) {
816 $filter->value = array(-1);
817 return $filter;
818 }
819
820 // Doubly ensure that all values are numeric only.
821 foreach ($filter->value as $id => $value) {
822 $filter->value[$id] = intval($value);
823 }
824
825 return $filter;
826 }
827
828 // --------------------------------------------------------------------------
829 // Date helper functions
830
831 /**
832 * Figure out what timezone we're in; needed for some date manipulations.
833 */
834 function views_get_timezone() {
835 global $user;
836 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
837 $timezone = $user->timezone;
838 }
839 else {
840 $timezone = variable_get('date_default_timezone', 0);
841 }
842
843 // set up the database timezone
844 if (in_array($GLOBALS['db_type'], array('mysql', 'mysqli', 'pgsql'))) {
845 $offset = '+00:00';
846 static $already_set = false;
847 if (!$already_set) {
848 if ($GLOBALS['db_type'] == 'pgsql') {
849 db_query("SET TIME ZONE INTERVAL '$offset' HOUR TO MINUTE");
850 }
851 elseif ($GLOBALS['db_type'] == 'mysqli' || version_compare(mysql_get_server_info(), '4.1.3', '>=')) {
852 db_query("SET @@session.time_zone = '$offset'");
853 }
854
855 $already_set = true;
856 }
857 }
858
859 return $timezone;
860 }
861
862 /**
863 * Helper function to create cross-database SQL dates.
864 *
865 * @param $field
866 * The real table and field name, like 'tablename.fieldname'.
867 * @param $field_type
868 * The type of date field, 'int' or 'datetime'.
869 * @param $set_offset
870 * The name of a field that holds the timezone offset or a fixed timezone
871 * offset value. If not provided, the normal Drupal timezone handling
872 * will be used, i.e. $set_offset = 0 will make no timezone adjustment.
873 * @return
874 * An appropriate SQL string for the db type and field type.
875 */
876 function views_date_sql_field($field, $field_type = 'int', $set_offset = NULL) {
877 $db_type = $GLOBALS['db_type'];
878 $offset = $set_offset !== NULL ? $set_offset : views_get_timezone();
879 switch ($db_type) {
880 case 'mysql':
881 case 'mysqli':
882 switch ($field_type) {
883 case 'int':
884 $field = "FROM_UNIXTIME($field)";
885 break;
886 case 'datetime':
887 break;
888 }
889 if (!empty($offset)) {
890 $field = "($field + INTERVAL $offset SECOND)";
891 }
892 return $field;
893 case 'pgsql':
894 switch ($field_type) {
895 case 'int':
896 $field = "$field::ABSTIME";
897 break;
898 case 'datetime':
899 break;
900 }
901 if (!empty($offset)) {
902 $field = "($field + INTERVAL '$offset SECONDS')";
903 }
904 return $field;
905 }
906 }
907
908 /**
909 * Helper function to create cross-database SQL date formatting.
910 *
911 * @param $format
912 * A format string for the result, like 'Y-m-d H:i:s'.
913 * @param $field
914 * The real table and field name, like 'tablename.fieldname'.
915 * @param $field_type
916 * The type of date field, 'int' or 'datetime'.
917 * @param $set_offset
918 * The name of a field that holds the timezone offset or a fixed timezone
919 * offset value. If not provided, the normal Drupal timezone handling
920 * will be used, i.e. $set_offset = 0 will make no timezone adjustment.
921 * @return
922 * An appropriate SQL string for the db type and field type.
923 */
924 function views_date_sql_format($format, $field, $field_type = 'int', $set_offset = NULL) {
925 $db_type = $GLOBALS['db_type'];
926 $field = views_date_sql_field($field, $field_type, $set_offset);
927 switch ($db_type) {
928 case 'mysql':
929 case 'mysqli':
930 $replace = array(
931 'Y' => '%Y',
932 'm' => '%m',
933 'd' => '%%d',
934 'H' => '%H',
935 'i' => '%i',
936 's' => '%s',
937 );
938 $format = strtr($format, $replace);
939 return "DATE_FORMAT($field, '$format')";
940 case 'pgsql':
941 $replace = array(
942 'Y' => 'YYYY',
943 'm' => 'MM',
944 'd' => 'DD',
945 'H' => 'HH24',
946 'i' => 'MI',
947 's' => 'SS',
948 );
949 $format = strtr($format, $replace);
950 return "TO_CHAR($field, '$format')";
951 }
952 }
953
954 /**
955 * Helper function to create cross-database SQL date extraction.
956 *
957 * @param $extract_type
958 * The type of value to extract from the date, like 'MONTH'.
959 * @param $field
960 * The real table and field name, like 'tablename.fieldname'.
961 * @param $field_type
962 * The type of date field, 'int' or 'datetime'.
963 * @param $set_offset
964 * The name of a field that holds the timezone offset or a fixed timezone
965 * offset value. If not provided, the normal Drupal timezone handling
966 * will be used, i.e. $set_offset = 0 will make no timezone adjustment.
967 * @return
968 * An appropriate SQL string for the db type and field type.
969 */
970 function views_date_sql_extract($extract_type, $field, $field_type = 'int', $set_offset = NULL) {
971 $db_type = $GLOBALS['db_type'];
972 $field = views_date_sql_field($field, $field_type, $set_offset);
973
974 // Note there is no space after FROM to avoid db_rewrite problems
975 // see http://drupal.org/node/79904.
976 switch ($extract_type) {
977 case('DATE'):
978 return $field;
979 case('YEAR'):
980 return "EXTRACT(YEAR FROM($field))";
981 case('MONTH'):
982 return "EXTRACT(MONTH FROM($field))";
983 case('DAY'):
984 return "EXTRACT(DAY FROM($field))";
985 case('HOUR'):
986 return "EXTRACT(HOUR FROM($field))";
987 case('MINUTE'):
988 return "EXTRACT(MINUTE FROM($field))";
989 case('SECOND'):
990 return "EXTRACT(SECOND FROM($field))";
991 case('WEEK'): // ISO week number for date
992 switch ($db_type) {
993 case('mysql'):
994 case('mysqli'):
995 // WEEK using arg 3 in mysql should return the same value as postgres EXTRACT
996 return "WEEK($field, 3)";
997 case('pgsql'):
998 return "EXTRACT(WEEK FROM($field))";
999 }
1000 case('DOW'):
1001 switch ($db_type) {
1002 case('mysql'):
1003 case('mysqli'):
1004 // mysql returns 1 for Sunday through 7 for Saturday
1005 // php date functions and postgres use 0 for Sunday and 6 for Saturday
1006 return "INTEGER(DAYOFWEEK($field) - 1)";
1007 case('pgsql'):
1008 return "EXTRACT(DOW FROM($field))";
1009 }
1010 case('DOY'):
1011 switch ($db_type) {
1012 case('mysql'):
1013 case('mysqli'):
1014 return "DAYOFYEAR($field)";
1015 case('pgsql'):
1016 return "EXTRACT(DOY FROM($field))";
1017 }
1018 }
1019 }
1020
1021 /**
1022 * Implementation of hook_views_handlers() to register all of the basic handlers
1023 * views uses.
1024 */
1025 function views_views_handlers() {
1026 return array(
1027 'info' => array(
1028 'path' => drupal_get_path('module', 'views') . '/handlers',
1029 ),
1030 'handlers' => array(
1031 // argument handlers
1032 'views_handler_argument' => array(
1033 'parent' => 'views_handler',
1034 ),
1035 'views_handler_argument_numeric' => array(
1036 'parent' => 'views_handler_argument',
1037 ),
1038 'views_handler_argument_formula' => array(
1039 'parent' => 'views_handler_argument',
1040 ),
1041 'views_handler_argument_date' => array(
1042 'parent' => 'views_handler_argument_formula',
1043 ),
1044 'views_handler_argument_string' => array(
1045 'parent' => 'views_handler_argument',
1046 ),
1047 'views_handler_argument_many_to_one' => array(
1048 'parent' => 'views_handler_argument',
1049 ),
1050 'views_handler_argument_null' => array(
1051 'parent' => 'views_handler_argument',
1052 ),
1053
1054 // field handlers
1055 'views_handler_field' => array(
1056 'parent' => 'views_handler',
1057 ),
1058 'views_handler_field_date' => array(
1059 'parent' => 'views_handler_field',
1060 ),
1061 'views_handler_field_boolean' => array(
1062 'parent' => 'views_handler_field',
1063 ),
1064 'views_handler_field_markup' => array(
1065 'parent' => 'views_handler_field',
1066 ),
1067 'views_handler_field_xss' => array(
1068 'parent' => 'views_handler_field',
1069 'file' => 'views_handler_field.inc',
1070 ),
1071 'views_handler_field_url' => array(
1072 'parent' => 'views_handler_field',
1073 ),
1074 'views_handler_field_file_size' => array(
1075 'parent' => 'views_handler_field',
1076 'file' => 'views_handler_field.inc',
1077 ),
1078 'views_handler_field_prerender_list' => array(
1079 'parent' => 'views_handler_field',
1080 ),
1081 'views_handler_field_numeric' => array(
1082 'parent' => 'views_handler_field',
1083 ),
1084 'views_handler_field_custom' => array(
1085 'parent' => 'views_handler_field',
1086 ),
1087 'views_handler_field_counter' => array(
1088 'parent' => 'views_handler_field',
1089 ),
1090
1091 // filter handlers
1092 'views_handler_filter' => array(
1093 'parent' => 'views_handler',
1094 ),
1095 'views_handler_filter_equality' => array(
1096 'parent' => 'views_handler_filter',
1097 ),
1098 'views_handler_filter_string' => array(
1099 'parent' => 'views_handler_filter',
1100 ),
1101 'views_handler_filter_boolean_operator' => array(
1102 'parent' => 'views_handler_filter',
1103 ),
1104 'views_handler_filter_boolean_operator_string' => array(
1105 'parent' => 'views_handler_filter_boolean_operator',
1106 ),
1107 'views_handler_filter_in_operator' => array(
1108 'parent' => 'views_handler_filter',
1109 ),
1110 'views_handler_filter_numeric' => array(
1111 'parent' => 'views_handler_filter',
1112 ),
1113 'views_handler_filter_float' => array(
1114 'parent' => 'views_handler_filter_numeric',
1115 ),
1116 'views_handler_filter_date' => array(
1117 'parent' => 'views_handler_filter_numeric',
1118 ),
1119 'views_handler_filter_many_to_one' => array(
1120 'parent' => 'views_handler_filter_in_operator',
1121 ),
1122
1123 // relationship handlers
1124 'views_handler_relationship' => array(
1125 'parent' => 'views_handler',
1126 ),
1127
1128
1129 // sort handlers
1130 'views_handler_sort' => array(
1131 'parent' => 'views_handler',
1132 ),
1133 'views_handler_sort_formula' => array(
1134 'parent' => 'views_handler_sort',
1135 ),
1136 'views_handler_sort_date' => array(
1137 'parent' => 'views_handler_sort',
1138 ),
1139 'views_handler_sort_menu_hierarchy' => array(
1140 'parent' => 'views_handler_sort',
1141 ),
1142 'views_handler_sort_random' => array(
1143 'parent' => 'views_handler_sort',
1144 ),
1145 ),
1146 );
1147 }
1148
1149
1150 /**
1151 * @}
1152 */
1153
1154 /**
1155 * @defgroup views_join_handlers Views' join handlers
1156 * @{
1157 * Handlers to tell Views how to join tables together.
1158
1159 * Here is how you do complex joins:
1160 *
1161 * @code
1162 * class views_join_complex extends views_join {
1163 * // PHP 4 doesn't call constructors of the base class automatically from a
1164 * // constructor of a derived class. It is your responsibility to propagate
1165 * // the call to constructors upstream where appropriate.
1166 * function construct($table, $left_table, $left_field, $field, $extra = array(), $type = 'LEFT') {
1167 * parent::construct($table, $left_table, $left_field, $field, $extra, $type);
1168 * }
1169 *
1170 * function join($table, &$query) {
1171 * $output = parent::join($table, $query);
1172 * }
1173 * $output .= "AND foo.bar = baz.boing";
1174 * return $output;
1175 * }
1176 * @endcode
1177 */
1178 /**
1179 * A function class to represent a join and create the SQL necessary
1180 * to implement the join.
1181 *
1182 * This is the Delegation pattern. If we had PHP5 exclusively, we would
1183 * declare this an interface.
1184 *
1185 * Extensions of this class can be used to create more interesting joins.
1186 *
1187 * join definition
1188 * - table: table to join (right table)
1189 * - field: field to join on (right field)
1190 * - left_table: The table we join to
1191 * - left_field: The field we join to
1192 * - type: either LEFT (default) or INNER
1193 * - extra: Either a string that's directly added, or an array of items:
1194 * - - table: if not set, current table; if NULL, no table. This field can't
1195 * be set in the cached definition because it can't know aliases; this field
1196 * can only be used by realtime joins.
1197 * - - field: Field or formula
1198 * - - operator: defaults to =
1199 * - - value: Must be set. If an array, operator will be defaulted to IN.
1200 * - - numeric: If true, the value will not be surrounded in quotes.
1201 * - extra type: How all the extras will be combined. Either AND or OR. Defaults to AND.
1202 */
1203 class views_join {
1204 /**
1205 * Construct the views_join object.
1206 */
1207 function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT') {
1208 $this->extra_type = 'AND';
1209 if (!empty($table)) {
1210 $this->table = $table;
1211 $this->left_table = $left_table;
1212 $this->left_field = $left_field;
1213 $this->field = $field;
1214 $this->extra = $extra;
1215 $this->type = strtoupper($type);
1216 }
1217 else if (!empty($this->definition)) {
1218 // if no arguments, construct from definition.
1219 // These four must exist or it will throw notices.
1220 $this->table = $this->definition['table'];
1221 $this->left_table = $this->definition['left_table'];
1222 $this->left_field = $this->definition['left_field'];
1223 $this->field = $this->definition['field'];
1224 if (!empty($this->definition['extra'])) {
1225 $this->extra = $this->definition['extra'];
1226 }
1227 if (!empty($this->definition['extra type'])) {
1228 $this->extra_type = strtoupper($this->definition['extra type']);
1229 }
1230
1231 $this->type = !empty($this->definition['type']) ? strtoupper($this->definition['type']) : 'LEFT';
1232 }
1233 }
1234
1235 /**
1236 * Build the SQL for the join this object represents.
1237 */
1238 function join($table, &$query) {
1239 if (empty($this->definition['table formula'])) {
1240 $right_table = "{" . $this->table . "}";
1241 }
1242 else {
1243 $right_table = $this->definition['table formula'];
1244 }
1245
1246 if ($this->left_table) {
1247 $left = $query->get_table_info($this->left_table);
1248 $left_field = "$left[alias].$this->left_field";
1249 }
1250 else {
1251 // This can be used if left_field is a formula or something. It should be used only *very* rarely.
1252 $left_field = $this->left_field;
1253 }
1254
1255 $output = " $this->type JOIN $right_table $table[alias] ON $left_field = $table[alias].$this->field";
1256 // Tack on the extra.
1257 if (isset($this->extra)) {
1258 if (is_array($this->extra)) {
1259 $extras = array();
1260 foreach ($this->extra as $info) {
1261 $extra = '';
1262 // Figure out the table name. Remember, only use aliases provided
1263 // if at all possible.
1264 $join_table = '';
1265 if (!array_key_exists('table', $info)) {
1266 $join_table = $table['alias'] . '.';
1267 }
1268 elseif (isset($info['table'])) {
1269 $join_table = $info['table'] . '.';
1270 }
1271
1272 // And now deal with the value and the operator. Set $q to
1273 // a single-quote for non-numeric values and the
1274 // empty-string for numeric values, then wrap all values in $q.
1275 $raw_value = $this->db_safe($info['value']);
1276 $q = (empty($info['numeric']) ? "'" : '');
1277
1278 if (is_array($raw_value)) {
1279 $operator = !empty($info['operator']) ? $info['operator'] : 'IN';
1280 // Transform from IN() notation to = notation if just one value.
1281 if (count($raw_value) == 1) {
1282 $value = $q . array_shift($raw_value) . $q;
1283 $operator = $operator == 'NOT IN' ? '!=' : '=';
1284 }
1285 else {
1286 $value = "($q" . implode("$q, $q", $raw_value) . "$q)";
1287 }
1288 }
1289 else {
1290 $operator = !empty($info['operator']) ? $info['operator'] : '=';
1291 $value = "$q$raw_value$q";
1292 }
1293 $extras[] = "$join_table$info[field] $operator $value";
1294 }
1295
1296 if ($extras) {
1297 if (count($extras) == 1) {
1298 $output .= ' AND ' . array_shift($extras);
1299 }
1300 else {
1301 $output .= ' AND (' . implode(' ' . $this->extra_type . ' ', $extras) . ')';
1302 }
1303 }
1304 }
1305 else if ($this->extra && is_string($this->extra)) {
1306 $output .= " AND ($this->extra)";
1307 }
1308 }
1309 return $output;
1310 }
1311
1312 /**
1313 * Ensure that input is db safe. We only check strings and ints tho
1314 * so something that needs floats in their joins needs to do their
1315 * own type checking.
1316 */
1317 function db_safe($input) {
1318 if (is_array($input)) {
1319 $output = array();
1320 foreach ($input as $value) {
1321 if (empty($info['numeric'])) {
1322 $output[] = db_escape_string($value);
1323 }
1324 else {
1325 $output[] = intval($value);
1326 }
1327 }
1328 }
1329 else if (empty($info['numeric'])) {
1330 $output = db_escape_string($input);
1331 }
1332 else {
1333 $output = intval($input);
1334 }
1335
1336 return $output;
1337 }
1338 }
1339
1340 /**
1341 * @}
1342 */
1343
1344 // Declare API compatibility on behalf of core modules:
1345
1346 /**
1347 * Implementation of hook_views_api().
1348 *
1349 * This one is used as the base to reduce errors when updating.
1350 */
1351 function views_views_api() {
1352 return array(
1353 'api' => 2,
1354 'path' => drupal_get_path('module', 'views') . '/modules',
1355 );
1356 }
1357
1358 function aggregator_views_api() { return views_views_api(); }
1359
1360 function book_views_api() { return views_views_api(); }
1361
1362 function comment_views_api() { return views_views_api(); }
1363
1364 function locale_views_api() { return views_views_api(); }
1365
1366 function filter_views_api() { return views_views_api(); }
1367
1368 function node_views_api() { return views_views_api(); }
1369
1370 function poll_views_api() { return views_views_api(); }
1371
1372 function profile_views_api() { return views_views_api(); }
1373
1374 function search_views_api() { return views_views_api(); }
1375
1376 function statistics_views_api() { return views_views_api(); }
1377
1378 function system_views_api() { return views_views_api(); }
1379
1380 function taxonomy_views_api() { return views_views_api(); }
1381
1382 function translation_views_api() { return views_views_api(); }
1383
1384 function upload_views_api() { return views_views_api(); }
1385
1386 function user_views_api() { return views_views_api(); }
1387
1388 function contact_views_api() { return views_views_api(); }