views.module 58.3 KB
Newer Older
1
<?php
2
// $Id$
3

4
function views_init() {
5
6
7
8
9
  // hook init is called even on cached pages, but we don't want to
  // actually do anything in that case.
  if (!function_exists('drupal_get_path')) {
    return;
  }
10
11
12
13
14
15
16
  // Load all our module 'on behalfs'.
  $path = drupal_get_path('module', 'views') . '/modules';
  $files = system_listing('views_.*\.inc$', $path, 'name', 0);

  foreach($files as $file) {
    // The filename format is very specific. It must be views_MODULENAME.inc
    $module = substr_replace($file->name, '', 0, 6);
17
    if (module_exists($module)) {
18
      require_once("./$file->filename");
19
20
21
22
    }
  }
}

23
// ---------------------------------------------------------------------------
24
// Acquire Views Data
25

26
/**
27
28
29
30
 * Return the arguments array; construct one if we haven't already. The
 * array is cached in a global, safely named variable so that arguments
 * are only constructed once per run.
 */
31
function _views_get_arguments($titles = false) {
32
  static $views_arguments;
33
  global $locale;
merlinofchaos's avatar
merlinofchaos committed
34

35
  if (!$views_arguments) {
36
    $data = cache_get("views_arguments:$locale", 'cache');
37
38
    $cache = unserialize($data->data);
    if (is_array($cache)) {
39
      $views_arguments = $cache;
40
41
    }
    else {
42
      $arguments = module_invoke_all('views_arguments');
43
      foreach ($arguments as $name => $arg) {
44
45
46
47
48
49
50
51
        if ($arg['option'] && !is_array($arg['option'])) {
          if ($arg['option'] == 'string' || $arg['option'] == 'integer') {
            $arg['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
          }
          else {
            $arg['option'] = array('#type' => 'select', '#options' => $arg['option']);
          }
        }
52
53
        $views_arguments['base'][$name] = $arg['name'];
        $views_arguments['title'][$name] = $arg;
54
      }
55
      $cache = $views_arguments;
56
      cache_set("views_arguments:$locale", 'cache', serialize($cache));
merlinofchaos's avatar
merlinofchaos committed
57
58
    }
  }
59
  return ($titles ? $views_arguments['base'] : $views_arguments['title']);
merlinofchaos's avatar
merlinofchaos committed
60
}
61

62
/**
63
64
65
 * Constructs the full table information array. Caches it into a global array
 * so that it will only be called once per run.
 */
66
function _views_get_tables($full = false) {
67
  static $views_tables;
68
  global $locale;
merlinofchaos's avatar
merlinofchaos committed
69

70
  if (!$views_tables) {
71
    $data = cache_get("views_tables:$locale", 'cache');
72
    $cache = unserialize($data->data);
merlinofchaos's avatar
merlinofchaos committed
73

74
    if (is_array($cache)) {
75
      $views_tables = $cache;
merlinofchaos's avatar
merlinofchaos committed
76
    }
77
    else {
78
79
      $table_data = module_invoke_all('views_tables');
      $views_tables['tables'] = $table_data;
80
81
82

      foreach ($table_data as $name => $table) {
        if (is_array($table['filters'])) {
83
          foreach ($table['filters'] as $filter => $data) {
84
            $data['table'] = $name;
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
            // translate for deprecated APIs...
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            if ($data['list']) {
              $data['value'] = array('#type' => 'select', '#options' => $data['list']);
              if ($data['list-type'] != 'select') {
                $data['value']['#multiple'] = TRUE;
              }
            }
            else if (!$data['value']) {
              $data['value'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
            }
103
104
            $views_tables['filters']['titles']["$name.$filter"] = $data['name'];
            $views_tables['filters']['base']["$name.$filter"] = $data;
105
106
107
          }
        }
        if (is_array($table['fields'])) {
108
          foreach ($table['fields'] as $field => $data) {
109
110
111
112
113
114
115
116
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
117
            $data['table'] = $name;
118
119
            $views_tables['fields']['titles']["$name.$field"] = $data['name'];
            $views_tables['fields']['base']["$name.$field"] = $data;
120
121
122
          }
        }
        if (is_array($table['sorts'])) {
123
          foreach ($table['sorts'] as $field => $data) {
124
            $data['table'] = $name;
125
126
127
128
129
130
131
132
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
133
134
            $views_tables['sorts']['titles']["$name.$field"] = $data['name'];
            $views_tables['sorts']['base']["$name.$field"] = $data;
135
136
          }
        }
merlinofchaos's avatar
merlinofchaos committed
137
      }
138
      cache_set("views_tables:$locale", 'cache', serialize($views_tables));
merlinofchaos's avatar
merlinofchaos committed
139
140
    }
  }
141
  return ($full ? $views_tables : $views_tables['tables']);
merlinofchaos's avatar
merlinofchaos committed
142
143
}

144
/**
145
146
147
 * Gets the filter information; if it doesn't exist, call the function
 * that constructs all that.
 */
merlinofchaos's avatar
merlinofchaos committed
148
function _views_get_filters($titles = false) {
149
150
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['filters']['titles'] : $table_data['filters']['base']);
merlinofchaos's avatar
merlinofchaos committed
151
152
}

153
/**
154
155
156
 * Gets the field information; if it doesn't exist, call the function
 * that constructs all that.
 */
merlinofchaos's avatar
merlinofchaos committed
157
function _views_get_fields($titles = false) {
158
159
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['fields']['titles'] : $table_data['fields']['base']);
merlinofchaos's avatar
merlinofchaos committed
160
161
}

162
/**
163
164
165
 * Gets the sort information; if it doesn't exist, call the function
 * that constructs all that.
 */
merlinofchaos's avatar
merlinofchaos committed
166
function _views_get_sorts($titles = false) {
167
168
169
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['sorts']['titles'] : $table_data['sorts']['base']);
}
merlinofchaos's avatar
merlinofchaos committed
170

171
/**
172
173
174
 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
 */
function views_invalidate_cache() {
175
  cache_clear_all('views_', 'cache', true);
merlinofchaos's avatar
merlinofchaos committed
176
177
}

178
/**
179
180
181
182
 * Ensures that views have legitimate information; a bit more is stored on
 * the $view object than is in the database, and this isn't necessarily
 * set when a view is constructed externally.
 */
merlinofchaos's avatar
merlinofchaos committed
183
function views_sanitize_view(&$view) {
184
  _views_check_arrays($view); // so reference works.
185
  foreach ($view->field as $i => $field) {
merlinofchaos's avatar
merlinofchaos committed
186
187
188
189
    if (!isset($view->field[$i]['id'])) {
      $view->field[$i]['id'] = $view->field[$i]['fullname'] = "$field[tablename].$field[field]";
      $view->field[$i]['queryname'] = "$field[tablename]_$field[field]";
    }
190
  }
191
192

  foreach ($view->filter as $i => $filter) {
merlinofchaos's avatar
merlinofchaos committed
193
194
195
    if (!isset($view->filter[$i]['id'])) {
      $view->filter[$i]['id'] = $view->filter[$i]['field'] = "$filter[tablename].$filter[field]";
    }
196
  }
197
198

  foreach ($view->exposed_filter as $i => $exposed_filter) {
merlinofchaos's avatar
merlinofchaos committed
199
200
201
    if (!isset($view->exposed_filter[$i]['id'])) {
      $view->exposed_filter[$i]['id'] = $view->exposed_filter[$i]['field'] = "$exposed_filter[tablename].$exposed_filter[field]";
    }
202
  }
203
204

  foreach ($view->sort as $i => $sort) {
merlinofchaos's avatar
merlinofchaos committed
205
206
207
    if (!isset($view->sort[$i]['id'])) {
      $view->sort[$i]['id'] = $view->sort[$i]['field'] = "$sort[tablename].$sort[field]";
    }
208
209
210
  }

  foreach ($view->argument as $i => $argument) {
merlinofchaos's avatar
merlinofchaos committed
211
212
213
    if (!isset($view->argument[$i]['id'])) {
      $view->argument[$i]['id'] = $view->argument[$i]['type'];
    }
214
  }
215
216
}

217
/**
218
219
 * Build default view information from all modules and cache it.
 */
merlinofchaos's avatar
merlinofchaos committed
220
function _views_get_default_views() {
221
  static $views_default_views;
222
  global $locale;
merlinofchaos's avatar
merlinofchaos committed
223

224
  if (!$views_default_views) {
225
    $data = cache_get("views_default_views:$locale", 'cache');
226
227
228
    $cache = unserialize($data->data);

    if (is_array($cache)) {
229
      $views_default_views = $cache;
230
231
    }
    else {
232
233
      // We have to make sure table data is built in order to be sure about providers.
      $tables = array_keys(_views_get_tables());
234

235
236
      $views = module_invoke_all('views_default_views');
      $views_default_views = array();
237
238
      foreach ($views as $i => $view) {
        if (!is_array($view->requires) || !array_diff($view->requires, $tables)) {
merlinofchaos's avatar
merlinofchaos committed
239
          views_sanitize_view($view);
240
          $views_default_views[$i] = $view;
241
        }
242
      }
243
      cache_set("views_default_views:$locale", 'cache', serialize($views_default_views));
merlinofchaos's avatar
merlinofchaos committed
244
245
    }
  }
246
  return $views_default_views;
merlinofchaos's avatar
merlinofchaos committed
247
}
248

249
250
251
252
253
254
255
256
257
258
/**
 * Return the style plugins; construct one if we haven't already. The
 * array is cached in a static variable so that arguments
 * are only constructed once per run.
 */
function _views_get_style_plugins($titles = false) {
  static $views_style_plugins;
  global $locale;

  if (!$views_style_plugins) {
259
    $data = cache_get("views_style_plugins:$locale", 'cache');
260
261
262
263
264
265
266
    $cache = unserialize($data->data);
    if (is_array($cache)) {
      $views_style_plugins = $cache;
    }
    else {
      $arguments = module_invoke_all('views_style_plugins');
      foreach ($arguments as $name => $arg) {
267
268
269
        if (!isset($arg['summary_theme'])) {
          $arg['summary_theme'] = 'views_summary';
        }
270
271
272
273
        $views_style_plugins['title'][$name] = $arg['name'];
        $views_style_plugins['base'][$name] = $arg;
      }
      $cache = $views_style_plugins;
274
      cache_set("views_style_plugins:$locale", 'cache', serialize($cache));
275
276
277
278
279
    }
  }
  return ($titles ? $views_style_plugins['title'] : $views_style_plugins['base']);
}

280
281
282
// ---------------------------------------------------------------------------
// Drupal Hooks

283
/**
284
285
 * Implementation of hook_help()
 */
286
287
function views_help($section) {
  switch ($section) {
288
    case 'admin/help#views':
289
      return t('The views module creates customized views of node lists.');
290
  }
291
292
}

293
/**
294
295
 * Implementation of hook_menu()
 */
296
297
function views_menu($may_cache) {
  $items = array();
298
  global $locale;
299
300

  if ($may_cache) {
301
302
    // Invalidate the views cache to ensure that views data gets rebuilt.
    // This is the best way to tell that module configuration has changed.
303
    if (arg(0) == 'admin' && arg(1) == 'modules') {
304
305
      views_invalidate_cache();
    }
306

307
    $result = db_query("SELECT * FROM {view_view} WHERE page = 1");
308
309
    $views_with_inline_args = array();

310
    while ($view = db_fetch_object($result)) {
311
312
      // unpack the array
      $view->access = ($view->access ? explode(', ', $view->access) : array());
313
314
315
316

      // This happens before the next check; even if it's put off for later
      // it is still used.
      $used[$view->name] = true;
merlinofchaos's avatar
merlinofchaos committed
317

318
      if (strrpos($view->url, '$arg')) {
319
320
321
        $arg_result = db_query("SELECT * FROM {view_argument} WHERE vid = %d", $view->vid);
        while ($view->argument[] = db_fetch_array($arg_result));
        array_pop($view->argument); // get rid of the NULL at the end.
322
        $views_with_inline_args[$view->name] = $view;
323
324
        continue;
      }
325
      _views_create_menu_item($items, $view, $view->url);
326
    }
327
    $default_views = _views_get_default_views();
328
329
    $views_status = variable_get('views_defaults', array());

330
    foreach ($default_views as $name => $view) {
merlinofchaos's avatar
merlinofchaos committed
331
      if ($view->page && !$used[$name] &&
332
       ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
333

334
        if (strrpos($view->url, '$arg')) {
335
          $views_with_inline_args[$view->name] = $view;
336
337
          continue;
        }
338

339
        _views_create_menu_item($items, $view, $view->url);
340
341
      }
    }
342
    cache_set("views_with_inline_args:$locale", 'cache', serialize($views_with_inline_args));
343
344
  }
  else {
345
    $data = cache_get("views_with_inline_args:$locale", 'cache');
346
347
348
349
    $views = unserialize($data->data);
    if (is_array($views)) {
      foreach ($views as $view) {
        // Do substitution on args.
350
        $view_args = array();
351
        $menu_path = array();
352
353
354
355
        foreach (explode('/', $view->url) as $num => $element) {
          if ($element == '$arg') {
            $menu_path[] = arg($num);
            $view_args[] = arg($num);
356
            $view->args[] = arg($num);
357
358
          }
          else {
359
            $menu_path[] = $element;
360
361
362
          }
        }
        $path = implode('/', $menu_path);
363
        _views_create_menu_item($items, $view, $path, MENU_CALLBACK, $view_args);
364
      }
365
    }
366
367
368
369
  }
  return $items;
}

370
371
372
/**
 * Helper function to add a menu item for a view.
 */
373
function _views_create_menu_item(&$items, $view, $path, $local_task_type = MENU_NORMAL_ITEM, $args = array()) {
374
375
376
377
378
379
380
  static $roles = NULL;
  if ($roles == NULL) {
    global $user;
    $roles = array_keys($user->roles);
  }
  $title = views_get_title($view, 'menu');
  $type = _views_menu_type($view);
381
382
383
  if ($type == MENU_LOCAL_TASK || $type == MENU_DEFAULT_LOCAL_TASK) {
    $weight = $view->menu_tab_weight;
  }
384
  $access = !$view->access || array_intersect($view->access, $roles);
385
  $items[] = _views_menu_item($path, $title, $view, $args, $access, $type, $weight);
merlinofchaos's avatar
merlinofchaos committed
386

387
  if ($type == MENU_DEFAULT_LOCAL_TASK) {
388
    $items[] = _views_menu_item(dirname($path), $title, $view, $args, $access, $local_task_type, $weight);
389
390
391
  }
}

392
393
394
/**
 * Helper function to create a menu item for a view.
 */
395
396
function _views_menu_item($path, $title, $view, $args, $access, $type, $weight = NULL) {
  array_unshift($args, $view->name);
397
  $retval = array('path' => $path,
398
399
400
    'title' => $title,
    'callback' => 'views_view_page',
    'callback arguments' => $args,
401
    'access' => user_access('access content') && $access,
402
403
    'type' => $type,
  );
404
405
406
407
  if ($weight !== NULL) {
    $retval['weight'] = $weight;
  }
  return $retval;
408
409
}

410
411
412
/**
 * Determine what menu type a view needs to use.
 */
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
function _views_menu_type($view) {
  if ($view->menu) {
    if ($view->menu_tab_default) {
      $type = MENU_DEFAULT_LOCAL_TASK;
    }
    else if ($view->menu_tab) {
      $type = MENU_LOCAL_TASK;
    }
    else {
      $type = MENU_NORMAL_ITEM;
    }
  }
  else {
    $type = MENU_CALLBACK;
  }
  return $type;
}
430

431
/**
432
433
 * Implementation of hook_block()
 */
434
435
436
function views_block($op = 'list', $delta = 0) {
  $block = array();
  if ($op == 'list') {
437
    // Grab views from the database and provide them as blocks.
438
    $result = db_query("SELECT vid, block_title, page_title, name FROM {view_view} WHERE block = 1");
439
    while ($view = db_fetch_object($result)) {
440
      $block[$view->name]['info'] = views_get_title($view, 'block-info');
441
    }
442

443
    $default_views = _views_get_default_views();
444
445
    $views_status = variable_get('views_defaults', array());

446
    foreach ($default_views as $name => $view) {
447
448
449
      if (!isset($block[$name]) && $view->block &&
        ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
        $block[$name]['info'] = views_get_title($view, 'block');
450
      }
451
452
453
454
455
456
457
458
    }
    return $block;
  }
  else if ($op == 'view') {
    return views_view_block($delta);
  }
}

459
460
461
// ---------------------------------------------------------------------------
// View Construction

462
/**
463
464
465
 * Ensure that all the arrays in a view exist so we don't run into array
 * operations on a non-array error.
 */
merlinofchaos's avatar
merlinofchaos committed
466
function _views_check_arrays(&$view) {
merlinofchaos's avatar
merlinofchaos committed
467
  $fields = array('field', 'sort', 'argument', 'filter', 'exposed_filter', 'access');
468
469
470
471
472

  foreach($fields as $field) {
    if (!is_array($view->$field)) {
      $view->$field = array();
    }
473
474
  }
  return $view;
475
476
}

477
/**
478
479
480
 * This function loads a view by name or vid; if not found in db, it looks
 * for a default view by that name.
 */
481
482
function views_get_view($view_name) {
  $view = _views_load_view($view_name);
483
  if ($view) {
merlinofchaos's avatar
merlinofchaos committed
484
    return $view;
485
  }
merlinofchaos's avatar
merlinofchaos committed
486

487
488
  if (is_int($view_name)) {
    return; // don't bother looking if view_name is an int!
489
  }
merlinofchaos's avatar
merlinofchaos committed
490

491
  $default_views = _views_get_default_views();
merlinofchaos's avatar
merlinofchaos committed
492

493
494
  if (isset($default_views[$view_name])) {
    return $default_views[$view_name];
495
  }
merlinofchaos's avatar
merlinofchaos committed
496
497
}

498
/**
499
 * This views a view by page, and should only be used as a callback.
500
501
502
503
504
505
506
507
 *
 * @param $view_name
 *   The name or id of the view to load
 * @param $args
 *   The arguments from the end of the url. Usually passed from the menu system.
 *
 * @return
 *   The view page.
508
 */
509
510
function views_view_page() {
  $args = func_get_args();
511
512
  $view_name = array_shift($args);
  $view = views_get_view($view_name);
513

514
515
516
517
  if (!$view) {
    drupal_not_found();
    exit;
  }
518

519
  $output = views_build_view('page', $view, $args, $view->use_pager, $view->nodes_per_page);
520
  if ($output === FALSE) {
521
522
523
524
    drupal_not_found();
    exit;
  }

525
  return $output;
526
527
}

528
/**
529
530
 * This views a view by block. Can be used as a callback or programmatically.
 */
531
function views_view_block($vid) {
532
  $view = views_get_view($vid);
533

534
  if (!$view || !$view->block) {
535
    return NULL;
536
  }
537

538
  global $user;
539
540
541
542
  if (!$user->roles) {
    return NULL;
  }

543
544
545
546
547
  $roles = array_keys($user->roles);
  if ($view->access && !array_intersect($roles, $view->access)) {
    return NULL;
  }

548
  $content = views_build_view('block', $view, array(), false, $view->nodes_per_block);
549
550
551
552
553
554
555
556
  if ($content) {
    $block['content'] = $content;
    $block['subject'] = views_get_title($view, 'block');
    return $block;
  }
  else {
    return NULL;
  }
557
558
}

559
/**
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
 * This builds the basic view.
 * @param $type
 *    'page' -- Produce output as a page, sent through theme.
 *      The only real difference between this and block is that
 *      a page uses drupal_set_title to change the page title.
 *    'block' -- Produce output as a block, sent through theme.
 *    'embed' -- Use this if you want to embed a view onto another page,
 *      and don't want any block or page specific things to happen to it.
 *    'result' -- return an $info array. The array contains:
 *      query: The actual query ran.
 *      countquery: The count query that would be run if limiting was required.
 *      summary: True if an argument was missing and a summary was generated.
 *      level: What level the missing argument was at.
 *      result: Database object you can use db_fetch_object on.
 *    'items' -- return info array as above, except instead of result,
 *      items: An array of objects containing the results of the query.
 * @param $view
 *   The actual view object. Use views_get_view() if you only have the name or
 *   vid.
 * @param $args
 *   args taken from the URL. Not relevant for many views. Can be null.
 * @param $use_pager
 *   If set, use a pager. Set this to the pager id you want it
 *   to use if you plan on using multiple pagers on a page. To go with the
584
585
 *   default setting, set to $view->use_pager. Note that the pager element
 *   id will be decremented in order to have the IDs start at 0.
586
587
588
589
590
591
592
 * @param $limit
 *   Required if $use_pager is set; if $limit is set and $use_pager is
 *   not, this will be the maximum number of records returned. This is ignored
 *   if using a view set to return a random result. To go with the default
 *   setting set to $view->nodes_per_page or $view->nodes_per_block. If
 *   $use_pager is set and this field is not, you'll get a SQL error. Don't
 *   do that!
593
594
595
596
 * @param $page
 *   $use_pager is false, and $limit is !0, $page tells it what page to start
 *   on, in case for some reason a particular section of view is needed,
 *   without paging on.
597
*/
598
function views_build_view($type, &$view, $args = array(), $use_pager = false, $limit = 0, $page = 0) {
599
600
601
602
603
  // Fix a number of annoying whines when NULL is passed in..
  if ($args == NULL) {
    $args = array();
  }

604
  $GLOBALS['current_view'] = &$view;
merlinofchaos's avatar
merlinofchaos committed
605

606
607
  $view->build_type = $type;
  $view->type = ($type == 'block' ? $view->block_type : $view->page_type);
608

609
610
  if ($view->view_args_php) {
    ob_start();
611
612
613
614
    $result = eval($view->view_args_php);
    if (is_array($result)) {
      $args = $result;
    }
615
616
617
    ob_end_clean();
  }

618
  $plugins = _views_get_style_plugins();
619
620
621
  if ($view->query) {
    $info['query'] = $view->query;
    $info['countquery'] = $view->countquery;
merlinofchaos's avatar
merlinofchaos committed
622

623
    if ($plugins[$view->type]['needs_table_header']) {
merlinofchaos's avatar
merlinofchaos committed
624
      $view->table_header = _views_construct_header($view, $fields);
625
    }
merlinofchaos's avatar
merlinofchaos committed
626
627
  }
  else {
628
    $path = drupal_get_path('module', 'views');
629
    require_once("./$path/views_query.inc");
630

merlinofchaos's avatar
merlinofchaos committed
631
    $info = _views_build_query($view, $args);
632
    if ($info['fail']) {
633
      return FALSE;
634
    }
merlinofchaos's avatar
merlinofchaos committed
635
636
  }

637
  // Run-time replacement so we can do cacheing
638
639
640
641
  $replacements = module_invoke_all('views_query_substitutions', $view);
  foreach ($replacements as $src => $dest) {
    $info['query'] = str_replace($src, $dest, $info['query']);
    $info['countquery'] = str_replace($src, $dest, $info['countquery']);
642

643
644
645
646
    if (is_array($info['args'])) {
      foreach ($info['args'] as $id => $arg) {
        $info['args'][$id] = str_replace($src, $dest, $arg);
      }
647
    }
648
  }
649

650
651
  $query = db_rewrite_sql($info['query'], 'node');

652
  if ($use_pager) {
653
    $cquery = db_rewrite_sql($info['countquery'], 'node', 'nid', $info['rewrite_args']);
654
    $result = pager_query($query, $limit, $use_pager - 1, $cquery, $info['args']);
655
    $view->total_rows = $GLOBALS['pager_total_items'][$use_pager - 1];
656
657
  }
  else {
658
    $result = ($limit ? db_query_range($query, $info['args'], $page * $limit, $limit) : db_query($query, $info['args']));
659
  }
660
  $view->num_rows = db_num_rows($result);
661
662
  if ($type == 'result') {
    $info['result'] = $result;
merlinofchaos's avatar
merlinofchaos committed
663
    return $info;
664
665
  }

merlinofchaos's avatar
merlinofchaos committed
666
  $items = array();
667
668
669
  while ($item = db_fetch_object($result)) {
    $items[] = $item;
  }
670
671
672
673
674

  if ($type == 'items') {
    $info['items'] = $items;
    return $info;
  }
675

676
677
678
  // Call a hook that'll let modules modify the view just before it is displayed.
  foreach (module_implements('views_pre_view') as $module) {
    $function = $module .'_views_pre_view';
679
    $output .= $function($view, $items);
680
681
  }

682
683
  $view->real_url = views_get_url($view, $args);

684
  $view->use_pager = $use_pager;
685
  $view->pager_limit = $limit;
686
  $output .= views_theme('views_view', $view, $type, $items, $info['level'], $args);
merlinofchaos's avatar
merlinofchaos committed
687

688
689
690
  // Call a hook that'll let modules modify the view just after it is displayed.
  foreach (module_implements('views_post_view') as $module) {
    $function = $module .'_views_post_view';
691
    $output .= $function($view, $items, $output);
692
693
  }

merlinofchaos's avatar
merlinofchaos committed
694
  return $output;
695
696
}

697
698
699
// ---------------------------------------------------------------------------
// Utility

merlinofchaos's avatar
merlinofchaos committed
700
/**
701
 * Easily theme any item to a view.
merlinofchaos's avatar
merlinofchaos committed
702
 * @param $function
703
704
705
706
707
708
709
 *   The name of the function to call.
 * @param $view
 *   The view being themed.
 */
function views_theme() {
  $args = func_get_args();
  $function = array_shift($args);
710
  $view = $args[0];
711
712
713
714
715
716
717
718
719
720

  if (!($func = theme_get_function($function . "_" . $view->name))) {
    $func = theme_get_function($function);
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

721
722
723
724
725
726
727
728
729
730
731
732
733
734
/**
 * Easily theme any item to a field name.
 * field name will be in the format of TABLENAME_FIELDNAME
 * You have to understand a bit about the views data to utilize this.
 *
 * @param $function
 *   The name of the function to call.
 * @param $field_name
 *   The field being themed.
 */
function views_theme_field() {
  $args = func_get_args();
  $function = array_shift($args);
  $field_name = array_shift($args);
735
  $view = array_pop($args);
736

737
738
739
740
  if (!($func = theme_get_function($function . '_' . $view->name . '_' . $field_name))) {
    if (!($func = theme_get_function($function . '_' . $field_name))) {
      $func = theme_get_function($function);
    }
741
742
743
744
745
746
747
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

748
/**
749
 * Figure out what timezone we're in; needed for some date manipulations.
750
 */
751
752
753
754
755
756
757
function _views_get_timezone() {
  global $user;
  if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
    $timezone = $user->timezone;
  }
  else {
    $timezone = variable_get('date_default_timezone', 0);
merlinofchaos's avatar
merlinofchaos committed
758
759
  }

760
761
762
763
  // set up the database timezone
  if (in_array($GLOBALS['db_type'], array('mysql', 'mysqli'))) {
    static $already_set = false;
    if (!$already_set) {
merlinofchaos's avatar
merlinofchaos committed
764
      if ($GLOBALS['db_type'] == 'mysqli' || version_compare(mysql_get_server_info(), '4.1.3', '>=')) {
765
766
767
768
769
770
        db_query("SET @@session.time_zone = '+00:00'");
      } 
      $already_set = true;
    }
  }

771
  return $timezone;
772
}
773
774
775
776
777
778
779

/**
 * Figure out what the URL of the view we're currently looking at is.
 */
function views_get_url($view, $args) {
  $url = $view->url;

780
781
782
783
784
  if (!empty($url)) {
    $where = 1;
    foreach ($args as $arg) {
      // This odd construct prevents us from strposing once there is no
      // longer an $arg to replace.
785
      if ($where && $where = strpos($url, '$arg')) {
786
787
788
789
790
        $url = substr_replace($url, $arg, $where, 4);
      }
      else {
        $url .= "/$arg";
      }
791
792
793
794
795
796
    }
  }

  return $url;
}

797
/**
798
799
 * Figure out what the title of a view should be.
 */
800
801
802
803
function views_get_title($view, $context = 'menu', $args = NULL) {
  if ($context == 'menu' && $view->menu_title)
    return $view->menu_title;

804
805
806
807
  if ($context == 'block-info') {
    return $view->description ? $view->description : $view->name;
  }

808
  if ($args === NULL) {
809
    $args = $view->args;
810
  }
811
812
813
814
815
816
817
818
819
820
  // Grab the title from the highest argument we got. If there is no such
  // title, track back until we find a title.

  if (is_array($args)) {
    $rargs = array_reverse(array_keys($args));
    foreach ($rargs as $arg_id) {
      if ($title = $view->argument[$arg_id]['title']) {
        break;
      }
    }
821
  }
822

823
  if (!$title && ($context == 'menu' || $context == 'page')) {
824
    $title = $view->page_title;
825
826
  }

827
  if (!$title) {
828
    $title = $view->block_title;
829
830
  }

831
832
833
834
  if (!$view->argument) {
    return $title;
  }

835
836
  $arginfo = _views_get_arguments();
  foreach ($view->argument as $i => $arg) {
837
838
839
    if (!isset($args[$i])) {
      break;
    }
840
    $argtype = $arg['type'];
841
842
843
844
    if ($arg['wildcard'] == $args[$i] && $arg['wildcard_substitution'] != '') {
      $title = str_replace("%" . ($i + 1), $arg['wildcard_substitution'], $title);
    }
    else if (function_exists($arginfo[$argtype]['handler'])) {
845
      // call the handler
846
      $rep = $arginfo[$argtype]['handler']('title', $args[$i], $argtype);
847
848
849
850
851
852
      $title = str_replace("%" . ($i + 1), $rep, $title);
    }
  }
  return $title;
}

853
/**
854
855
 * Determine whether or not a view is cacheable. A view is not cacheable if
 * there is some kind of user input or data required. For example, views
856
 * that need to restrict to the 'current' user, or any views that require
857
858
 * arguments or allow click-sorting are not cacheable.
 */
merlinofchaos's avatar
merlinofchaos committed
859
860
function _views_is_cacheable(&$view) {
  // views with arguments are immediately not cacheable.
861
  if (!empty($view->argument) || !empty($view->exposed_filter)) {
merlinofchaos's avatar
merlinofchaos committed
862
    return false;
863
  }
merlinofchaos's avatar
merlinofchaos committed
864
865
866
867

  $filters = _views_get_filters();

  foreach ($view->filter as $i => $filter) {
868
    if ($filters[$filter['field']]['cacheable'] == 'no')  {
merlinofchaos's avatar
merlinofchaos committed
869
      return false;
870
    }
merlinofchaos's avatar
merlinofchaos committed
871
  }
872

873
  foreach ($view->field as $i => $field) {
874
    if ($field['sortable']) {
875
      return false;
876
877
    }
  }
merlinofchaos's avatar
merlinofchaos committed
878
879
880
  return true;
}

881
882
883
// ---------------------------------------------------------------------------
// Database functions

884
/**
885
886
 * Provide all the fields in a view.
 */
887
function _views_view_fields() {
888
  return array('vid', 'name', 'description', 'access', 'page', 'page_title', 'page_header', 'page_header_format', 'page_footer', 'page_footer_format', 'page_empty', 'page_empty_format', 'page_type', 'use_pager', 'nodes_per_page', 'url', 'menu', 'menu_tab', 'menu_tab_default', 'menu_tab_weight', 'menu_title', 'block', 'block_title', 'block_use_page_header', 'block_header', 'block_header_format', 'block_use_page_footer', 'block_footer', 'block_footer_format', 'block_use_page_empty', 'block_empty', 'block_empty_format', 'block_type', 'nodes_per_block', 'block_more', 'url', 'breadcrumb_no_home', 'changed', 'query', 'countquery', 'view_args_php');
889
890
}

891
/**
892
893
 * Delete a view from the database.
 */
894
895
function _views_delete_view($view) {
  $view->vid = intval($view->vid);
896
  if (!$view->vid) {
897
    return;
898
  }
899

merlinofchaos's avatar
merlinofchaos committed
900
901
902
903
  db_query("DELETE FROM {view_view} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_sort} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_argument} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_tablefield} where vid=%d", $view->vid);
904
905
}

906
907
908
909
910
911
912
/**
 * Load a view from the database -- public version of the function.
 */
function views_load_view($arg) {
  return _views_load_view($arg);
}

913
/**
914
 * Load a view from the database.
915
 * (deprecated; use views_load_view in favor of this function).
916
 */
917
function _views_load_view($arg) {
918
919
920
921
922
  static $cache = array();
  $which = is_numeric($arg) ? 'vid' : 'name';
  if (isset($cache[$which][$arg])) {
    return $cache[$which][$arg];
  }
923

924
  $where = (is_numeric($arg) ? "v.vid =  %d" : "v.name = '%s'");
925
  $view = db_fetch_object(db_query("SELECT v.* FROM {view_view} v WHERE $where", $arg));
926

927
  if (!$view->name) {
928
    return NULL;
929
  }
930

931
932
  $view->access = ($view->access ? explode(', ', $view->access) : array());

933
934
935
  // load the sorting criteria too.
  $result = db_query("SELECT * FROM {view_sort} vs WHERE vid = $view->vid ORDER BY position ASC");

merlinofchaos's avatar
merlinofchaos committed
936
937
  $view->sort = array();
  while ($sort = db_fetch_array($result)) {
938
939
940
    if (substr($sort['field'], 0, 2) == 'n.') {
      $sort['field'] = 'node' . substr($sort['field'], 1);
    }
941
    $sort['id'] = $sort['field'];
merlinofchaos's avatar
merlinofchaos committed
942
    $view->sort[] = $sort;
943
944
  }

945
  $result = db_query("SELECT * FROM {view_argument} WHERE vid = $view->vid ORDER BY position ASC");
946
947
948

  $view->argument = array();
  while ($arg = db_fetch_array($result)) {
949
    $arg['id'] = $arg['type'];
950
951
952
    $view->argument[] = $arg;
  }

merlinofchaos's avatar