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 @ 6e3ce7c2

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

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

    
416
  page_manager_clear_page_cache($cache->task_name);
417

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

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

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

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

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

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

    
460
  return $name;
461
}
462

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

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

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

    
487
  $handler->name = $name;
488

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

    
497
// --------------------------------------------------------------------------
498
// Database routines
499
//
500
// This includes fetching plugins and plugin info as well as specialized
501
// fetch methods to get groups of task handlers per task.
502
/**
503
 * Load a single task handler by name.
504
 *
505
 * Handlers can come from multiple sources; either the database or by normal
506
 * export method, which is handled by the ctools library, but handlers can
507
 * also be bundled with task/subtask. We have to check there and perform
508
 * overrides as appropriate.
509
 *
510
 * Handlers bundled with the task are of a higher priority than default
511
 * handlers provided by normal code, and are of a lower priority than
512
 * the database, so we have to check the source of handlers when we have
513
 * multiple to choose from.
514
 */
515
function page_manager_load_task_handler($task, $subtask_id, $name) {
516
  ctools_include('export');
517
  $result = ctools_export_load_object('page_manager_handlers', 'names', array($name));
518
  $handlers = page_manager_get_default_task_handlers($task, $subtask_id);
519
  return page_manager_compare_task_handlers($result, $handlers, $name);
520
}
521

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

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

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

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

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

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

    
564
  return $handlers;
565
}
566

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

    
587
  return $handlers;
588
}
589

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

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

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

    
670
  return 0;
671
}
672

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

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

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

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

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

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

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

    
728
  return $output;
729
}
730

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

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

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

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

    
769
/**
770
 * Create a new task handler object.
771
 *
772
 * @param $plugin
773
 *   The plugin this task handler is created from.
774
 */
775
function page_manager_new_task_handler($plugin) {
776
  // Generate a unique name. Unlike most named objects, we don't let people choose
777
  // names for task handlers because they mostly don't make sense.
778
  // Create a new, empty handler object.
779
  $handler          = new stdClass();
780
  $handler->title   = $plugin['title'];
781
  $handler->task    = NULL;
782
  $handler->subtask = NULL;
783
  $handler->name    = NULL;
784
  $handler->handler = $plugin['name'];
785
  $handler->weight  = 0;
786
  $handler->conf    = array();
787

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

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

    
803
  return $handler;
804
}
805

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

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

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

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

    
853
  return $tasks;
854
}
855

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

    
867
  if ($function = ctools_plugin_get_function($task, 'subtasks callback')) {
868
    $retval = $function($task);
869
    if (is_array($retval)) {
870
      return $retval;
871
    }
872
  }
873

    
874
  return array();
875
}
876

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

    
890
  if ($function = ctools_plugin_get_function($task, 'subtask callback')) {
891
    return $function($task, $subtask_id);
892
  }
893
}
894

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

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

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

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

    
932
  return $handlers;
933
}
934

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

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

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

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

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

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

    
1000
// --------------------------------------------------------------------------
1001
// Functions existing on behalf of tasks and task handlers
1002

    
1003

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

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

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

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

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

    
1050
  $contexts = array();
1051

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

    
1057
  return array($page->subtask['subtask']->access, $contexts);
1058
}
1059

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

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

    
1086
  if (!isset($handler->conf['access'])) {
1087
    $handler->conf['access'] = array();
1088
  }
1089

    
1090
  ctools_include('context-task-handler');
1091

    
1092
  $contexts = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
1093

    
1094
  return array($handler->conf['access'], $contexts);
1095
}
1096

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

    
1112
  $handler->conf['access'] = $access;
1113
  page_manager_set_page_cache($page);
1114
}
1115

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

    
1124
  if (empty($trail) || $trail == array('summary')) {
1125
    return "admin/structure/pages/edit/$task_name";
1126
  }
1127

    
1128
  return 'admin/structure/pages/nojs/operation/' . $task_name . '/' . implode('/', $trail);
1129
}
1130

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

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

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

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

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

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

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

    
1235
  return $current;
1236
}
1237

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

    
1250
  module_load_include('inc', 'page_manager', 'page_manager.admin');
1251
  $tasks = page_manager_get_tasks_by_type('page');
1252
  $pages = array('operations' => array());
1253

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

    
1266
    // Only show 10.
1267
    if (++$count >= 10) {
1268
      break;
1269
    }
1270
  }
1271

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

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

    
1295
  $task_name = array_shift($address);
1296
  $subtask_name = array_shift($address);
1297
  $handler_name = array_shift($address);
1298
  if ($address) {
1299
    $arguments = array_shift($address);
1300
  }
1301

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

    
1315
  $task = page_manager_get_task($task_name);
1316
  if (!$task) {
1317
    return;
1318
  }
1319

    
1320
  $handler = page_manager_load_task_handler($task, $subtask_name, $handler_name);
1321
  if (!$handler) {
1322
    return;
1323
  }
1324

    
1325
  $handler_plugin = page_manager_get_task_handler($handler->handler);
1326
  if (!$handler_plugin) {
1327
    return;
1328
  }
1329

    
1330
  // Load the contexts for the task.
1331
  ctools_include('context');
1332
  ctools_include('context-task-handler');
1333
  $contexts = ctools_context_handler_get_task_contexts($task, $subtask_name, $arguments);
1334

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

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