#633482 by dagmar: pre_execute() method needs to be called on exposed forms.
[project/views.git] / includes / handlers.inc
CommitLineData
013538bb
EM
1<?php
2// $Id$
3/**
4 * @file handlers.inc
5 * Defines the various handler objects to help build and display views.
6 */
7
8/**
021885c3 9 * Instantiate and construct a new handler
021885c3 10 */
fe44beb7 11function _views_create_handler($definition, $type = 'handler') {
238f7347 12// vpr('Instantiating handler ' . $definition['handler']);
fe44beb7
EM
13 if (empty($definition['handler'])) {
14 return;
15 }
16
17 if (!class_exists($definition['handler']) && !views_include_handler($definition, $type)) {
99c8e8b1
EM
18 return;
19 }
20
021885c3 21 $handler = new $definition['handler'];
c60d618c 22 $handler->set_definition($definition);
725bd2c9 23 // let the handler have something like a constructor.
fe44beb7
EM
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 */
35function 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;
021885c3 39 }
fe44beb7
EM
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;
725bd2c9 45 }
021885c3 46
fe44beb7
EM
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']);
021885c3
EM
82}
83
84/**
85 * Prepare a handler's data by checking defaults and such.
021885c3
EM
86 */
87function _views_prepare_handler($definition, $data, $field) {
4d3d2243 88 foreach (array('group', 'title', 'title short', 'help', 'real field') as $key) {
ae6c9b86
EM
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 }
021885c3
EM
98 }
99 }
100
101 return _views_create_handler($definition);
102}
103
104/**
fe44beb7
EM
105 * Fetch the handler data from cache.
106 */
107function views_fetch_handler_data($handler = NULL) {
108 static $cache = NULL;
109 if (!isset($cache)) {
ef3e937a 110 $start = views_microtime();
fe44beb7
EM
111
112 $cache = views_discover_handlers();
113
ef3e937a 114 vpr('Views handlers build time: ' . (views_microtime() - $start) * 1000 . ' ms');
fe44beb7
EM
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 */
133function 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/**
021885c3 167 * Fetch a handler to join one table to a primary table from the data cache
021885c3 168 */
ee23afa2 169function views_get_table_join($table, $base_table) {
021885c3 170 $data = views_fetch_data($table);
ee23afa2
EM
171 if (isset($data['table']['join'][$base_table])) {
172 $h = $data['table']['join'][$base_table];
2d3898d7
EM
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'])) {
ee23afa2 187 $handler->definition['left_table'] = $base_table;
2d3898d7
EM
188 }
189
021885c3 190 if (isset($h['arguments'])) {
b207ba28 191 call_user_func_array(array(&$handler, 'construct'), $h['arguments']);
021885c3 192 }
2d3898d7
EM
193 else {
194 $handler->construct();
195 }
196
021885c3
EM
197 return $handler;
198 }
199 // DEBUG -- identify missing handlers
ee23afa2 200 vpr("Missing join: $table $base_table");
021885c3
EM
201}
202
203/**
86ed07d8 204 * Base handler, from which all the other handlers are derived.
013538bb
EM
205 * It creates a common interface to create consistency amongst
206 * handlers and data.
207 *
013538bb 208 * This class would be abstract in PHP5, but PHP4 doesn't understand that.
86ed07d8 209 *
11d03592
EM
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.
013538bb 228 */
cffc1056 229class views_handler extends views_object {
013538bb 230 /**
86ed07d8 231 * init the handler with necessary data.
013538bb
EM
232 * @param $view
233 * The $view object this handler is attached to.
5ad6fb04 234 * @param $options
013538bb
EM
235 * The item from the database; the actual contents of this will vary
236 * based upon the type of handler.
237 */
1008b7ff 238 function init(&$view, $options) {
013538bb 239 $this->view = &$view;
cb2cdc11 240 $this->unpack_options($this->options, $options);
013538bb 241
013538bb 242 // This exist on most handlers, but not all. So they are still optional.
1008b7ff
EM
243 if (isset($options['table'])) {
244 $this->table = $options['table'];
013538bb
EM
245 }
246
38b3122d
EM
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
1008b7ff
EM
255 if (isset($options['field'])) {
256 $this->field = $options['field'];
cffc1056 257 if (!isset($this->real_field)) {
1008b7ff 258 $this->real_field = $options['field'];
cffc1056 259 }
013538bb
EM
260 }
261
7f56fb27 262 $this->query = &$view->query;
013538bb
EM
263 }
264
265 /**
4191b1df
EM
266 * Return a string representing this handler's name in the UI.
267 */
4d3d2243
EM
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));
4191b1df
EM
271 }
272
273 /**
013538bb
EM
274 * Provide a form for setting options.
275 */
3a69a04c 276 function options_form(&$form, &$form_state) { }
86ed07d8 277
013538bb
EM
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 /**
8881fd4d
EM
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 /**
d3887131
EM
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
70b45fc4
EM
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 /**
d3887131
EM
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() { }
4191b1df 346
7ae4dc41
EM
347 /**
348 * Check whether current user has access to this handler.
349 *
350 * @return boolean
4191b1df 351 */
7ae4dc41 352 function access() {
fa774b18
EM
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
7ae4dc41
EM
360 return TRUE;
361 }
d3887131
EM
362
363 /**
0a5243db
EM
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 /**
4191b1df
EM
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.
0d0ed51a 387 if (empty($this->view->relationship[$relationship])) {
4191b1df
EM
388 return;
389 }
390
391 // Check to see if the relationship has already processed. If not, then we
392 // cannot process it.
0d0ed51a 393 if (empty($this->view->relationship[$relationship]->alias)) {
4191b1df
EM
394 return;
395 }
396
397 // Finally!
0d0ed51a 398 $this->relationship = $this->view->relationship[$relationship]->alias;
4191b1df
EM
399 }
400
401 /**
013538bb
EM
402 * Add this handler into the query.
403 *
404 * If we were using PHP5, this would be abstract.
405 */
406 function query() { }
cffc1056
EM
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() {
1146ee98 413 if (!isset($this->table_alias)) {
455d2315 414 if (!method_exists($this->query, 'ensure_table')) { vpr_trace(); exit; }
06f6fd84 415 $this->table_alias = $this->query->ensure_table($this->table, $this->relationship);
cffc1056
EM
416 }
417 return $this->table_alias;
418 }
3a69a04c
EM
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; }
bb770a1b
EM
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 */
618449fb 445 function accept_exposed_input($input) { return TRUE; }
f4a62619
EM
446
447 /**
b74a5caa
EM
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 /**
f4a62619
EM
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.
b407c95e
EM
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 }
f4a62619 473 }
0d0ed51a
EM
474
475 /**
f0318253
EM
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 /**
0d0ed51a
EM
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() { }
cb2cdc11
EM
493}
494
495/**
ca78ec49 496 * This many to one helper object is used on both arguments and filters.
538c7cf5
EM
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.
11d03592
EM
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 *
013538bb 508 */
ca78ec49
EM
509class views_many_to_one_helper {
510 function views_many_to_one_helper(&$handler) {
511 $this->handler = &$handler;
512 }
013538bb 513
cb2cdc11
EM
514 function option_definition(&$options) {
515 $options['reduce_duplicates'] = array('default' => FALSE);
516 }
517
ca78ec49
EM
518 function options_form(&$form, &$form_state) {
519 $form['reduce_duplicates'] = array(
520 '#type' => 'checkbox',
521 '#title' => t('Reduce duplicates'),
1c33b94f 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.'),
ca78ec49
EM
523 '#default_value' => !empty($this->handler->options['reduce_duplicates']),
524 );
525 }
0a5243db
EM
526
527 /**
ca78ec49
EM
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();
013538bb 531 */
ca78ec49
EM
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;
8a718296 538 }
013538bb 539 }
013538bb 540
013538bb 541 /**
50e8b0ab
EM
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])) {
ee23afa2 563 $base_table = $this->handler->query->base_table;
50e8b0ab
EM
564 }
565 else {
ee23afa2 566 $base_table = $this->handler->query->relationships[$relationship]['base'];
50e8b0ab
EM
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);
ee23afa2
EM
572 while ($r_join->left_table != $base_table) {
573 $r_join = views_get_table_join($r_join->left_table, $base_table);
50e8b0ab 574 }
50e8b0ab
EM
575 // If we found that there are tables in between, add the relationship.
576 if ($r_join->table != $join->table) {
bca64c83 577 $relationship = $this->handler->query->add_relationship($this->handler->table . '_' . $r_join->table, $r_join, $r_join->table, $this->handler->relationship);
50e8b0ab
EM
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.
83076935
EM
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 }
50e8b0ab
EM
591
592 return $alias;
593 }
594
595 function get_join() {
f4a62619 596 return $this->handler->get_join();
50e8b0ab
EM
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 /**
ca78ec49
EM
637 * Override ensure_my_table so we can control how this joins in.
638 * The operator actually has influence over joining.
013538bb 639 */
ca78ec49
EM
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;
ca78ec49 644 if ($this->handler->operator == 'or' && empty($this->handler->options['reduce_duplicates'])) {
2440bfa7 645 if (empty($this->handler->options['add_table']) && empty($this->handler->view->many_to_one_tables[$field])) {
1f4cbd48
EM
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);
ca78ec49
EM
651 $this->handler->view->many_to_one_tables[$field] = $this->handler->value;
652 }
653 else {
50e8b0ab 654 $join = $this->get_join();
1f4cbd48 655 $join->type = 'LEFT';
ca78ec49
EM
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 }
013538bb 668
50e8b0ab 669 $this->handler->table_alias = $this->add_table($join);
ca78ec49 670 }
50e8b0ab 671
ca78ec49
EM
672 return $this->handler->table_alias;
673 }
0225248a 674
ca78ec49
EM
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) {
50e8b0ab 680 $join = $this->get_join();
1f4cbd48
EM
681 if ($this->handler->operator == 'and') {
682 $join->type = 'INNER';
683 }
ca78ec49
EM
684 $join->extra = array(
685 array(
686 'field' => $this->handler->real_field,
687 'value' => $value,
688 'numeric' => !empty($this->handler->definition['numeric']),
689 ),
690 );
48293eb6
EM
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])) {
f71554f5
EM
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;
48293eb6 697 }
f71554f5 698 $this->handler->view->many_to_one_aliases[$field][$value] = $this->handler->table . '_value_' . ($this->handler->view->many_to_one_count[$this->handler->table]++);
48293eb6
EM
699 }
700 $alias = $this->handler->table_aliases[$value] = $this->add_table($join, $this->handler->view->many_to_one_aliases[$field][$value]);
ca78ec49
EM
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.
50e8b0ab 711 $join = $this->get_join();
ca78ec49
EM
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 }
0225248a 722
50e8b0ab 723 $this->handler->table_alias = $this->add_table($join);
ca78ec49 724 }
0225248a 725 }
ca78ec49 726 return $this->handler->table_alias;
0225248a 727 }
0225248a 728
ca78ec49
EM
729 function add_filter() {
730 if (empty($this->handler->value)) {
8a718296 731 return;
0a5243db 732 }
ca78ec49
EM
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;
9e948ec4
EM
741 }
742
ca78ec49 743 $placeholder = !empty($this->handler->definition['numeric']) ? '%d' : "'%s'";
b57c309a 744
ca78ec49
EM
745 if ($operator == 'not') {
746 $this->handler->query->add_where($options['group'], "$field IS NULL");
9e948ec4 747 }
ca78ec49 748 else if ($operator == 'or' && empty($options['reduce_duplicates'])) {
50e8b0ab
EM
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 }
013538bb 757 }
ca78ec49
EM
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 }
01c6ed1e 764
ca78ec49
EM
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);
01c6ed1e 769 }
01c6ed1e
EM
770 }
771}
772
8a718296
EM
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.
013538bb 784 */
8a718296
EM
785function views_break_phrase($str, $filter = NULL) {
786 if (!$filter) {
ca78ec49 787 $filter = new stdClass();
3a69a04c 788 }
878b28f4
EM
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
8a718296
EM
804 if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str)) {
805 // The '+' character in a query string may be parsed as ' '.
806 $filter->operator = 'or';
ca78ec49 807 $filter->value = preg_split('/[+ ]/', $str);
bb770a1b 808 }
8a718296
EM
809 else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str)) {
810 $filter->operator = 'and';
ca78ec49 811 $filter->value = explode(',', $str);
3a69a04c
EM
812 }
813
eca7ad62 814 // Keep an 'error' value if invalid strings were given.
0c4b06c1 815 if (!empty($str) && (empty($filter->value) || !is_array($filter->value))) {
eca7ad62 816 $filter->value = array(-1);
0c4b06c1 817 return $filter;
eca7ad62
EM
818 }
819
83076935
EM
820 // Doubly ensure that all values are numeric only.
821 foreach ($filter->value as $id => $value) {
822 $filter->value[$id] = intval($value);
823 }
9d99573a 824
8a718296
EM
825 return $filter;
826}
52208794 827
80f01edd
EM
828// --------------------------------------------------------------------------
829// Date helper functions
830
831/**
832 * Figure out what timezone we're in; needed for some date manipulations.
833 */
834function 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
12ff86f2
EM
844 if (in_array($GLOBALS['db_type'], array('mysql', 'mysqli', 'pgsql'))) {
845 $offset = '+00:00';
80f01edd
EM
846 static $already_set = false;
847 if (!$already_set) {
12ff86f2
EM
848 if ($GLOBALS['db_type'] == 'pgsql') {
849 db_query("SET TIME ZONE INTERVAL '$offset' HOUR TO MINUTE");
80f01edd 850 }
12ff86f2
EM
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
80f01edd
EM
855 $already_set = true;
856 }
bca64c83 857 }
80f01edd
EM
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
12ff86f2 868 * The type of date field, 'int' or 'datetime'.
80f01edd
EM
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 */
876function 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)) {
62749ef0 902 $field = "($field + INTERVAL '$offset SECONDS')";
80f01edd
EM
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 */
924function 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(
60eaa7a9 942 'Y' => 'YYYY',
80f01edd
EM
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 */
970function 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 }
fe44beb7 1019}
80f01edd 1020
fe44beb7
EM
1021/**
1022 * Implementation of hook_views_handlers() to register all of the basic handlers
1023 * views uses.
1024 */
1025function 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 ),
d8c64e8b
EM
1084 'views_handler_field_custom' => array(
1085 'parent' => 'views_handler_field',
1086 ),
aae33021
EM
1087 'views_handler_field_counter' => array(
1088 'parent' => 'views_handler_field',
1089 ),
fe44beb7
EM
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 ),
dcb189ee
EM
1104 'views_handler_filter_boolean_operator_string' => array(
1105 'parent' => 'views_handler_filter_boolean_operator',
1106 ),
fe44beb7
EM
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 ),
e15188ee
EM
1113 'views_handler_filter_float' => array(
1114 'parent' => 'views_handler_filter_numeric',
1115 ),
fe44beb7
EM
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 );
80f01edd 1147}
fe44beb7
EM
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 */
1203class 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'])) {
6ed05843 1228 $this->extra_type = strtoupper($this->definition['extra type']);
fe44beb7
EM
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) {
1b4ddafa
EM
1239 if (empty($this->definition['table formula'])) {
1240 $right_table = "{" . $this->table . "}";
1241 }
1242 else {
1243 $right_table = $this->definition['table formula'];
1244 }
1245
c9e3cc14 1246 if ($this->left_table) {
24b5971e 1247 $left = $query->get_table_info($this->left_table);
1b4ddafa 1248 $left_field = "$left[alias].$this->left_field";
24b5971e
EM
1249 }
1250 else {
1251 // This can be used if left_field is a formula or something. It should be used only *very* rarely.
1b4ddafa 1252 $left_field = $this->left_field;
24b5971e 1253 }
1b4ddafa
EM
1254
1255 $output = " $this->type JOIN $right_table $table[alias] ON $left_field = $table[alias].$this->field";
fe44beb7
EM
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 */
1351function views_views_api() {
1352 return array(
1353 'api' => 2,
1354 'path' => drupal_get_path('module', 'views') . '/modules',
1355 );
1356}
1357
9299118b
EM
1358function aggregator_views_api() { return views_views_api(); }
1359
793cef59
EM
1360function book_views_api() { return views_views_api(); }
1361
fe44beb7
EM
1362function comment_views_api() { return views_views_api(); }
1363
e4fabcf4
EM
1364function locale_views_api() { return views_views_api(); }
1365
2ef7bd19
EM
1366function filter_views_api() { return views_views_api(); }
1367
fe44beb7
EM
1368function node_views_api() { return views_views_api(); }
1369
1370function poll_views_api() { return views_views_api(); }
1371
1372function profile_views_api() { return views_views_api(); }
1373
1374function search_views_api() { return views_views_api(); }
1375
1376function statistics_views_api() { return views_views_api(); }
1377
1378function system_views_api() { return views_views_api(); }
1379
1380function taxonomy_views_api() { return views_views_api(); }
1381
74274a93
EM
1382function translation_views_api() { return views_views_api(); }
1383
fe44beb7
EM
1384function upload_views_api() { return views_views_api(); }
1385
1386function user_views_api() { return views_views_api(); }
ccca435e
EM
1387
1388function contact_views_api() { return views_views_api(); }