Projet

Général

Profil

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

root / drupal7 / sites / all / modules / ctools / page_manager / page_manager.module @ e4c061ad

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
  // Optional machine name.
444
  if (!empty($handler->conf['name'])) {
445
    $name = $base . '__' . $handler->conf['name'];
446
  }
447

    
448
  // If no machine name was provided, generate a unique name.
449
  else {
450
    $base .= '__' . $handler->handler;
451

    
452
    // Use the ctools uuid generator to generate a unique id.
453
    $name = $base . '_' . ctools_uuid_generate();
454
  }
455

    
456
  return $name;
457
}
458

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

    
473
  if ($title) {
474
    $handler->conf['title'] = $title;
475
  }
476

    
477
  $name = page_manager_handler_get_name($page->task_name, $page->handlers, $handler);
478

    
479
  $handler->name = $name;
480

    
481
  $page->handlers[$name] = $handler;
482
  $page->handler_info[$name] = array(
483
    'weight' => $handler->weight,
484
    'name' => $handler->name,
485
    'changed' => PAGE_MANAGER_CHANGED_CACHED,
486
  );
487
}
488

    
489
// --------------------------------------------------------------------------
490
// Database routines
491
//
492
// This includes fetching plugins and plugin info as well as specialized
493
// fetch methods to get groups of task handlers per task.
494

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

    
515
/**
516
 * Load all task handlers for a given task/subtask.
517
 */
518
function page_manager_load_task_handlers($task, $subtask_id = NULL, $default_handlers = NULL) {
519
  ctools_include('export');
520
  $conditions = array(
521
    'task' => $task['name'],
522
  );
523

    
524
  if (isset($subtask_id)) {
525
    $conditions['subtask'] = $subtask_id;
526
  }
527

    
528
  $handlers = ctools_export_load_object('page_manager_handlers', 'conditions', $conditions);
529
  $defaults = isset($default_handlers) ? $default_handlers : page_manager_get_default_task_handlers($task, $subtask_id);
530
  foreach ($defaults as $name => $default) {
531
    $result = page_manager_compare_task_handlers($handlers, $defaults, $name);
532

    
533
    if ($result) {
534
      $handlers[$name] = $result;
535
      // Ensure task and subtask are correct, because it's easy to change task
536
      // names when editing a default and fail to do it on the associated handlers.
537
      $result->task = $task['name'];
538
      $result->subtask = $subtask_id;
539
    }
540
  }
541

    
542
  // Override weights from the weight table.
543
  if ($handlers) {
544
    $names = array();
545
    $placeholders = array();
546
    foreach ($handlers as $handler) {
547
      $names[] = $handler->name;
548
      $placeholders[] = "'%s'";
549
    }
550

    
551
    $result = db_query('SELECT name, weight FROM {page_manager_weights} WHERE name IN (:names)', array(':names' => $names));
552
    foreach ($result as $weight) {
553
      $handlers[$weight->name]->weight = $weight->weight;
554
    }
555
  }
556

    
557
  return $handlers;
558
}
559

    
560
/**
561
 * Get the default task handlers from a task, if they exist.
562
 *
563
 * Tasks can contain 'default' task handlers which are provided by the
564
 * default task. Because these can come from either the task or the
565
 * subtask, the logic is abstracted to reduce code duplication.
566
 */
567
function page_manager_get_default_task_handlers($task, $subtask_id) {
568
  // Load default handlers that are provied by the task/subtask itself.
569
  $handlers = array();
570
  if ($subtask_id) {
571
    $subtask = page_manager_get_task_subtask($task, $subtask_id);
572
    if (isset($subtask['default handlers'])) {
573
      $handlers = $subtask['default handlers'];
574
    }
575
  }
576
  else if (isset($task['default handlers'])) {
577
    $handlers = $task['default handlers'];
578
  }
579

    
580
  return $handlers;
581
}
582

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

    
627
/**
628
 * Load all task handlers for a given task and subtask and sort them.
629
 */
630
function page_manager_load_sorted_handlers($task, $subtask_id = NULL, $enabled = FALSE) {
631
  $handlers = page_manager_load_task_handlers($task, $subtask_id);
632
  if ($enabled) {
633
    foreach ($handlers as $id => $handler) {
634
      if (!empty($handler->disabled)) {
635
        unset($handlers[$id]);
636
      }
637
    }
638
  }
639
  uasort($handlers, 'page_manager_sort_task_handlers');
640
  return $handlers;
641
}
642

    
643
/**
644
 * Callback for uasort to sort task handlers.
645
 *
646
 * Task handlers are sorted by weight then by name.
647
 */
648
function page_manager_sort_task_handlers($a, $b) {
649
  if ($a->weight < $b->weight) {
650
    return -1;
651
  }
652
  elseif ($a->weight > $b->weight) {
653
    return 1;
654
  }
655
  elseif ($a->name < $b->name) {
656
    return -1;
657
  }
658
  elseif ($a->name > $b->name) {
659
    return 1;
660
  }
661

    
662
  return 0;
663
}
664

    
665
/**
666
 * Write a task handler to the database.
667
 */
668
function page_manager_save_task_handler(&$handler) {
669
  $update = (isset($handler->did)) ? array('did') : array();
670
  // Let the task handler respond to saves:
671
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'save')) {
672
    $function($handler, $update);
673
  }
674

    
675
  drupal_write_record('page_manager_handlers', $handler, $update);
676
  db_delete('page_manager_weights')
677
    ->condition('name', $handler->name)
678
    ->execute();
679

    
680
  // If this was previously a default handler, we may have to write task handlers.
681
  if (!$update) {
682
    // @todo wtf was I going to do here?
683
  }
684
  return $handler;
685
}
686

    
687
/**
688
 * Remove a task handler.
689
 */
690
function page_manager_delete_task_handler($handler) {
691
  // Let the task handler respond to saves:
692
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'delete')) {
693
    $function($handler);
694
  }
695
  db_delete('page_manager_handlers')
696
    ->condition('name', $handler->name)
697
    ->execute();
698
  db_delete('page_manager_weights')
699
    ->condition('name', $handler->name)
700
    ->execute();
701
}
702

    
703
/**
704
 * Export a task handler into code suitable for import or use as a default
705
 * task handler.
706
 */
707
function page_manager_export_task_handler($handler, $indent = '') {
708
  ctools_include('export');
709
  ctools_include('plugins');
710
  $handler = clone $handler;
711

    
712
  $append = '';
713
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'export')) {
714
    $append = $function($handler, $indent);
715
  }
716

    
717
  $output = ctools_export_object('page_manager_handlers', $handler, $indent);
718
  $output .= $append;
719

    
720
  return $output;
721
}
722

    
723
/**
724
 * Loads page manager handler for export.
725
 *
726
 * Callback to load page manager handler within ctools_export_crud_load().
727
 *
728
 * @param string $name
729
 *   The name of the handler to load.
730
 *
731
 * @return
732
 *   Loaded page manager handler object, extended with external properties.
733
 */
734
function page_manager_export_task_handler_load($name) {
735
  $table = 'page_manager_handlers';
736
  $schema = ctools_export_get_schema($table);
737
  $export = $schema['export'];
738

    
739
  $result = ctools_export_load_object($table, 'names', array($name));
740
  if (isset($result[$name])) {
741
    $handler = $result[$name];
742

    
743
    // Weight is stored in additional table so that in-code task handlers
744
    // don't need to get written to the database just because they have their
745
    // weight changed. Therefore, handler could have no correspondent database
746
    // entry. Revert will not be performed for this handler and the weight
747
    // will not be reverted. To make possible revert of the weight field
748
    // export_type must simulate that the handler is stored in the database.
749
    $handler->export_type = EXPORT_IN_DATABASE;
750

    
751
    // Also, page manager handler weight should be overriden with correspondent
752
    // weight from page_manager_weights table, if there is one.
753
    $result = db_query('SELECT weight FROM {page_manager_weights} WHERE name = (:names)', array(':names' => $handler->name))->fetchField();
754
    if (is_numeric($result)) {
755
      $handler->weight = $result;
756
    }
757
    return $handler;
758
  }
759
}
760

    
761
/**
762
 * Create a new task handler object.
763
 *
764
 * @param $plugin
765
 *   The plugin this task handler is created from.
766
 */
767
function page_manager_new_task_handler($plugin) {
768
  // Generate a unique name. Unlike most named objects, we don't let people choose
769
  // names for task handlers because they mostly don't make sense.
770

    
771
  // Create a new, empty handler object.
772
  $handler          = new stdClass;
773
  $handler->title   = $plugin['title'];
774
  $handler->task    = NULL;
775
  $handler->subtask = NULL;
776
  $handler->name    = NULL;
777
  $handler->handler = $plugin['name'];
778
  $handler->weight  = 0;
779
  $handler->conf    = array();
780

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

    
787
  if (isset($plugin['default conf'])) {
788
    if (is_array($plugin['default conf'])) {
789
      $handler->conf = $plugin['default conf'];
790
    }
791
    else if (function_exists($plugin['default conf'])) {
792
      $handler->conf = $plugin['default conf']($handler);
793
    }
794
  }
795

    
796
  return $handler;
797
}
798

    
799
/**
800
 * Set an overidden weight for a task handler.
801
 *
802
 * We do this so that in-code task handlers don't need to get written
803
 * to the database just because they have their weight changed.
804
 */
805
function page_manager_update_task_handler_weight($handler, $weight) {
806
  db_delete('page_manager_weights')
807
    ->condition('name', $handler->name)
808
    ->execute();
809
  db_insert('page_manager_weights')
810
    ->fields(array(
811
      'name' => $handler->name,
812
      'weight' => $weight,
813
    ))
814
    ->execute();
815
}
816

    
817

    
818
/**
819
 * Shortcut function to get task plugins.
820
 */
821
function page_manager_get_tasks() {
822
  ctools_include('plugins');
823
  return ctools_get_plugins('page_manager', 'tasks');
824
}
825

    
826
/**
827
 * Shortcut function to get a task plugin.
828
 */
829
function page_manager_get_task($id) {
830
  ctools_include('plugins');
831
  return ctools_get_plugins('page_manager', 'tasks', $id);
832
}
833

    
834
/**
835
 * Get all tasks for a given type.
836
 */
837
function page_manager_get_tasks_by_type($type) {
838
  ctools_include('plugins');
839
  $all_tasks = ctools_get_plugins('page_manager', 'tasks');
840
  $tasks = array();
841
  foreach ($all_tasks as $id => $task) {
842
    if (isset($task['task type']) && $task['task type'] == $type) {
843
      $tasks[$id] = $task;
844
    }
845
  }
846

    
847
  return $tasks;
848
}
849

    
850
/**
851
 * Fetch all subtasks for a page managertask.
852
 *
853
 * @param $task
854
 *   A loaded $task plugin object.
855
 */
856
function page_manager_get_task_subtasks($task) {
857
  if (empty($task['subtasks'])) {
858
    return array();
859
  }
860

    
861
  if ($function = ctools_plugin_get_function($task, 'subtasks callback')) {
862
    $retval = $function($task);
863
    if (is_array($retval)) {
864
      return $retval;
865
    }
866
  }
867

    
868
  return array();
869
}
870

    
871
/**
872
 * Fetch all subtasks for a page managertask.
873
 *
874
 * @param $task
875
 *   A loaded $task plugin object.
876
 * @param $subtask_id
877
 *   The subtask ID to load.
878
 */
879
function page_manager_get_task_subtask($task, $subtask_id) {
880
  if (empty($task['subtasks'])) {
881
    return;
882
  }
883

    
884
  if ($function = ctools_plugin_get_function($task, 'subtask callback')) {
885
    return $function($task, $subtask_id);
886
  }
887
}
888

    
889
/**
890
 * Shortcut function to get task handler plugins.
891
 */
892
function page_manager_get_task_handlers() {
893
  ctools_include('plugins');
894
  return ctools_get_plugins('page_manager', 'task_handlers');
895
}
896

    
897
/**
898
 * Shortcut function to get a task handler plugin.
899
 */
900
function page_manager_get_task_handler($id) {
901
  ctools_include('plugins');
902
  return ctools_get_plugins('page_manager', 'task_handlers', $id);
903
}
904

    
905
/**
906
 * Retrieve a list of all applicable task handlers for a given task.
907
 *
908
 * This looks at the $task['handler type'] and compares that to $task_handler['handler type'].
909
 * If the task has no type, the id of the task is used instead.
910
 */
911
function page_manager_get_task_handler_plugins($task, $all = FALSE) {
912
  $type = isset($task['handler type']) ? $task['handler type'] : $task['name'];
913
  $name = $task['name'];
914

    
915
  $handlers = array();
916
  $task_handlers = page_manager_get_task_handlers();
917
  foreach ($task_handlers as $id => $handler) {
918
    $task_type = is_array($handler['handler type']) ? $handler['handler type'] : array($handler['handler type']);
919
    if (in_array($type, $task_type) || in_array($name, $task_type)) {
920
      if ($all || !empty($handler['visible'])) {
921
        $handlers[$id] = $handler;
922
      }
923
    }
924
  }
925

    
926
  return $handlers;
927
}
928

    
929
/**
930
 * Get the title for a given handler.
931
 *
932
 * If the plugin has no 'admin title' function, the generic title of the
933
 * plugin is used instead.
934
 */
935
function page_manager_get_handler_title($plugin, $handler, $task, $subtask_id) {
936
  $function = ctools_plugin_get_function($plugin, 'admin title');
937
  if ($function) {
938
    return $function($handler, $task, $subtask_id);
939
  }
940
  else {
941
    return $plugin['title'];
942
  }
943
}
944

    
945
/**
946
 * Get the admin summary (additional info) for a given handler.
947
 */
948
function page_manager_get_handler_summary($plugin, $handler, $page, $title = TRUE) {
949
  if ($function = ctools_plugin_get_function($plugin, 'admin summary')) {
950
    return $function($handler, $page->task, $page->subtask, $page, $title);
951
  }
952
}
953

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

    
963
/**
964
 * Split a task name into a task id and subtask id, if applicable.
965
 */
966
function page_manager_get_task_id($task_name) {
967
  if (strpos($task_name, '-') !== FALSE) {
968
    return explode('-', $task_name, 2);
969
  }
970
  else {
971
    return array($task_name, NULL);
972
  }
973
}
974

    
975
/**
976
 * Turn a task id + subtask_id into a task name.
977
 */
978
function page_manager_make_task_name($task_id, $subtask_id) {
979
  if ($subtask_id) {
980
    return $task_id . '-' . $subtask_id;
981
  }
982
  else {
983
    return $task_id;
984
  }
985
}
986

    
987
/**
988
 * Get the render function for a handler.
989
 */
990
function page_manager_get_renderer($handler) {
991
  return ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'render');
992
}
993

    
994
// --------------------------------------------------------------------------
995
// Functions existing on behalf of tasks and task handlers
996

    
997

    
998
/**
999
 * Page manager arg load function because menu system will not load extra
1000
 * files for these; they must be in a .module.
1001
 */
1002
function pm_arg_load($value, $subtask, $argument) {
1003
  page_manager_get_task('page');
1004
  return _pm_arg_load($value, $subtask, $argument);
1005
}
1006

    
1007
/**
1008
 * Special arg_load function to use %menu_tail like functionality to
1009
 * get everything after the arg together as a single value.
1010
 */
1011
function pm_arg_tail_load($value, $subtask, $argument, $map) {
1012
  $value = implode('/', array_slice($map, $argument));
1013
  page_manager_get_task('page');
1014
  return _pm_arg_load($value, $subtask, $argument);
1015
}
1016

    
1017
/**
1018
 * Special menu _load() function for the user:uid argument.
1019
 *
1020
 * This is just the normal page manager argument. It only exists so that
1021
 * the to_arg can exist.
1022
 */
1023
function pm_uid_arg_load($value, $subtask, $argument) {
1024
  page_manager_get_task('page');
1025
  return _pm_arg_load($value, $subtask, $argument);
1026
}
1027

    
1028
/**
1029
 * to_arg function for the user:uid argument to provide the arg for the
1030
 * current global user.
1031
 */
1032
function pm_uid_arg_to_arg($arg) {
1033
  return user_uid_optional_to_arg($arg);
1034
}
1035

    
1036
/**
1037
 * Callback for access control ajax form on behalf of page.inc task.
1038
 *
1039
 * Returns the cached access config and contexts used.
1040
 */
1041
function page_manager_page_ctools_access_get($argument) {
1042
  $page = page_manager_get_page_cache($argument);
1043

    
1044
  $contexts = array();
1045

    
1046
  // Load contexts based on argument data:
1047
  if ($arguments = _page_manager_page_get_arguments($page->subtask['subtask'])) {
1048
    $contexts = ctools_context_get_placeholders_from_argument($arguments);
1049
  }
1050

    
1051
  return array($page->subtask['subtask']->access, $contexts);
1052
}
1053

    
1054
/**
1055
 * Callback for access control ajax form on behalf of page.inc task.
1056
 *
1057
 * Writes the changed access to the cache.
1058
 */
1059
function page_manager_page_ctools_access_set($argument, $access) {
1060
  $page = page_manager_get_page_cache($argument);
1061
  $page->subtask['subtask']->access = $access;
1062
  page_manager_set_page_cache($page);
1063
}
1064

    
1065
/**
1066
 * Callback for access control ajax form on behalf of context task handler.
1067
 *
1068
 * Returns the cached access config and contexts used.
1069
 */
1070
function page_manager_task_handler_ctools_access_get($argument) {
1071
  list($task_name, $name) = explode('*', $argument);
1072
  $page = page_manager_get_page_cache($task_name);
1073
  if (empty($name)) {
1074
    $handler = &$page->new_handler;
1075
  }
1076
  else {
1077
    $handler = &$page->handlers[$name];
1078
  }
1079

    
1080
  if (!isset($handler->conf['access'])) {
1081
    $handler->conf['access'] = array();
1082
  }
1083

    
1084
  ctools_include('context-task-handler');
1085

    
1086
  $contexts = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
1087

    
1088
  return array($handler->conf['access'], $contexts);
1089
}
1090

    
1091
/**
1092
 * Callback for access control ajax form on behalf of context task handler.
1093
 *
1094
 * Writes the changed access to the cache.
1095
 */
1096
function page_manager_task_handler_ctools_access_set($argument, $access) {
1097
  list($task_name, $name) = explode('*', $argument);
1098
  $page = page_manager_get_page_cache($task_name);
1099
  if (empty($name)) {
1100
    $handler = &$page->new_handler;
1101
  }
1102
  else {
1103
    $handler = &$page->handlers[$name];
1104
  }
1105

    
1106
  $handler->conf['access'] = $access;
1107
  page_manager_set_page_cache($page);
1108
}
1109

    
1110
/**
1111
 * Form a URL to edit a given page given the trail.
1112
 */
1113
function page_manager_edit_url($task_name, $trail = array()) {
1114
  if (!is_array($trail)) {
1115
    $trail = array($trail);
1116
  }
1117

    
1118
  if (empty($trail) || $trail == array('summary')) {
1119
    return "admin/structure/pages/edit/$task_name";
1120
  }
1121

    
1122
  return 'admin/structure/pages/nojs/operation/' . $task_name . '/' . implode('/', $trail);
1123
}
1124

    
1125
/**
1126
 * Watch menu links during the menu rebuild, and re-parent things if we need to.
1127
 */
1128
function page_manager_menu_link_alter(&$item) {
1129
  return;
1130
/** -- disabled, concept code --
1131
  static $mlids = array();
1132
  // Keep an array of mlids as links are saved that we can use later.
1133
  if (isset($item['mlid'])) {
1134
    $mlids[$item['path']] = $item['mlid'];
1135
  }
1136

    
1137
  if (isset($item['parent_path'])) {
1138
    if (isset($mlids[$item['parent_path']])) {
1139
      $item['plid'] = $mlids[$item['parent_path']];
1140
    }
1141
    else {
1142
      // Since we didn't already see an mlid, let's check the database for one.
1143
      $mlid = db_query('SELECT mlid FROM {menu_links} WHERE router_path = :path', array('path' => $item['parent_path']))->fetchField();
1144
      if ($mlid) {
1145
        $item['plid'] = $mlid;
1146
      }
1147
    }
1148
  }
1149
 */
1150
}
1151

    
1152
/**
1153
 * Callback to list handlers available for export.
1154
 */
1155
function page_manager_page_manager_handlers_list() {
1156
  $list = $types = array();
1157
  $tasks = page_manager_get_tasks();
1158
  foreach ($tasks as $type => $info) {
1159
    if (empty($info['non-exportable'])) {
1160
      $types[] = $type;
1161
    }
1162
  }
1163

    
1164
  $handlers = ctools_export_load_object('page_manager_handlers');
1165
  foreach ($handlers as $handler) {
1166
    if (in_array($handler->task, $types)) {
1167
      $plugin = page_manager_get_task_handler($handler->handler);
1168
      $title = page_manager_get_handler_title($plugin, $handler, $tasks[$handler->task], $handler->subtask);
1169

    
1170
      if ($title) {
1171
        $list[$handler->name] = check_plain("$handler->task: $title ($handler->name)");
1172
      }
1173
      else {
1174
        $list[$handler->name] = check_plain("$handler->task: ($handler->name)");
1175
      }
1176
    }
1177
  }
1178
  return $list;
1179
}
1180

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

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

    
1229
  return $current;
1230
}
1231

    
1232
/**
1233
 * Implementation of hook_panels_dashboard_blocks().
1234
 *
1235
 * Adds page information to the Panels dashboard.
1236
 */
1237
function page_manager_panels_dashboard_blocks(&$vars) {
1238
  $vars['links']['page_manager'] = array(
1239
    'weight' => -100,
1240
    'title' => l(t('Panel page'), 'admin/structure/pages/add'),
1241
    'description' => t('Panel pages can be used as landing pages. They have a URL path, accept arguments and can have menu entries.'),
1242
  );
1243

    
1244
  module_load_include('inc', 'page_manager', 'page_manager.admin');
1245
  $tasks = page_manager_get_tasks_by_type('page');
1246
  $pages = array('operations' => array());
1247

    
1248
  page_manager_get_pages($tasks, $pages);
1249
  $count = 0;
1250
  $rows = array();
1251
  foreach ($pages['rows'] as $id => $info) {
1252
    $rows[] = array(
1253
      'data' => array(
1254
        $info['data']['title'],
1255
        $info['data']['operations'],
1256
      ),
1257
      'class' => $info['class'],
1258
    );
1259

    
1260
    // Only show 10.
1261
    if (++$count >= 10) {
1262
      break;
1263
    }
1264
  }
1265

    
1266
  $vars['blocks']['page_manager'] = array(
1267
    'weight' => -100,
1268
    'title' => t('Manage pages'),
1269
    'link' => l(t('Go to list'), 'admin/structure/pages'),
1270
    'content' => theme('table', array('header' => array(), 'rows' => $rows, 'attributes' => array('class' => 'panels-manage'))),
1271
    'class' => 'dashboard-pages',
1272
    'section' => 'right',
1273
  );
1274
}
1275

    
1276
/**
1277
 * Implement pseudo-hook to fetch addressable content.
1278
 *
1279
 * For Page Manager, the address will be an array. The first
1280
 * element will be the $task and the second element will be the
1281
 * $task_handler. The third elements will be the arguments
1282
 * provided.
1283
 */
1284
function page_manager_addressable_content($address, $type) {
1285
  if (count($address) < 3) {
1286
    return;
1287
  }
1288

    
1289
  $task_name = array_shift($address);
1290
  $subtask_name = array_shift($address);
1291
  $handler_name = array_shift($address);
1292
  if ($address) {
1293
    $arguments = array_shift($address);
1294
  }
1295

    
1296
  // Since $arguments is an array of arbitrary size, we need to implode it:
1297
  if (!empty($arguments)) {
1298
    // The only choices we have for separators since :: is already
1299
    // used involve ., - or _. Since - and _ are more common than .
1300
    // in URLs, let's try .. as an argument separator.
1301
    $arguments = explode('..', $arguments);
1302
  }
1303
  else {
1304
    // implode does not return an empty array on an empty
1305
    // string so do it specifically.
1306
    $arguments = array();
1307
  }
1308

    
1309
  $task = page_manager_get_task($task_name);
1310
  if (!$task) {
1311
    return;
1312
  }
1313

    
1314
  $handler = page_manager_load_task_handler($task, $subtask_name, $handler_name);
1315
  if (!$handler) {
1316
    return;
1317
  }
1318

    
1319
  $handler_plugin = page_manager_get_task_handler($handler->handler);
1320
  if (!$handler_plugin) {
1321
    return;
1322
  }
1323

    
1324
  // Load the contexts for the task.
1325
  ctools_include('context');
1326
  ctools_include('context-task-handler');
1327
  $contexts = ctools_context_handler_get_task_contexts($task, $subtask_name, $arguments);
1328

    
1329
  // With contexts loaded, ensure the task is accessible. Tasks without a callback
1330
  // are automatically accessible.
1331
  $function = ctools_plugin_get_function($task, 'access callback');
1332
  if ($function && !$function($task, $subtask_name, $contexts)) {
1333
    return;
1334
  }
1335

    
1336
  $function = ctools_plugin_get_function($handler_plugin, 'addressable callback');
1337
  if ($function) {
1338
    return $function($task, $subtask_name, $handler, $address, $contexts, $arguments, $type);
1339
  }
1340
}