Projet

Général

Profil

Paste
Télécharger (40,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ctools / page_manager / page_manager.module @ 560c3060

1
<?php
2

    
3
/**
4
 * @file
5
 * The page manager module provides a UI and API to manage pages.
6
 *
7
 * It defines pages, both for system pages, overrides of system pages, and
8
 * custom pages using Drupal's normal menu system. It allows complex
9
 * manipulations of these pages, their content, and their hierarchy within
10
 * the site. These pages can be exported to code for superior revision
11
 * control.
12
 */
13

    
14
/**
15
 * Bit flag on the 'changed' value to tell us if an item was moved.
16
 */
17
define('PAGE_MANAGER_CHANGED_MOVED', 0x01);
18

    
19
/**
20
 * Bit flag on the 'changed' value to tell us if an item edited or added.
21
 */
22
define('PAGE_MANAGER_CHANGED_CACHED', 0x02);
23

    
24
/**
25
 * Bit flag on the 'changed' value to tell us if an item deleted.
26
 */
27
define('PAGE_MANAGER_CHANGED_DELETED', 0x04);
28

    
29
/**
30
 * Bit flag on the 'changed' value to tell us if an item has had its disabled status changed.
31
 */
32
define('PAGE_MANAGER_CHANGED_STATUS', 0x08);
33

    
34
// --------------------------------------------------------------------------
35
// Drupal hooks
36

    
37
/**
38
 * Implements hook_permission().
39
 */
40
function page_manager_permission() {
41
  return array(
42
    'use page manager' => array(
43
      'title' => t('Use Page Manager'),
44
      'description' => t("Allows users to use most of Page Manager's features, though restricts some of the most powerful, potentially site-damaging features. Note that even the reduced featureset still allows for enormous control over your website."),
45
      'restrict access' => TRUE,
46
    ),
47
    'administer page manager' => array(
48
      'title' => t('Administer Page Manager'),
49
      'description' => t('Allows complete control over Page Manager, i.e., complete control over your site. Grant with extreme caution.'),
50
      'restrict access' => TRUE,
51
    ),
52
  );
53

    
54
}
55

    
56
/**
57
 * Implements hook_ctools_plugin_directory() to let the system know
58
 * where our task and task_handler plugins are.
59
 */
60
function page_manager_ctools_plugin_directory($owner, $plugin_type) {
61
  if ($owner == 'page_manager') {
62
    return 'plugins/' . $plugin_type;
63
  }
64
  if ($owner == 'ctools' && $plugin_type == 'cache') {
65
    return 'plugins/' . $plugin_type;
66
  }
67
}
68

    
69
/**
70
 * Implements hook_ctools_plugin_type() to inform the plugin system that Page
71
 * Manager owns task, task_handler, and page_wizard plugin types.
72
 *
73
 * All of these are empty because the defaults all work.
74
 */
75
function page_manager_ctools_plugin_type() {
76
  return array(
77
    'tasks' => array(),
78
    'task_handlers' => array(),
79
    'page_wizards' => array(),
80
  );
81
}
82

    
83
/**
84
 * Delegated implementation of hook_menu().
85
 */
86
function page_manager_menu() {
87
  // For some reason, some things can activate modules without satisfying
88
  // dependencies. I don't know how, but this helps prevent things from
89
  // whitescreening when this happens.
90
  if (!module_exists('ctools')) {
91
    return;
92
  }
93

    
94
  $items = array();
95
  $base = array(
96
    'access arguments' => array('use page manager'),
97
    'file' => 'page_manager.admin.inc',
98
    'theme callback' => 'ajax_base_page_theme',
99
  );
100

    
101
  $items['admin/structure/pages'] = array(
102
    'title' => 'Pages',
103
    'description' => 'Add, edit and remove overridden system pages and user defined pages from the system.',
104
    'page callback' => 'page_manager_list_page',
105
  ) + $base;
106

    
107
  $items['admin/structure/pages/list'] = array(
108
    'title' => 'List',
109
    'page callback' => 'page_manager_list_page',
110
    'type' => MENU_DEFAULT_LOCAL_TASK,
111
    'weight' => -10,
112
  ) + $base;
113

    
114
  $items['admin/structure/pages/edit/%page_manager_cache'] = array(
115
    'title' => 'Edit',
116
    'page callback' => 'page_manager_edit_page',
117
    'page arguments' => array(4),
118
    'type' => MENU_NORMAL_ITEM,
119
  ) + $base;
120

    
121
  $items['admin/structure/pages/%ctools_js/operation/%page_manager_cache'] = array(
122
    'page callback' => 'page_manager_edit_page_operation',
123
    'page arguments' => array(3, 5),
124
    'type' => MENU_NORMAL_ITEM,
125
  ) + $base;
126

    
127
  $items['admin/structure/pages/%ctools_js/enable/%page_manager_cache'] = array(
128
    'page callback' => 'page_manager_enable_page',
129
    'page arguments' => array(FALSE, 3, 5),
130
    'type' => MENU_CALLBACK,
131
  ) + $base;
132

    
133
  $items['admin/structure/pages/%ctools_js/disable/%page_manager_cache'] = array(
134
    'page callback' => 'page_manager_enable_page',
135
    'page arguments' => array(TRUE, 3, 5),
136
    'type' => MENU_CALLBACK,
137
  ) + $base;
138

    
139
  $tasks = page_manager_get_tasks();
140

    
141
  // Provide menu items for each task.
142
  foreach ($tasks as $task_id => $task) {
143
    // Allow the task to add its own menu items.
144
    if ($function = ctools_plugin_get_function($task, 'hook menu')) {
145
      $function($items, $task);
146
    }
147

    
148
    // And for those that provide subtasks, provide menu items for them, as well.
149
    foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
150
      // Allow the task to add its own menu items.
151
      if ($function = ctools_plugin_get_function($task, 'hook menu')) {
152
        $function($items, $subtask);
153
      }
154
    }
155
  }
156

    
157
  return $items;
158
}
159

    
160
function page_manager_admin_paths() {
161
  /* @todo FIX ME this is a major resource suck. */
162
  return;
163

    
164
  $items = array();
165
  ctools_include('page', 'page_manager', 'plugins/tasks');
166
  $pages = page_manager_page_load_all();
167
  foreach ($pages as $page) {
168
    // Make sure the page we're on is set to be an administrative path and that
169
    // it is not set to be a frontpage path.
170
    if ((isset($page->conf['admin_paths']) && $page->conf['admin_paths']) && (!isset($page->make_frontpage) || !$page->make_frontpage)) {
171
      $path_parts = explode('/', $page->path);
172
      foreach ($path_parts as $key => $part) {
173
        if (strpos($part, '%') !== FALSE || strpos($part, '!') !== FALSE) {
174
          $path_parts[$key] = '*';
175
        }
176
      }
177
      $path = implode('/', $path_parts);
178
      if ($page->menu['type'] == 'default tab') {
179
        array_pop($path_parts);
180
        $parent_path = implode('/', $path_parts);
181
        $items[$parent_path] = TRUE;
182
      }
183
      $items[$path] = TRUE;
184
    }
185
  }
186
  return $items;
187
}
188

    
189
/**
190
 * Implements hook_menu_alter.
191
 *
192
 * Get a list of all tasks and delegate to them.
193
 */
194
function page_manager_menu_alter(&$items) {
195
  // For some reason, some things can activate modules without satisfying
196
  // dependencies. I don't know how, but this helps prevent things from
197
  // whitescreening when this happens.
198
  if (!module_exists('ctools')) {
199
    return;
200
  }
201

    
202
  $tasks = page_manager_get_tasks();
203

    
204
  foreach ($tasks as $task) {
205
    if ($function = ctools_plugin_get_function($task, 'hook menu alter')) {
206
      $function($items, $task);
207
    }
208
    // let the subtasks alter the menu items too.
209
    foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
210
      if ($function = ctools_plugin_get_function($subtask, 'hook menu alter')) {
211
        $function($items, $subtask);
212
      }
213
    }
214
  }
215

    
216
  // Override the core node revisions display to use the configured Page
217
  // display handler.
218
  if (!variable_get('page_manager_node_view_disabled', TRUE) && isset($items['node/%node/revisions/%/view'])) {
219
    // Abstract the basic settings.
220
    $item = array(
221
      // Handle the page arguments.
222
      'load arguments' => array(3),
223
      'page arguments' => array(1, TRUE),
224

    
225
      // Replace the normal node_show call with Page Manager's node view.
226
      'page callback' => 'page_manager_node_view_page',
227

    
228
      // Provide the correct path to the Page Manager file.
229
      'file' => 'node_view.inc',
230
      'file path' => drupal_get_path('module', 'page_manager') . '/plugins/tasks',
231
    );
232
    // Re-build the menu item using the normal values from node.module.
233
    $items['node/%node/revisions/%/view'] = array(
234
      'title' => 'Revisions',
235
      'access callback' => '_node_revision_access',
236
      'access arguments' => array(1),
237
    ) + $item;
238
  }
239

    
240
  return $items;
241
}
242

    
243
/*
244
 * Implements hook_theme()
245
 */
246
function page_manager_theme() {
247
  // For some reason, some things can activate modules without satisfying
248
  // dependencies. I don't know how, but this helps prevent things from
249
  // whitescreening when this happens.
250
  if (!module_exists('ctools')) {
251
    return;
252
  }
253

    
254
  $base = array(
255
    'path' => drupal_get_path('module', 'page_manager') . '/theme',
256
    'file' => 'page_manager.theme.inc',
257
  );
258

    
259
  $items = array(
260
    'page_manager_handler_rearrange' => array(
261
      'render element' => 'form',
262
    ) + $base,
263
    'page_manager_edit_page' => array(
264
      'template' => 'page-manager-edit-page',
265
      'variables' => array('page' => NULL, 'save' => NULL, 'operations' => array(), 'content' => array()),
266
    ) + $base,
267
    'page_manager_lock' => array(
268
      'variables' => array('page' => array()),
269
    ) + $base,
270
    'page_manager_changed' => array(
271
      'variables' => array('text' => NULL, 'description' => NULL),
272
    ) + $base,
273
  );
274

    
275
  // Allow task plugins to have theme registrations by passing through:
276
  $tasks = page_manager_get_tasks();
277

    
278
  // Provide menu items for each task.
279
  foreach ($tasks as $task_id => $task) {
280
    if ($function = ctools_plugin_get_function($task, 'hook theme')) {
281
      $function($items, $task);
282
    }
283
  }
284

    
285
  return $items;
286
}
287

    
288
// --------------------------------------------------------------------------
289
// Page caching
290
//
291
// The page cache is used to store a page temporarily, using the ctools object
292
// cache. When loading from the page cache, it will either load the cached
293
// version, or if there is not one, load the real thing and create a cache
294
// object which can then be easily stored.
295

    
296
/**
297
 * Get the cached changes to a given task handler.
298
 */
299
function page_manager_get_page_cache($task_name) {
300
  $caches = drupal_static(__FUNCTION__, array());
301
  if (!isset($caches[$task_name])) {
302
    ctools_include('object-cache');
303
    $cache = ctools_object_cache_get('page_manager_page', $task_name);
304
    if (!$cache) {
305
      $cache = new stdClass();
306
      $cache->task_name = $task_name;
307
      list($cache->task_id, $cache->subtask_id) = page_manager_get_task_id($cache->task_name);
308

    
309
      $cache->task = page_manager_get_task($cache->task_id);
310
      if (empty($cache->task)) {
311
        return FALSE;
312
      }
313

    
314
      if ($cache->subtask_id) {
315
        $cache->subtask = page_manager_get_task_subtask($cache->task, $cache->subtask_id);
316
        if (empty($cache->subtask)) {
317
          return FALSE;
318
        }
319
      }
320
      else {
321
        $cache->subtask = $cache->task;
322
        $cache->subtask['name'] = '';
323
      }
324

    
325
      $cache->handlers = page_manager_load_sorted_handlers($cache->task, $cache->subtask_id);
326
      $cache->handler_info = array();
327
      foreach ($cache->handlers as $id => $handler) {
328
        $cache->handler_info[$id] = array(
329
          'weight' => $handler->weight,
330
          'changed' => FALSE,
331
          'name' => $id,
332
        );
333
      }
334
    }
335
    else {
336
      // ensure the task is loaded.
337
      page_manager_get_task($cache->task_id);
338
    }
339

    
340
    if ($task_name != '::new') {
341
      $cache->locked = ctools_object_cache_test('page_manager_page', $task_name);
342
    }
343
    else {
344
      $cache->locked = FALSE;
345
    }
346

    
347
    $caches[$task_name] = $cache;
348
  }
349

    
350
  return $caches[$task_name];
351
}
352

    
353
/**
354
 * Store changes to a task handler in the object cache.
355
 */
356
function page_manager_set_page_cache($page) {
357
  if (!empty($page->locked)) {
358
    return;
359
  }
360

    
361
  if (empty($page->task_name)) {
362
    return;
363
  }
364

    
365
  ctools_include('object-cache');
366
  $page->changed = TRUE;
367
  $cache = ctools_object_cache_set('page_manager_page', $page->task_name, $page);
368
}
369

    
370
/**
371
 * Remove an item from the object cache.
372
 */
373
function page_manager_clear_page_cache($name) {
374
  ctools_include('object-cache');
375
  ctools_object_cache_clear('page_manager_page', $name);
376
}
377

    
378
/**
379
 * Write all changes from the page cache and clear it out.
380
 */
381
function page_manager_save_page_cache($cache) {
382
  // Save the subtask:
383
  if ($function = ctools_plugin_get_function($cache->task, 'save subtask callback')) {
384
    $function($cache->subtask, $cache);
385
  }
386

    
387
  // Iterate through handlers and save/delete/update as necessary.
388
  // Go through each of the task handlers, check to see if it needs updating,
389
  // and update it if so.
390
  foreach ($cache->handler_info as $id => $info) {
391
    $handler = &$cache->handlers[$id];
392
    // If it has been marked for deletion, delete it.
393

    
394
    if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
395
      page_manager_delete_task_handler($handler);
396
    }
397
    // If it has been somehow edited (or added), write the cached version
398
    elseif ($info['changed'] & PAGE_MANAGER_CHANGED_CACHED) {
399
      // Make sure we get updated weight from the form for this.
400
      $handler->weight = $info['weight'];
401
      page_manager_save_task_handler($handler);
402
    }
403
    // Otherwise, check to see if it has moved and, if so, update the weight.
404
    elseif ($info['weight'] != $handler->weight) {
405
      // Theoretically we could only do this for in code objects, but since our
406
      // load mechanism checks for all, this is less database work.
407
      page_manager_update_task_handler_weight($handler, $info['weight']);
408
    }
409

    
410
    // Set enable/disabled status.
411
    if ($info['changed'] & PAGE_MANAGER_CHANGED_STATUS) {
412
      ctools_include('export');
413
      ctools_export_set_object_status($cache->handlers[$id], $info['disabled']);
414
    }
415
  }
416

    
417
  page_manager_clear_page_cache($cache->task_name);
418

    
419
  if (!empty($cache->path_changed) || !empty($cache->new)) {
420
    // Force a menu rebuild to make sure the menu entries are set.
421
    menu_rebuild();
422
  }
423
  cache_clear_all();
424
}
425

    
426
/**
427
 * Menu callback to load a page manager cache object for menu callbacks.
428
 */
429
function page_manager_cache_load($task_name) {
430
  // load context plugin as there may be contexts cached here.
431
  ctools_include('context');
432
  return page_manager_get_page_cache($task_name);
433
}
434

    
435
/**
436
 * Generate a unique name for a task handler.
437
 *
438
 * Task handlers need to be named but they aren't allowed to set their own
439
 * names. Instead, they are named based upon their parent task and type.
440
 */
441
function page_manager_handler_get_name($task_name, $handlers, $handler) {
442
  $base = str_replace('-', '_', $task_name);
443
  $name = '';
444

    
445
  // Optional machine name.
446
  if (!empty($handler->conf['name'])) {
447
    $name = $base . '__' . $handler->conf['name'];
448
    if (count(ctools_export_load_object('page_manager_handlers', 'names', array($name)))) {
449
      $name = '';
450
    }
451
  }
452

    
453
  // If no machine name was provided or the name is in use, generate a unique name.
454
  if (empty($name)) {
455
    $base .= '__' . $handler->handler;
456

    
457
    // Use the ctools uuid generator to generate a unique id.
458
    $name = $base . '_' . ctools_uuid_generate();
459
  }
460

    
461
  return $name;
462
}
463

    
464
/**
465
 * Import a handler into a page.
466
 *
467
 * This is used by both import and clone, since clone just exports the
468
 * handler and immediately imports it.
469
 */
470
function page_manager_handler_add_to_page(&$page, &$handler, $title = NULL) {
471
  $last = end($page->handler_info);
472
  $handler->weight = $last ? $last['weight'] + 1 : 0;
473
  $handler->task = $page->task_id;
474
  $handler->subtask = $page->subtask_id;
475
  $handler->export_type = EXPORT_IN_DATABASE;
476
  $handler->type = t('Normal');
477

    
478
  if ($title) {
479
    $handler->conf['title'] = $title;
480
    $handler->conf['name'] = trim(preg_replace('/[^a-z0-9_]+/', '-', strtolower($title)), '-');
481
  }
482
  else {
483
    $handler->conf['name'] = '';
484
  }
485

    
486
  $name = page_manager_handler_get_name($page->task_name, $page->handlers, $handler);
487

    
488
  $handler->name = $name;
489

    
490
  $page->handlers[$name] = $handler;
491
  $page->handler_info[$name] = array(
492
    'weight' => $handler->weight,
493
    'name' => $handler->name,
494
    'changed' => PAGE_MANAGER_CHANGED_CACHED,
495
  );
496
}
497

    
498
// --------------------------------------------------------------------------
499
// Database routines
500
//
501
// This includes fetching plugins and plugin info as well as specialized
502
// fetch methods to get groups of task handlers per task.
503

    
504
/**
505
 * Load a single task handler by name.
506
 *
507
 * Handlers can come from multiple sources; either the database or by normal
508
 * export method, which is handled by the ctools library, but handlers can
509
 * also be bundled with task/subtask. We have to check there and perform
510
 * overrides as appropriate.
511
 *
512
 * Handlers bundled with the task are of a higher priority than default
513
 * handlers provided by normal code, and are of a lower priority than
514
 * the database, so we have to check the source of handlers when we have
515
 * multiple to choose from.
516
 */
517
function page_manager_load_task_handler($task, $subtask_id, $name) {
518
  ctools_include('export');
519
  $result = ctools_export_load_object('page_manager_handlers', 'names', array($name));
520
  $handlers = page_manager_get_default_task_handlers($task, $subtask_id);
521
  return page_manager_compare_task_handlers($result, $handlers, $name);
522
}
523

    
524
/**
525
 * Load all task handlers for a given task/subtask.
526
 */
527
function page_manager_load_task_handlers($task, $subtask_id = NULL, $default_handlers = NULL) {
528
  ctools_include('export');
529
  $conditions = array(
530
    'task' => $task['name'],
531
  );
532

    
533
  if (isset($subtask_id)) {
534
    $conditions['subtask'] = $subtask_id;
535
  }
536

    
537
  $handlers = ctools_export_load_object('page_manager_handlers', 'conditions', $conditions);
538
  $defaults = isset($default_handlers) ? $default_handlers : page_manager_get_default_task_handlers($task, $subtask_id);
539
  foreach ($defaults as $name => $default) {
540
    $result = page_manager_compare_task_handlers($handlers, $defaults, $name);
541

    
542
    if ($result) {
543
      $handlers[$name] = $result;
544
      // Ensure task and subtask are correct, because it's easy to change task
545
      // names when editing a default and fail to do it on the associated handlers.
546
      $result->task = $task['name'];
547
      $result->subtask = $subtask_id;
548
    }
549
  }
550

    
551
  // Override weights from the weight table.
552
  if ($handlers) {
553
    $names = array();
554
    $placeholders = array();
555
    foreach ($handlers as $handler) {
556
      $names[] = $handler->name;
557
      $placeholders[] = "'%s'";
558
    }
559

    
560
    $result = db_query('SELECT name, weight FROM {page_manager_weights} WHERE name IN (:names)', array(':names' => $names));
561
    foreach ($result as $weight) {
562
      $handlers[$weight->name]->weight = $weight->weight;
563
    }
564
  }
565

    
566
  return $handlers;
567
}
568

    
569
/**
570
 * Get the default task handlers from a task, if they exist.
571
 *
572
 * Tasks can contain 'default' task handlers which are provided by the
573
 * default task. Because these can come from either the task or the
574
 * subtask, the logic is abstracted to reduce code duplication.
575
 */
576
function page_manager_get_default_task_handlers($task, $subtask_id) {
577
  // Load default handlers that are provied by the task/subtask itself.
578
  $handlers = array();
579
  if ($subtask_id) {
580
    $subtask = page_manager_get_task_subtask($task, $subtask_id);
581
    if (isset($subtask['default handlers'])) {
582
      $handlers = $subtask['default handlers'];
583
    }
584
  }
585
  else if (isset($task['default handlers'])) {
586
    $handlers = $task['default handlers'];
587
  }
588

    
589
  return $handlers;
590
}
591

    
592
/**
593
 * Compare a single task handler from two lists and provide the correct one.
594
 *
595
 * Task handlers can be gotten from multiple sources. As exportable objects,
596
 * they can be provided by default hooks and the database. But also, because
597
 * they are tightly bound to tasks, they can also be provided by default
598
 * tasks. This function reconciles where to pick up a task handler between
599
 * the exportables list and the defaults provided by the task itself.
600
 *
601
 * @param $result
602
 *   A list of handlers provided by export.inc
603
 * @param $handlers
604
 *   A list of handlers provided by the default task.
605
 * @param $name
606
 *   Which handler to compare.
607
 * @return
608
 *   Which handler to use, if any. May be NULL.
609
 */
610
function page_manager_compare_task_handlers($result, $handlers, $name) {
611
  // Compare our special default handler against the actual result, if
612
  // any, and do the right thing.
613
  if (!isset($result[$name]) && isset($handlers[$name])) {
614
    $handlers[$name]->type = t('Default');
615
    $handlers[$name]->export_type = EXPORT_IN_CODE;
616
    return $handlers[$name];
617
  }
618
  else if (isset($result[$name]) && !isset($handlers[$name])) {
619
    return $result[$name];
620
  }
621
  else if (isset($result[$name]) && isset($handlers[$name])) {
622
    if ($result[$name]->export_type & EXPORT_IN_DATABASE) {
623
      $result[$name]->type = t('Overridden');
624
      $result[$name]->export_type = $result[$name]->export_type | EXPORT_IN_CODE;
625
      return $result[$name];
626
    }
627
    else {
628
      // In this case, our default is a higher priority than the standard default.
629
      $handlers[$name]->type = t('Default');
630
      $handlers[$name]->export_type = EXPORT_IN_CODE;
631
      return $handlers[$name];
632
    }
633
  }
634
}
635

    
636
/**
637
 * Load all task handlers for a given task and subtask and sort them.
638
 */
639
function page_manager_load_sorted_handlers($task, $subtask_id = NULL, $enabled = FALSE) {
640
  $handlers = page_manager_load_task_handlers($task, $subtask_id);
641
  if ($enabled) {
642
    foreach ($handlers as $id => $handler) {
643
      if (!empty($handler->disabled)) {
644
        unset($handlers[$id]);
645
      }
646
    }
647
  }
648
  uasort($handlers, 'page_manager_sort_task_handlers');
649
  return $handlers;
650
}
651

    
652
/**
653
 * Callback for uasort to sort task handlers.
654
 *
655
 * Task handlers are sorted by weight then by name.
656
 */
657
function page_manager_sort_task_handlers($a, $b) {
658
  if ($a->weight < $b->weight) {
659
    return -1;
660
  }
661
  elseif ($a->weight > $b->weight) {
662
    return 1;
663
  }
664
  elseif ($a->name < $b->name) {
665
    return -1;
666
  }
667
  elseif ($a->name > $b->name) {
668
    return 1;
669
  }
670

    
671
  return 0;
672
}
673

    
674
/**
675
 * Write a task handler to the database.
676
 */
677
function page_manager_save_task_handler(&$handler) {
678
  $update = (isset($handler->did)) ? array('did') : array();
679
  // Let the task handler respond to saves:
680
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'save')) {
681
    $function($handler, $update);
682
  }
683

    
684
  drupal_write_record('page_manager_handlers', $handler, $update);
685
  db_delete('page_manager_weights')
686
    ->condition('name', $handler->name)
687
    ->execute();
688

    
689
  // If this was previously a default handler, we may have to write task handlers.
690
  if (!$update) {
691
    // @todo wtf was I going to do here?
692
  }
693
  return $handler;
694
}
695

    
696
/**
697
 * Remove a task handler.
698
 */
699
function page_manager_delete_task_handler($handler) {
700
  // Let the task handler respond to saves:
701
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'delete')) {
702
    $function($handler);
703
  }
704
  db_delete('page_manager_handlers')
705
    ->condition('name', $handler->name)
706
    ->execute();
707
  db_delete('page_manager_weights')
708
    ->condition('name', $handler->name)
709
    ->execute();
710
}
711

    
712
/**
713
 * Export a task handler into code suitable for import or use as a default
714
 * task handler.
715
 */
716
function page_manager_export_task_handler($handler, $indent = '') {
717
  ctools_include('export');
718
  ctools_include('plugins');
719
  $handler = clone $handler;
720

    
721
  $append = '';
722
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'export')) {
723
    $append = $function($handler, $indent);
724
  }
725

    
726
  $output = ctools_export_object('page_manager_handlers', $handler, $indent);
727
  $output .= $append;
728

    
729
  return $output;
730
}
731

    
732
/**
733
 * Loads page manager handler for export.
734
 *
735
 * Callback to load page manager handler within ctools_export_crud_load().
736
 *
737
 * @param string $name
738
 *   The name of the handler to load.
739
 *
740
 * @return
741
 *   Loaded page manager handler object, extended with external properties.
742
 */
743
function page_manager_export_task_handler_load($name) {
744
  $table = 'page_manager_handlers';
745
  $schema = ctools_export_get_schema($table);
746
  $export = $schema['export'];
747

    
748
  $result = ctools_export_load_object($table, 'names', array($name));
749
  if (isset($result[$name])) {
750
    $handler = $result[$name];
751

    
752
    // Weight is stored in additional table so that in-code task handlers
753
    // don't need to get written to the database just because they have their
754
    // weight changed. Therefore, handler could have no correspondent database
755
    // entry. Revert will not be performed for this handler and the weight
756
    // will not be reverted. To make possible revert of the weight field
757
    // export_type must simulate that the handler is stored in the database.
758
    $handler->export_type = EXPORT_IN_DATABASE;
759

    
760
    // Also, page manager handler weight should be overriden with correspondent
761
    // weight from page_manager_weights table, if there is one.
762
    $result = db_query('SELECT weight FROM {page_manager_weights} WHERE name = (:names)', array(':names' => $handler->name))->fetchField();
763
    if (is_numeric($result)) {
764
      $handler->weight = $result;
765
    }
766
    return $handler;
767
  }
768
}
769

    
770
/**
771
 * Create a new task handler object.
772
 *
773
 * @param $plugin
774
 *   The plugin this task handler is created from.
775
 */
776
function page_manager_new_task_handler($plugin) {
777
  // Generate a unique name. Unlike most named objects, we don't let people choose
778
  // names for task handlers because they mostly don't make sense.
779

    
780
  // Create a new, empty handler object.
781
  $handler          = new stdClass;
782
  $handler->title   = $plugin['title'];
783
  $handler->task    = NULL;
784
  $handler->subtask = NULL;
785
  $handler->name    = NULL;
786
  $handler->handler = $plugin['name'];
787
  $handler->weight  = 0;
788
  $handler->conf    = array();
789

    
790
  // These are provided by the core export API provided by ctools and we
791
  // set defaults here so that we don't cause notices. Perhaps ctools should
792
  // provide a way to do this for us so we don't have to muck with it.
793
  $handler->export_type = EXPORT_IN_DATABASE;
794
  $handler->type = t('Local');
795

    
796
  if (isset($plugin['default conf'])) {
797
    if (is_array($plugin['default conf'])) {
798
      $handler->conf = $plugin['default conf'];
799
    }
800
    else if (function_exists($plugin['default conf'])) {
801
      $handler->conf = $plugin['default conf']($handler);
802
    }
803
  }
804

    
805
  return $handler;
806
}
807

    
808
/**
809
 * Set an overidden weight for a task handler.
810
 *
811
 * We do this so that in-code task handlers don't need to get written
812
 * to the database just because they have their weight changed.
813
 */
814
function page_manager_update_task_handler_weight($handler, $weight) {
815
  db_delete('page_manager_weights')
816
    ->condition('name', $handler->name)
817
    ->execute();
818
  db_insert('page_manager_weights')
819
    ->fields(array(
820
      'name' => $handler->name,
821
      'weight' => $weight,
822
    ))
823
    ->execute();
824
}
825

    
826

    
827
/**
828
 * Shortcut function to get task plugins.
829
 */
830
function page_manager_get_tasks() {
831
  ctools_include('plugins');
832
  return ctools_get_plugins('page_manager', 'tasks');
833
}
834

    
835
/**
836
 * Shortcut function to get a task plugin.
837
 */
838
function page_manager_get_task($id) {
839
  ctools_include('plugins');
840
  return ctools_get_plugins('page_manager', 'tasks', $id);
841
}
842

    
843
/**
844
 * Get all tasks for a given type.
845
 */
846
function page_manager_get_tasks_by_type($type) {
847
  ctools_include('plugins');
848
  $all_tasks = ctools_get_plugins('page_manager', 'tasks');
849
  $tasks = array();
850
  foreach ($all_tasks as $id => $task) {
851
    if (isset($task['task type']) && $task['task type'] == $type) {
852
      $tasks[$id] = $task;
853
    }
854
  }
855

    
856
  return $tasks;
857
}
858

    
859
/**
860
 * Fetch all subtasks for a page managertask.
861
 *
862
 * @param $task
863
 *   A loaded $task plugin object.
864
 */
865
function page_manager_get_task_subtasks($task) {
866
  if (empty($task['subtasks'])) {
867
    return array();
868
  }
869

    
870
  if ($function = ctools_plugin_get_function($task, 'subtasks callback')) {
871
    $retval = $function($task);
872
    if (is_array($retval)) {
873
      return $retval;
874
    }
875
  }
876

    
877
  return array();
878
}
879

    
880
/**
881
 * Fetch all subtasks for a page managertask.
882
 *
883
 * @param $task
884
 *   A loaded $task plugin object.
885
 * @param $subtask_id
886
 *   The subtask ID to load.
887
 */
888
function page_manager_get_task_subtask($task, $subtask_id) {
889
  if (empty($task['subtasks'])) {
890
    return;
891
  }
892

    
893
  if ($function = ctools_plugin_get_function($task, 'subtask callback')) {
894
    return $function($task, $subtask_id);
895
  }
896
}
897

    
898
/**
899
 * Shortcut function to get task handler plugins.
900
 */
901
function page_manager_get_task_handlers() {
902
  ctools_include('plugins');
903
  return ctools_get_plugins('page_manager', 'task_handlers');
904
}
905

    
906
/**
907
 * Shortcut function to get a task handler plugin.
908
 */
909
function page_manager_get_task_handler($id) {
910
  ctools_include('plugins');
911
  return ctools_get_plugins('page_manager', 'task_handlers', $id);
912
}
913

    
914
/**
915
 * Retrieve a list of all applicable task handlers for a given task.
916
 *
917
 * This looks at the $task['handler type'] and compares that to $task_handler['handler type'].
918
 * If the task has no type, the id of the task is used instead.
919
 */
920
function page_manager_get_task_handler_plugins($task, $all = FALSE) {
921
  $type = isset($task['handler type']) ? $task['handler type'] : $task['name'];
922
  $name = $task['name'];
923

    
924
  $handlers = array();
925
  $task_handlers = page_manager_get_task_handlers();
926
  foreach ($task_handlers as $id => $handler) {
927
    $task_type = is_array($handler['handler type']) ? $handler['handler type'] : array($handler['handler type']);
928
    if (in_array($type, $task_type) || in_array($name, $task_type)) {
929
      if ($all || !empty($handler['visible'])) {
930
        $handlers[$id] = $handler;
931
      }
932
    }
933
  }
934

    
935
  return $handlers;
936
}
937

    
938
/**
939
 * Get the title for a given handler.
940
 *
941
 * If the plugin has no 'admin title' function, the generic title of the
942
 * plugin is used instead.
943
 */
944
function page_manager_get_handler_title($plugin, $handler, $task, $subtask_id) {
945
  $function = ctools_plugin_get_function($plugin, 'admin title');
946
  if ($function) {
947
    return $function($handler, $task, $subtask_id);
948
  }
949
  else {
950
    return $plugin['title'];
951
  }
952
}
953

    
954
/**
955
 * Get the admin summary (additional info) for a given handler.
956
 */
957
function page_manager_get_handler_summary($plugin, $handler, $page, $title = TRUE) {
958
  if ($function = ctools_plugin_get_function($plugin, 'admin summary')) {
959
    return $function($handler, $page->task, $page->subtask, $page, $title);
960
  }
961
}
962

    
963
/**
964
 * Get the admin summary (additional info) for a given page.
965
 */
966
function page_manager_get_page_summary($task, $subtask) {
967
  if ($function = ctools_plugin_get_function($subtask, 'admin summary')) {
968
    return $function($task, $subtask);
969
  }
970
}
971

    
972
/**
973
 * Split a task name into a task id and subtask id, if applicable.
974
 */
975
function page_manager_get_task_id($task_name) {
976
  if (strpos($task_name, '-') !== FALSE) {
977
    return explode('-', $task_name, 2);
978
  }
979
  else {
980
    return array($task_name, NULL);
981
  }
982
}
983

    
984
/**
985
 * Turn a task id + subtask_id into a task name.
986
 */
987
function page_manager_make_task_name($task_id, $subtask_id) {
988
  if ($subtask_id) {
989
    return $task_id . '-' . $subtask_id;
990
  }
991
  else {
992
    return $task_id;
993
  }
994
}
995

    
996
/**
997
 * Get the render function for a handler.
998
 */
999
function page_manager_get_renderer($handler) {
1000
  return ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'render');
1001
}
1002

    
1003
// --------------------------------------------------------------------------
1004
// Functions existing on behalf of tasks and task handlers
1005

    
1006

    
1007
/**
1008
 * Page manager arg load function because menu system will not load extra
1009
 * files for these; they must be in a .module.
1010
 */
1011
function pm_arg_load($value, $subtask, $argument) {
1012
  page_manager_get_task('page');
1013
  return _pm_arg_load($value, $subtask, $argument);
1014
}
1015

    
1016
/**
1017
 * Special arg_load function to use %menu_tail like functionality to
1018
 * get everything after the arg together as a single value.
1019
 */
1020
function pm_arg_tail_load($value, $subtask, $argument, $map) {
1021
  $value = implode('/', array_slice($map, $argument));
1022
  page_manager_get_task('page');
1023
  return _pm_arg_load($value, $subtask, $argument);
1024
}
1025

    
1026
/**
1027
 * Special menu _load() function for the user:uid argument.
1028
 *
1029
 * This is just the normal page manager argument. It only exists so that
1030
 * the to_arg can exist.
1031
 */
1032
function pm_uid_arg_load($value, $subtask, $argument) {
1033
  page_manager_get_task('page');
1034
  return _pm_arg_load($value, $subtask, $argument);
1035
}
1036

    
1037
/**
1038
 * to_arg function for the user:uid argument to provide the arg for the
1039
 * current global user.
1040
 */
1041
function pm_uid_arg_to_arg($arg) {
1042
  return user_uid_optional_to_arg($arg);
1043
}
1044

    
1045
/**
1046
 * Callback for access control ajax form on behalf of page.inc task.
1047
 *
1048
 * Returns the cached access config and contexts used.
1049
 */
1050
function page_manager_page_ctools_access_get($argument) {
1051
  $page = page_manager_get_page_cache($argument);
1052

    
1053
  $contexts = array();
1054

    
1055
  // Load contexts based on argument data:
1056
  if ($arguments = _page_manager_page_get_arguments($page->subtask['subtask'])) {
1057
    $contexts = ctools_context_get_placeholders_from_argument($arguments);
1058
  }
1059

    
1060
  return array($page->subtask['subtask']->access, $contexts);
1061
}
1062

    
1063
/**
1064
 * Callback for access control ajax form on behalf of page.inc task.
1065
 *
1066
 * Writes the changed access to the cache.
1067
 */
1068
function page_manager_page_ctools_access_set($argument, $access) {
1069
  $page = page_manager_get_page_cache($argument);
1070
  $page->subtask['subtask']->access = $access;
1071
  page_manager_set_page_cache($page);
1072
}
1073

    
1074
/**
1075
 * Callback for access control ajax form on behalf of context task handler.
1076
 *
1077
 * Returns the cached access config and contexts used.
1078
 */
1079
function page_manager_task_handler_ctools_access_get($argument) {
1080
  list($task_name, $name) = explode('*', $argument);
1081
  $page = page_manager_get_page_cache($task_name);
1082
  if (empty($name)) {
1083
    $handler = &$page->new_handler;
1084
  }
1085
  else {
1086
    $handler = &$page->handlers[$name];
1087
  }
1088

    
1089
  if (!isset($handler->conf['access'])) {
1090
    $handler->conf['access'] = array();
1091
  }
1092

    
1093
  ctools_include('context-task-handler');
1094

    
1095
  $contexts = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
1096

    
1097
  return array($handler->conf['access'], $contexts);
1098
}
1099

    
1100
/**
1101
 * Callback for access control ajax form on behalf of context task handler.
1102
 *
1103
 * Writes the changed access to the cache.
1104
 */
1105
function page_manager_task_handler_ctools_access_set($argument, $access) {
1106
  list($task_name, $name) = explode('*', $argument);
1107
  $page = page_manager_get_page_cache($task_name);
1108
  if (empty($name)) {
1109
    $handler = &$page->new_handler;
1110
  }
1111
  else {
1112
    $handler = &$page->handlers[$name];
1113
  }
1114

    
1115
  $handler->conf['access'] = $access;
1116
  page_manager_set_page_cache($page);
1117
}
1118

    
1119
/**
1120
 * Form a URL to edit a given page given the trail.
1121
 */
1122
function page_manager_edit_url($task_name, $trail = array()) {
1123
  if (!is_array($trail)) {
1124
    $trail = array($trail);
1125
  }
1126

    
1127
  if (empty($trail) || $trail == array('summary')) {
1128
    return "admin/structure/pages/edit/$task_name";
1129
  }
1130

    
1131
  return 'admin/structure/pages/nojs/operation/' . $task_name . '/' . implode('/', $trail);
1132
}
1133

    
1134
/**
1135
 * Watch menu links during the menu rebuild, and re-parent things if we need to.
1136
 */
1137
function page_manager_menu_link_alter(&$item) {
1138
  return;
1139
/** -- disabled, concept code --
1140
  static $mlids = array();
1141
  // Keep an array of mlids as links are saved that we can use later.
1142
  if (isset($item['mlid'])) {
1143
    $mlids[$item['path']] = $item['mlid'];
1144
  }
1145

    
1146
  if (isset($item['parent_path'])) {
1147
    if (isset($mlids[$item['parent_path']])) {
1148
      $item['plid'] = $mlids[$item['parent_path']];
1149
    }
1150
    else {
1151
      // Since we didn't already see an mlid, let's check the database for one.
1152
      $mlid = db_query('SELECT mlid FROM {menu_links} WHERE router_path = :path', array('path' => $item['parent_path']))->fetchField();
1153
      if ($mlid) {
1154
        $item['plid'] = $mlid;
1155
      }
1156
    }
1157
  }
1158
 */
1159
}
1160

    
1161
/**
1162
 * Callback to list handlers available for export.
1163
 */
1164
function page_manager_page_manager_handlers_list() {
1165
  $list = $types = array();
1166
  $tasks = page_manager_get_tasks();
1167
  foreach ($tasks as $type => $info) {
1168
    if (empty($info['non-exportable'])) {
1169
      $types[] = $type;
1170
    }
1171
  }
1172

    
1173
  $handlers = ctools_export_load_object('page_manager_handlers');
1174
  foreach ($handlers as $handler) {
1175
    if (in_array($handler->task, $types)) {
1176
      $plugin = page_manager_get_task_handler($handler->handler);
1177
      $title = page_manager_get_handler_title($plugin, $handler, $tasks[$handler->task], $handler->subtask);
1178

    
1179
      if ($title) {
1180
        $list[$handler->name] = check_plain("$handler->task: $title ($handler->name)");
1181
      }
1182
      else {
1183
        $list[$handler->name] = check_plain("$handler->task: ($handler->name)");
1184
      }
1185
    }
1186
  }
1187
  return $list;
1188
}
1189

    
1190
/**
1191
 * Callback to bulk export page manager pages.
1192
 */
1193
function page_manager_page_manager_pages_to_hook_code($names = array(), $name = 'foo') {
1194
  $schema = ctools_export_get_schema('page_manager_pages');
1195
  $export = $schema['export'];
1196
  $objects = ctools_export_load_object('page_manager_pages', 'names', array_values($names));
1197
  if ($objects) {
1198
    $code = "/**\n";
1199
    $code .= " * Implements hook_{$export['default hook']}()\n";
1200
    $code .= " */\n";
1201
    $code .= "function " . $name . "_{$export['default hook']}() {\n";
1202
    foreach ($objects as $object) {
1203
      // Have to implement our own because this export func sig requires it
1204
      $code .= $export['export callback']($object, TRUE, '  ');
1205
      $code .= "  \${$export['identifier']}s['" . check_plain($object->$export['key']) . "'] = \${$export['identifier']};\n\n";
1206
    }
1207
    $code .= "  return \${$export['identifier']}s;\n";
1208
    $code .= "}\n";
1209
    return $code;
1210
  }
1211
}
1212

    
1213
/**
1214
 * Get the current page information.
1215
 *
1216
 * @return $page
1217
 *   An array containing the following information.
1218
 *
1219
 * - 'name': The name of the page as used in the page manager admin UI.
1220
 * - 'task': The plugin for the task in use. If this is a system page it
1221
 *   will contain information about that page, such as what functions
1222
 *   it uses.
1223
 * - 'subtask': The plugin for the subtask. If this is a custom page, this
1224
 *   will contain information about that custom page. See 'subtask' in this
1225
 *   array to get the actual page object.
1226
 * - 'handler': The actual handler object used. If using panels, see
1227
 *   $page['handler']->conf['display'] for the actual panels display
1228
 *   used to render.
1229
 * - 'contexts': The context objects used to render this page.
1230
 * - 'arguments': The raw arguments from the URL used on this page.
1231
 */
1232
function page_manager_get_current_page($page = NULL) {
1233
  static $current = array();
1234
  if (isset($page)) {
1235
    $current = $page;
1236
  }
1237

    
1238
  return $current;
1239
}
1240

    
1241
/**
1242
 * Implementation of hook_panels_dashboard_blocks().
1243
 *
1244
 * Adds page information to the Panels dashboard.
1245
 */
1246
function page_manager_panels_dashboard_blocks(&$vars) {
1247
  $vars['links']['page_manager'] = array(
1248
    'weight' => -100,
1249
    'title' => l(t('Panel page'), 'admin/structure/pages/add'),
1250
    'description' => t('Panel pages can be used as landing pages. They have a URL path, accept arguments and can have menu entries.'),
1251
  );
1252

    
1253
  module_load_include('inc', 'page_manager', 'page_manager.admin');
1254
  $tasks = page_manager_get_tasks_by_type('page');
1255
  $pages = array('operations' => array());
1256

    
1257
  page_manager_get_pages($tasks, $pages);
1258
  $count = 0;
1259
  $rows = array();
1260
  foreach ($pages['rows'] as $id => $info) {
1261
    $rows[] = array(
1262
      'data' => array(
1263
        $info['data']['title'],
1264
        $info['data']['operations'],
1265
      ),
1266
      'class' => $info['class'],
1267
    );
1268

    
1269
    // Only show 10.
1270
    if (++$count >= 10) {
1271
      break;
1272
    }
1273
  }
1274

    
1275
  $vars['blocks']['page_manager'] = array(
1276
    'weight' => -100,
1277
    'title' => t('Manage pages'),
1278
    'link' => l(t('Go to list'), 'admin/structure/pages'),
1279
    'content' => theme('table', array('header' => array(), 'rows' => $rows, 'attributes' => array('class' => 'panels-manage'))),
1280
    'class' => 'dashboard-pages',
1281
    'section' => 'right',
1282
  );
1283
}
1284

    
1285
/**
1286
 * Implement pseudo-hook to fetch addressable content.
1287
 *
1288
 * For Page Manager, the address will be an array. The first
1289
 * element will be the $task and the second element will be the
1290
 * $task_handler. The third elements will be the arguments
1291
 * provided.
1292
 */
1293
function page_manager_addressable_content($address, $type) {
1294
  if (count($address) < 3) {
1295
    return;
1296
  }
1297

    
1298
  $task_name = array_shift($address);
1299
  $subtask_name = array_shift($address);
1300
  $handler_name = array_shift($address);
1301
  if ($address) {
1302
    $arguments = array_shift($address);
1303
  }
1304

    
1305
  // Since $arguments is an array of arbitrary size, we need to implode it:
1306
  if (!empty($arguments)) {
1307
    // The only choices we have for separators since :: is already
1308
    // used involve ., - or _. Since - and _ are more common than .
1309
    // in URLs, let's try .. as an argument separator.
1310
    $arguments = explode('..', $arguments);
1311
  }
1312
  else {
1313
    // implode does not return an empty array on an empty
1314
    // string so do it specifically.
1315
    $arguments = array();
1316
  }
1317

    
1318
  $task = page_manager_get_task($task_name);
1319
  if (!$task) {
1320
    return;
1321
  }
1322

    
1323
  $handler = page_manager_load_task_handler($task, $subtask_name, $handler_name);
1324
  if (!$handler) {
1325
    return;
1326
  }
1327

    
1328
  $handler_plugin = page_manager_get_task_handler($handler->handler);
1329
  if (!$handler_plugin) {
1330
    return;
1331
  }
1332

    
1333
  // Load the contexts for the task.
1334
  ctools_include('context');
1335
  ctools_include('context-task-handler');
1336
  $contexts = ctools_context_handler_get_task_contexts($task, $subtask_name, $arguments);
1337

    
1338
  // With contexts loaded, ensure the task is accessible. Tasks without a callback
1339
  // are automatically accessible.
1340
  $function = ctools_plugin_get_function($task, 'access callback');
1341
  if ($function && !$function($task, $subtask_name, $contexts)) {
1342
    return;
1343
  }
1344

    
1345
  $function = ctools_plugin_get_function($handler_plugin, 'addressable callback');
1346
  if ($function) {
1347
    return $function($task, $subtask_name, $handler, $address, $contexts, $arguments, $type);
1348
  }
1349
}