Projet

Général

Profil

Paste
Télécharger (61,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / panels / panels.module @ 87dbc3bf

1
<?php
2

    
3
/**
4
 * @file panels.module
5
 *
6
 * Core functionality for the Panels engine.
7
 */
8

    
9
define('PANELS_REQUIRED_CTOOLS_API', '2.0-alpha');
10

    
11
define('PANELS_TITLE_FIXED', 0); // Hide title use to be true/false. So false remains old behavior.
12
define('PANELS_TITLE_NONE', 1); // And true meant no title.
13
define('PANELS_TITLE_PANE', 2); // And this is the new behavior, where the title field will pick from a pane.
14

    
15
/**
16
 * Returns the API version of Panels. This didn't exist in 1.
17
 *
18
 * @todo -- this should work more like the CTools API version.
19
 *
20
 * @return An array with the major and minor versions
21
 */
22
function panels_api_version() {
23
  return array(3, 1);
24
}
25

    
26
// --------------------------------------------------------------------------
27
// Core Drupal hook implementations
28

    
29
/**
30
 * Implementation of hook_theme()
31
 */
32
function panels_theme() {
33
  // Safety: go away if CTools is not at an appropriate version.
34
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
35
    return array();
36
  }
37

    
38
  $theme = array();
39
  $theme['panels_layout_link'] = array(
40
    'variables' => array('title' => NULL, 'id' => NULL, 'image' => NULL, 'link' => NULL, 'class' => NULL),
41
  );
42
  $theme['panels_layout_icon'] = array(
43
    'variables' => array('id' => NULL, 'image' => NULL, 'title' => NULL),
44
  );
45
  $theme['panels_pane'] = array(
46
    'variables' => array('output' => array(), 'pane' => array(), 'display' => array()),
47
    'path' => drupal_get_path('module', 'panels') . '/templates',
48
    'template' => 'panels-pane',
49
  );
50
  $theme['panels_common_content_list'] = array(
51
    'variables' => array('display' => NULL),
52
    'file' => 'includes/common.inc',
53
  );
54
  $theme['panels_render_display_form'] = array(
55
    'render element' => 'element',
56
  );
57

    
58
  $theme['panels_dashboard'] = array(
59
    'variables' => array(),
60
    'path' => drupal_get_path('module', 'panels') . '/templates',
61
    'file' => '../includes/callbacks.inc',
62
    'template' => 'panels-dashboard',
63
  );
64

    
65
  $theme['panels_dashboard_link'] = array(
66
    'variables' => array('link' => array()),
67
    'path' => drupal_get_path('module', 'panels') . '/templates',
68
    'file' => '../includes/callbacks.inc',
69
    'template' => 'panels-dashboard-link',
70
  );
71

    
72
  $theme['panels_dashboard_block'] = array(
73
    'variables' => array('block' => array()),
74
    'path' => drupal_get_path('module', 'panels') . '/templates',
75
    'file' => '../includes/callbacks.inc',
76
    'template' => 'panels-dashboard-block',
77
  );
78

    
79
  $theme['panels_add_content_modal'] = array(
80
    'variables' => array('renderer' => NULL, 'categories' => array(), 'region' => NULL, 'category' => NULL, 'column_count' => 2),
81
    'path' => drupal_get_path('module', 'panels') . '/templates',
82
    'file' => '../includes/add-content.inc',
83
    'template' => 'panels-add-content-modal',
84
  );
85

    
86
  $theme['panels_add_content_link'] = array(
87
    'variables' => array('renderer' => NULL, 'region' => NULL, 'content_type' => NULL),
88
    'path' => drupal_get_path('module', 'panels') . '/templates',
89
    'file' => '../includes/add-content.inc',
90
    'template' => 'panels-add-content-link',
91
  );
92

    
93
  // We don't need layout and style themes in maintenance mode.
94
  // Disabling this: See http://drupal.org/node/979912 for information.
95
//  if (defined('MAINTENANCE_MODE')) {
96
//    return $theme;
97
//  }
98

    
99
  // Register layout and style themes on behalf of all of these items.
100
  ctools_include('plugins', 'panels');
101

    
102
  // No need to worry about files; the plugin has to already be loaded for us
103
  // to even know what the theme function is, so files will be auto included.
104
  $layouts = panels_get_layouts();
105
  foreach ($layouts as $name => $data) {
106
    foreach (array('theme', 'admin theme') as $callback) {
107
      if (!empty($data[$callback])) {
108
        $theme[$data[$callback]] = array(
109
          'variables' => array('css_id' => NULL, 'content' => NULL, 'settings' => NULL, 'display' => NULL, 'layout' => NULL, 'renderer' => NULL),
110
          'path' => $data['path'],
111
          'file' => $data['file'],
112
        );
113

    
114
        // if no theme function exists, assume template.
115
        if (!function_exists("theme_$data[theme]")) {
116
          $theme[$data[$callback]]['template'] = str_replace('_', '-', $data[$callback]);
117
          $theme[$data[$callback]]['file'] = $data['file']; // for preprocess.
118
        }
119
      }
120
    }
121
  }
122

    
123
  $styles = panels_get_styles();
124
  foreach ($styles as $name => $data) {
125
    if (!empty($data['render pane'])) {
126
      $theme[$data['render pane']] = array(
127
        'variables' => array('content' => NULL, 'pane' => NULL, 'display' => NULL, 'style' => NULL, 'settings' => NULL),
128
        'path' => $data['path'],
129
        'file' => $data['file'],
130
      );
131
    }
132
    if (!empty($data['render region'])) {
133
      $theme[$data['render region']] = array(
134
        'variables' => array('display' => NULL, 'owner_id' => NULL, 'panes' => NULL, 'settings' => NULL, 'region_id' => NULL, 'style' => NULL),
135
        'path' => $data['path'],
136
        'file' => $data['file'],
137
      );
138
    }
139

    
140
    if (!empty($data['hook theme'])) {
141
      if (is_array($data['hook theme'])) {
142
        $theme += $data['hook theme'];
143
      }
144
      else if (function_exists($data['hook theme'])) {
145
        $data['hook theme']($theme, $data);
146
      }
147
    }
148
  }
149

    
150
  return $theme;
151
}
152

    
153
/**
154
 * Implementation of hook_menu
155
 */
156
function panels_menu() {
157
  // Safety: go away if CTools is not at an appropriate version.
158
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
159
    return array();
160
  }
161
  $items = array();
162

    
163
  // Base AJAX router callback.
164
  $items['panels/ajax'] = array(
165
    'access arguments' => array('access content'),
166
    'page callback' => 'panels_ajax_router',
167
    'theme callback' => 'ajax_base_page_theme',
168
    'delivery callback' => 'ajax_deliver',
169
    'type' => MENU_CALLBACK,
170
  );
171

    
172
  $admin_base = array(
173
    'file' => 'includes/callbacks.inc',
174
    'access arguments' => array('use panels dashboard'),
175
  );
176
  // Provide a nice location for a panels admin panel.
177
  $items['admin/structure/panels'] = array(
178
    'title' => 'Panels',
179
    'page callback' => 'panels_admin_page',
180
    'description' => 'Get a bird\'s eye view of items related to Panels.',
181
  ) + $admin_base;
182

    
183
  $items['admin/structure/panels/dashboard'] = array(
184
    'title' => 'Dashboard',
185
    'page callback' => 'panels_admin_page',
186
    'type' => MENU_DEFAULT_LOCAL_TASK,
187
    'weight' => -10,
188
  ) + $admin_base;
189

    
190
  $items['admin/structure/panels/settings'] = array(
191
    'title' => 'Settings',
192
    'page callback' => 'drupal_get_form',
193
    'page arguments' => array('panels_admin_settings_page'),
194
    'type' => MENU_LOCAL_TASK,
195
  ) + $admin_base;
196

    
197
  $items['admin/structure/panels/settings/general'] = array(
198
    'title' => 'General',
199
    'page callback' => 'drupal_get_form',
200
    'page arguments' => array('panels_admin_settings_page'),
201
    'access arguments' => array('administer page manager'),
202
    'type' => MENU_DEFAULT_LOCAL_TASK,
203
    'weight' => -10,
204
  ) + $admin_base;
205

    
206
  if (module_exists('page_manager')) {
207
    $items['admin/structure/panels/settings/panel-page'] = array(
208
      'title' => 'Panel pages',
209
      'page callback' => 'panels_admin_panel_context_page',
210
      'type' => MENU_LOCAL_TASK,
211
      'weight' => -10,
212
    ) + $admin_base;
213
  }
214

    
215
  ctools_include('plugins', 'panels');
216
  $layouts = panels_get_layouts();
217
  foreach ($layouts as $name => $data) {
218
    if (!empty($data['hook menu'])) {
219
      if (is_array($data['hook menu'])) {
220
        $items += $data['hook menu'];
221
      }
222
      else if (function_exists($data['hook menu'])) {
223
        $data['hook menu']($items, $data);
224
      }
225
    }
226
  }
227

    
228

    
229
  return $items;
230
}
231

    
232
/**
233
 * Menu loader function to load a cache item for Panels AJAX.
234
 *
235
 * This load all of the includes needed to perform AJAX, and loads the
236
 * cache object and makes sure it is valid.
237
 */
238
function panels_edit_cache_load($cache_key) {
239
  ctools_include('display-edit', 'panels');
240
  ctools_include('plugins', 'panels');
241
  ctools_include('ajax');
242
  ctools_include('modal');
243
  ctools_include('context');
244

    
245
  return panels_edit_cache_get($cache_key);
246
}
247

    
248
/**
249
 * Implementation of hook_init()
250
 */
251
function panels_init() {
252
  // Safety: go away if CTools is not at an appropriate version.
253
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
254
    if (user_access('administer site configuration')) {
255
      drupal_set_message(t('Panels is enabled but CTools is out of date. All Panels modules are disabled until CTools is updated. See the status page for more information.'), 'error');
256
    }
257
    return;
258
  }
259

    
260
  ctools_add_css('panels', 'panels');
261
}
262

    
263
/**
264
 * Implementation of hook_permission().
265
 *
266
 * @todo Almost all of these need to be moved into pipelines.
267
 */
268
function panels_permission() {
269
  return array(
270
    'use panels dashboard' => array(
271
      'title' => t("Use Panels Dashboard"),
272
      'description' => t("Allows a user to access the !link.", array('!link' => l('Panels Dashboard', 'admin/structure/panels'))),
273
    ),
274
    'view pane admin links' => array( // @todo
275
      'title' => t("View administrative links on Panel panes"),
276
      'description' => t(""),
277
    ),
278
    'administer pane access' => array( // @todo should we really have a global perm for this, or should it be moved into a pipeline question?
279
      'title' => t("Configure access settings on Panel panes"),
280
      'description' => t("Access rules (often also called visibility rules) can be configured on a per-pane basis. This permission allows users to configure those settings."),
281
    ),
282
    'use panels in place editing' => array(
283
      'title' => t("Use the Panels In-Place Editor"),
284
      'description' => t("Allows a user to utilize Panels' In-Place Editor."),
285
    ),
286
    'change layouts in place editing' => array(
287
      'title' => t("Change layouts with the Panels In-Place Editor"),
288
      'description' => t("Allows a user to change layouts with the IPE."),
289
    ),
290
    'administer advanced pane settings' => array(
291
      'title' => t("Configure advanced settings on Panel panes"),
292
      'description' => t(""),
293
    ),
294
    'administer panels layouts' => array(
295
      'title' => t("Administer Panels layouts"),
296
      'description' => t("Allows a user to administer exported Panels layout plugins & instances."),
297
    ),
298
    'administer panels styles' => array(
299
      'title' => t("Administer Panels styles"),
300
      'description' => t("Allows a user to administer the styles of Panel panes."),
301
    ),
302
    'use panels caching features' => array(
303
      'title' => t("Configure caching settings on Panels"),
304
      'description' => t("Allows a user to configure caching on Panels displays and panes."),
305
    ),
306
    'use panels locks' => array(
307
      'title' => t('Use panel locks'),
308
      'description' => t('Allows a user to lock and unlock panes in a panel display.'),
309
    ),
310
    'use ipe with page manager' => array(
311
      'title' => t("Use the Panels In-Place Editor with Page Manager"),
312
      'description' => t('Allows users with access to the In-Place editor to administer page manager pages. This permission is only needed for users without "use page manager" access.'),
313
    ),
314
  );
315
}
316

    
317
/**
318
 * Implementation of hook_flush_caches().
319
 *
320
 * We implement this so that we can be sure our legacy rendering state setting
321
 * in $conf is updated whenever caches are cleared.
322
 */
323
//function panels_flush_caches() {
324
//  $legacy = panels_get_legacy_state();
325
//  $legacy->determineStatus();
326
//}
327

    
328
/**
329
 * Implements hook_flush_caches().
330
 */
331
function panels_flush_caches() {
332
  return array('cache_panels');
333
}
334

    
335
// ---------------------------------------------------------------------------
336
// CTools hook implementations
337
//
338
// These aren't core Drupal hooks but they are just as important.
339

    
340
/**
341
 * Implementation of hook_ctools_plugin_directory() to let the system know
342
 * we implement task and task_handler plugins.
343
 */
344
function panels_ctools_plugin_directory($module, $plugin) {
345
  // Safety: go away if CTools is not at an appropriate version.
346
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
347
    return;
348
  }
349

    
350
  // We don't support the 'ctools' 'cache' plugin and pretending to causes
351
  // errors when they're in use.
352
  if ($module == 'ctools' && $plugin == 'cache') {
353
    return;
354
    // if we did we'd make a plugin/ctools_cache or something.
355
  }
356

    
357
  if ($module == 'page_manager' || $module == 'panels' || $module == 'ctools' || $module == 'stylizer') {
358
    // Panels and CTools both implement a 'cache' plugin but we don't implement
359
    // the CTools version.
360
    if ($module == 'ctools' && $plugin == 'cache') {
361
      return;
362
    }
363

    
364
    return 'plugins/' . $plugin;
365
  }
366
}
367

    
368
/**
369
 * Implements hook_ctools_plugin_type().
370
 *
371
 * Register layout, style, cache, and display_renderer plugin types, declaring
372
 * relevant plugin type information as necessary.
373
 */
374
function panels_ctools_plugin_type() {
375
  return array(
376
    'layouts' => array(
377
      'load themes' => TRUE, // Can define layouts in themes
378
      'process' => 'panels_layout_process',
379
      'child plugins' => TRUE,
380
    ),
381
    'styles' => array(
382
      'load themes' => TRUE,
383
      'process' => 'panels_plugin_styles_process',
384
      'child plugins' => TRUE,
385
    ),
386
    'cache' => array(),
387
    'display_renderers' => array(
388
      'classes' => array('renderer'),
389
    ),
390
  );
391
}
392

    
393
/**
394
 * Ensure a layout has a minimal set of data.
395
 */
396
function panels_layout_process(&$plugin) {
397
  $plugin += array(
398
    'category' => t('Miscellaneous'),
399
    'description' => '',
400
  );
401
}
402

    
403
/**
404
 * Implementation of hook_ctools_plugin_api().
405
 *
406
 * Inform CTools about version information for various plugins implemented by
407
 * Panels.
408
 *
409
 * @param string $owner
410
 *   The system name of the module owning the API about which information is
411
 *   being requested.
412
 * @param string $api
413
 *   The name of the API about which information is being requested.
414
 */
415
function panels_ctools_plugin_api($owner, $api) {
416
  if ($owner == 'panels' && $api == 'styles') {
417
    // As of 6.x-3.6, Panels has a slightly new system for style plugins.
418
    return array('version' => 2.0);
419
  }
420

    
421
  if ($owner == 'panels' && $api == 'pipelines') {
422
    return array(
423
      'version' => 1,
424
      'path' => drupal_get_path('module', 'panels') . '/includes',
425
    );
426
  }
427
}
428

    
429
/**
430
 * Implementation of hook_views_api().
431
 */
432
function panels_views_api() {
433
  return array(
434
    'api' => 2,
435
    'path' => drupal_get_path('module', 'panels') . '/plugins/views',
436
  );
437
}
438

    
439
/**
440
 * Perform additional processing on a style plugin.
441
 *
442
 * Currently this is only being used to apply versioning information to style
443
 * plugins in order to ensure the legacy renderer passes the right type of
444
 * parameters to a style plugin in a hybrid environment of both new and old
445
 * plugins.
446
 *
447
 * @see _ctools_process_data()
448
 *
449
 * @param array $plugin
450
 *   The style plugin that is being processed.
451
 * @param array $info
452
 *   The style plugin type info array.
453
 */
454
function panels_plugin_styles_process(&$plugin, $info) {
455
  $plugin += array(
456
    'weight' => 0,
457
  );
458

    
459
  $compliant_modules = ctools_plugin_api_info('panels', 'styles', 2.0, 2.0);
460
  $plugin['version'] = empty($compliant_modules[$plugin['module']]) ? 1.0 : $compliant_modules[$plugin['module']]['version'];
461
}
462

    
463
/**
464
 * Declare what style types Panels uses.
465
 */
466
function panels_ctools_style_base_types() {
467
  return array(
468
    'region' => array(
469
      'title' => t('Panel region'),
470
      'preview' => 'panels_stylizer_region_preview',
471
      'theme variables' => array('settings' => NULL, 'class' => NULL, 'content' => NULL),
472
    ),
473
    'pane' => array(
474
      'title' => t('Panel pane'),
475
      'preview' => 'panels_stylizer_pane_preview',
476
      'theme variables' => array('settings' => NULL, 'content' => NULL, 'pane' => NULL, 'display' => NULL),
477
    ),
478
  );
479
}
480

    
481
function panels_stylizer_lipsum() {
482
  return "
483
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at velit dolor. Donec egestas tellus sit amet urna rhoncus adipiscing. Proin nec porttitor sem. Maecenas aliquam, purus nec tempus dignissim, nulla arcu aliquam diam, non tincidunt massa ante vel dolor. Aliquam sapien sapien, tincidunt id tristique at, pretium sagittis libero.</p>
484

    
485
    <p>Nulla facilisi. Curabitur lacinia, tellus sed tristique consequat, diam lorem scelerisque felis, at dictum purus augue facilisis lorem. Duis pharetra dignissim rutrum. Curabitur ac elit id dui dapibus tincidunt. Nulla eget sem quam, non eleifend eros. Cras porttitor tempus lectus ac scelerisque. Curabitur vehicula bibendum lorem, vitae ornare ligula venenatis ut.</p>
486
  ";
487
}
488

    
489
/**
490
 * Generate a preview given the current settings.
491
 */
492
function panels_stylizer_region_preview($plugin, $settings) {
493
  ctools_stylizer_add_css($plugin, $settings);
494
  return theme($plugin['theme'], array('settings' => $settings, 'class' => ctools_stylizer_get_css_class($plugin, $settings), 'content' => panels_stylizer_lipsum()));
495
}
496

    
497
/**
498
 * Generate a preview given the current settings.
499
 */
500
function panels_stylizer_pane_preview($plugin, $settings) {
501
  ctools_stylizer_add_css($plugin, $settings);
502
  $pane = new stdClass();
503

    
504
  $content = new stdClass;
505
  $content->title = t('Lorem ipsum');
506
  $content->content = panels_stylizer_lipsum();
507
  $content->type = 'dummy';
508
  $content->subtype = 'dummy';
509

    
510
  $content->css_class = ctools_stylizer_get_css_class($plugin, $settings);
511

    
512
  $display = new panels_display();
513

    
514
  if (!empty($plugin['theme'])) {
515
    return theme($plugin['theme'], array('settings' => $settings, 'content' => $content, 'pane' => $pane, 'display' => $display));
516
  }
517
  else {
518
    return theme('panels_pane', array('content' => $content, 'pane' => $pane, 'display' => $display));
519
  }
520
}
521

    
522
// ---------------------------------------------------------------------------
523
// Panels display editing
524

    
525
/**
526
 * @defgroup mainapi Functions comprising the main panels API
527
 * @{
528
 */
529

    
530
/**
531
 * Main API entry point to edit a panel display.
532
 *
533
 * Sample implementations utiltizing the the complex $destination behavior can be found
534
 * in panels_page_edit_content() and, in a separate contrib module, OG Blueprints
535
 * (http://drupal.org/project/og_blueprints), og_blueprints_blueprint_edit().
536
 *
537
 * @ingroup mainapi
538
 *
539
 * @param object $display instanceof panels_display \n
540
 *  A fully loaded panels $display object, as returned from panels_load_display().
541
 *  Merely passing a did is NOT sufficient. \n
542
 *  Note that 'fully loaded' means the $display must already be loaded with any contexts
543
 *  the caller wishes to have set for the display.
544
 * @param mixed $destination \n
545
 *  The redirect destination that the user should be taken to on form submission or
546
 *  cancellation. With panels_edit, $destination has complex effects on the return
547
 *  values of panels_edit() once the form has been submitted. See the explanation of
548
 *  the return value below to understand the different types of values returned by panels_edit()
549
 *  at different stages of FAPI. Under most circumstances, simply passing in
550
 *  drupal_get_destination() is all that's necessary.
551
 * @param array $content_types \n
552
 *  An associative array of allowed content types, typically as returned from
553
 *  panels_common_get_allowed_types(). Note that context partially governs available content types,
554
 *  so you will want to create any relevant contexts using panels_create_context() or
555
 *  panels_create_context_empty() to make sure all the appropriate content types are available.
556
 *
557
 * @return
558
 *  Because the functions called by panels_edit() invoke the form API, this function
559
 *  returns different values depending on the stage of form submission we're at. In Drupal 5,
560
 *  the phase of form submission is indicated by the contents of $_POST['op']. Here's what you'll
561
 *  get at different stages:
562
 *    -# If !$_POST['op']: then we're on on the initial passthrough and the form is being
563
 *       rendered, so it's the $form itself that's being returned. Because negative margins,
564
 *       a common CSS technique, bork the display editor's ajax drag-and-drop, it's important
565
 *       that the $output be printed, not returned. Use this syntax in the caller function: \n
566
 *          print theme('page', panels_edit($display, $destination, $content_types), FALSE); \n
567
 *    -# If $_POST['op'] == t('Cancel'): form submission has been cancelled. If empty($destination) == FALSE,
568
 *       then there is no return value and the panels API takes care of redirecting to $destination.
569
 *       If empty($destination) == TRUE, then there's still no return value, but the caller function
570
 *       has to take care of form redirection.
571
 *    -# If $_POST['op'] == ('Save'): the form has been submitted successfully and has run through
572
 *        panels_edit_display_submit(). $output depends on the value of $destination:
573
 *      - If empty($destination) == TRUE: $output contains the modified $display
574
 *        object, and no redirection will occur. This option is useful if the caller
575
 *        needs to perform additional operations on or with the modified $display before
576
 *        the page request is complete. Using hook_form_alter() to add an additional submit
577
 *        handler is typically the preferred method for something like this, but there
578
 *        are certain use cases where that is infeasible and $destination = NULL should
579
 *        be used instead. If this method is employed, the caller will need to handle form
580
 *        redirection. Note that having $_REQUEST['destination'] set, whether via
581
 *        drupal_get_destination() or some other method, will NOT interfere with this
582
 *        functionality; consequently, you can use drupal_get_destination() to safely store
583
 *        your desired redirect in the caller function, then simply use drupal_goto() once
584
 *        panels_edit() has done its business.
585
 *      - If empty($destination) == FALSE: the form will redirect to the URL string
586
 *        given in $destination and NO value will be returned.
587
 */
588
function panels_edit($display, $destination = NULL, $content_types = NULL, $title = FALSE) {
589
  ctools_include('display-edit', 'panels');
590
  ctools_include('ajax');
591
  ctools_include('plugins', 'panels');
592
  return _panels_edit($display, $destination, $content_types, $title);
593
}
594

    
595
/**
596
 * API entry point for selecting a layout for a given display.
597
 *
598
 * Layout selection is nothing more than a list of radio items encompassing the available
599
 * layouts for this display, as defined by .inc files in the panels/layouts subdirectory.
600
 * The only real complexity occurs when a user attempts to change the layout of a display
601
 * that has some content in it.
602
 *
603
 * @param object $display instanceof panels_display \n
604
 *  A fully loaded panels $display object, as returned from panels_load_display().
605
 *  Merely passing a did is NOT sufficient.
606
 * @param string $finish
607
 *  A string that will be used for the text of the form submission button. If no value is provided,
608
 *  then the form submission button will default to t('Save').
609
 * @param mixed $destination
610
 *  Basic usage is a string containing the URL that the form should redirect to upon submission.
611
 *  For a discussion of advanced usages, see panels_edit().
612
 * @param mixed $allowed_layouts
613
 *  Allowed layouts has three different behaviors that depend on which of three value types
614
 *  are passed in by the caller:
615
 *    #- if $allowed_layouts instanceof panels_allowed_layouts (includes subclasses): the most
616
 *       complex use of the API. The caller is passing in a loaded panels_allowed_layouts object
617
 *       that the client module previously created and stored somewhere using a custom storage
618
 *       mechanism.
619
 *    #- if is_string($allowed_layouts): the string will be used in a call to variable_get() which
620
 *       will call the $allowed_layouts . '_allowed_layouts' var. If the data was stored properly
621
 *       in the system var, the $allowed_layouts object will be unserialized and recreated.
622
 *       @see panels_common_set_allowed_layouts()
623
 *    #- if is_null($allowed_layouts): the default behavior, which also provides backwards
624
 *       compatibility for implementations of the Panels2 API written before beta4. In this case,
625
 *       a dummy panels_allowed_layouts object is created which does not restrict any layouts.
626
 *       Subsequent behavior is indistinguishable from pre-beta4 behavior.
627
 *
628
 * @return
629
 *  Can return nothing, or a modified $display object, or a redirection string; return values for the
630
 *  panels_edit* family of functions are quite complex. See panels_edit() for detailed discussion.
631
 * @see panels_edit()
632
 */
633
function panels_edit_layout($display, $finish, $destination = NULL, $allowed_layouts = NULL) {
634
  ctools_include('display-layout', 'panels');
635
  ctools_include('plugins', 'panels');
636
  return _panels_edit_layout($display, $finish, $destination, $allowed_layouts);
637
}
638

    
639
// ---------------------------------------------------------------------------
640
// Panels database functions
641

    
642
/**
643
 * Forms the basis of a panel display
644
 *
645
 */
646
class panels_display {
647
  var $args = array();
648
  var $content = array();
649
  var $panels = array();
650
  var $incoming_content = NULL;
651
  var $css_id = NULL;
652
  var $context = array();
653
  var $did = 'new';
654
  var $renderer = 'standard';
655

    
656
  function add_pane(&$pane, $location = NULL) {
657
    // If no location specified, use what's set in the pane.
658
    if (empty($location)) {
659
      $location = $pane->panel;
660
    }
661
    else {
662
      $pane->panel = $location;
663
    }
664

    
665
    // Generate a permanent uuid for this pane, and use
666
    // it as a temporary pid.
667
    $pane->uuid = ctools_uuid_generate();
668
    $pane->pid = 'new-' . $pane->uuid;
669

    
670
    // Add the pane to the approprate spots.
671
    $this->content[$pane->pid] = &$pane;
672
    $this->panels[$location][] = $pane->pid;
673
  }
674

    
675
  function duplicate_pane($pid, $location = FALSE) {
676
    $pane = $this->clone_pane($pid);
677
    $this->add_pane($pane, $location);
678
  }
679

    
680
  function clone_pane($pid) {
681
    $pane = clone $this->content[$pid];
682
    $pane->uuid = ctools_uuid_generate();
683
    return $pane;
684
  }
685

    
686
  /**
687
   * Get the title from a display.
688
   *
689
   * The display must have already been rendered, or the setting to set the
690
   * display's title from a pane's title will not have worked.
691
   *
692
   * @return
693
   *   The title to use. If NULL, this means to let any default title that may be in use
694
   *   pass through. i.e, do not actually set the title.
695
   */
696
  function get_title() {
697
    switch ($this->hide_title) {
698
      case PANELS_TITLE_NONE:
699
        return '';
700

    
701
      case PANELS_TITLE_PANE:
702
        return isset($this->stored_pane_title) ? $this->stored_pane_title : '';
703

    
704
      case PANELS_TITLE_FIXED:
705
      case FALSE; // For old exported panels that are not in the database.
706
        if (!empty($this->title)) {
707
          return filter_xss_admin(ctools_context_keyword_substitute($this->title, array(), $this->context));
708
        }
709
        return NULL;
710
    }
711
  }
712

    
713
  /**
714
   * Render this panels display.
715
   *
716
   * After checking to ensure the designated layout plugin is valid, a
717
   * display renderer object is spawned and runs its rendering logic.
718
   *
719
   * @param mixed $renderer
720
   *    An instantiated display renderer object, or the name of a display
721
   *    renderer plugin+class to be fetched. Defaults to NULL. When NULL, the
722
   *    predesignated display renderer will be used.
723
   */
724
  function render($renderer = NULL) {
725
    $layout = panels_get_layout($this->layout);
726
    if (!$layout) {
727
      return NULL;
728
    }
729

    
730
    // If we were not given a renderer object, load it.
731
    if (!is_object($renderer)) {
732
      // If the renderer was not specified, default to $this->renderer
733
      // which is either standard or was already set for us.
734
      $renderer = panels_get_renderer_handler(!empty($renderer) ? $renderer : $this->renderer, $this);
735
      if (!$renderer) {
736
        return NULL;
737
      }
738
    }
739

    
740
    $output = '';
741
    // Let modules act just prior to render.
742
    foreach (module_implements('panels_pre_render') as $module) {
743
      $function = $module . '_panels_pre_render';
744
      $output .= $function($this, $renderer);
745
    }
746

    
747
    $output .= $renderer->render();
748

    
749
    // Let modules act just after render.
750
    foreach (module_implements('panels_post_render') as $module) {
751
      $function = $module . '_panels_post_render';
752
      $output .= $function($this, $renderer);
753
    }
754
    return $output;
755
  }
756
}
757

    
758
/**
759
 * }@ End of 'defgroup mainapi', although other functions are specifically added later
760
 */
761

    
762
/**
763
 * Creates a new display, setting the ID to our magic new id.
764
 */
765
function panels_new_display() {
766
  ctools_include('export');
767
  $display = ctools_export_new_object('panels_display', FALSE);
768
  $display->did = 'new';
769
  return $display;
770
}
771

    
772
/**
773
 * Create a new pane.
774
 *
775
 * @todo -- use schema API for some of this?
776
 */
777
function panels_new_pane($type, $subtype, $set_defaults = FALSE) {
778
  ctools_include('export');
779
  $pane = ctools_export_new_object('panels_pane', FALSE);
780
  $pane->pid = 'new';
781
  $pane->type = $type;
782
  $pane->subtype = $subtype;
783
  if ($set_defaults) {
784
    ctools_include('content');
785
    $content_type = ctools_get_content_type($type);
786
    $content_subtype = ctools_content_get_subtype($content_type, $subtype);
787
    $pane->configuration = ctools_content_get_defaults($content_type, $content_subtype);
788
  }
789

    
790
  return $pane;
791
}
792

    
793
/**
794
 * Load and fill the requested $display object(s).
795
 *
796
 * Helper function primarily for for panels_load_display().
797
 *
798
 * @param array $dids
799
 *  An indexed array of dids to be loaded from the database.
800
 *
801
 * @return $displays
802
 *  An array of displays, keyed by their display dids.
803
 *
804
 * @todo schema API can drasticly simplify this code.
805
 */
806
function panels_load_displays($dids) {
807
  $displays = array();
808
  if (empty($dids) || !is_array($dids)) {
809
    return $displays;
810
  }
811

    
812
  $result = db_query("SELECT * FROM {panels_display} WHERE did IN (:dids)", array(':dids' => $dids));
813

    
814
  ctools_include('export');
815
  foreach ($result as $obj) {
816
    $displays[$obj->did] = ctools_export_unpack_object('panels_display', $obj);
817
    // Modify the hide_title field to go from a bool to an int if necessary.
818
  }
819

    
820
  $result = db_query("SELECT * FROM {panels_pane} WHERE did IN (:dids) ORDER BY did, panel, position", array(':dids' => $dids));
821
  foreach ($result as $obj) {
822
    $pane = ctools_export_unpack_object('panels_pane', $obj);
823

    
824
    $displays[$pane->did]->panels[$pane->panel][] = $pane->pid;
825
    $displays[$pane->did]->content[$pane->pid] = $pane;
826
  }
827

    
828
  return $displays;
829
}
830

    
831
/**
832
 * Load a single display.
833
 *
834
 * @ingroup mainapi
835
 *
836
 * @param int $did
837
 *  The display id (did) of the display to be loaded.
838
 *
839
 * @return object $display instanceof panels_display \n
840
 *  Returns a partially-loaded panels_display object. $display objects returned from
841
 *  from this function have only the following data:
842
 *    - $display->did (the display id)
843
 *    - $display->name (the 'name' of the display, where applicable - it often isn't)
844
 *    - $display->layout (a string with the system name of the display's layout)
845
 *    - $display->panel_settings (custom layout style settings contained in an associative array; NULL if none)
846
 *    - $display->layout_settings (panel size and configuration settings for Flexible layouts; NULL if none)
847
 *    - $display->css_id (the special css_id that has been assigned to this display, if any; NULL if none)
848
 *    - $display->content (an array of pane objects, keyed by pane id (pid))
849
 *    - $display->panels (an associative array of panel regions, each an indexed array of pids in the order they appear in that region)
850
 *    - $display->cache (any relevant data from panels_simple_cache)
851
 *    - $display->args
852
 *    - $display->incoming_content
853
 *
854
 * While all of these members are defined, $display->context is NEVER defined in the returned $display;
855
 * it must be set using one of the ctools_context_create() functions.
856
 */
857
function panels_load_display($did) {
858
  $displays = panels_load_displays(array($did));
859
  if (!empty($displays)) {
860
    return array_shift($displays);
861
  }
862
}
863

    
864
/**
865
 * Save a display object.
866
 *
867
 * @ingroup mainapi
868
 *
869
 * Note that a new $display only receives a real did once it is run through
870
 * this function, and likewise for the pid of any new pane.
871
 *
872
 * Until then, a new display uses a string placeholder, 'new', in place of
873
 * a real did, and a new pane (whether on a new $display or not) appends a
874
 * universally-unique identifier (which is stored permanently in the 'uuid'
875
 * field). This format is also used in place of the real pid for exports.
876
 *
877
 * @param object $display instanceof panels_display \n
878
 *  The display object to be saved. Passed by reference so the caller need not use
879
 *  the return value for any reason except convenience.
880
 *
881
 * @return object $display instanceof panels_display \n
882
 */
883
function panels_save_display(&$display) {
884
  $update = (isset($display->did) && is_numeric($display->did)) ? array('did') : array();
885
  if (empty($display->uuid) || !ctools_uuid_is_valid($display->uuid)) {
886
    $display->uuid = ctools_uuid_generate();
887
  }
888
  drupal_write_record('panels_display', $display, $update);
889

    
890
  $pids = array();
891
  if ($update) {
892
    // Get a list of all panes currently in the database for this display so we can know if there
893
    // are panes that need to be deleted. (i.e, aren't currently in our list of panes).
894
    $result = db_query("SELECT pid FROM {panels_pane} WHERE did = :did", array(':did' => $display->did));
895
    foreach ($result as $pane) {
896
      $pids[$pane->pid] = $pane->pid;
897
    }
898
  }
899

    
900
  // update all the panes
901
  ctools_include('plugins', 'panels');
902
  ctools_include('content');
903

    
904
  foreach ($display->panels as $id => $panes) {
905
    $position = 0;
906
    $new_panes = array();
907
    foreach ((array) $panes as $pid) {
908
      if (!isset($display->content[$pid])) {
909
        continue;
910
      }
911
      $pane = $display->content[$pid];
912
      $type = ctools_get_content_type($pane->type);
913

    
914
      $pane->position = $position++;
915
      $pane->did = $display->did;
916

    
917
      $old_pid = $pane->pid;
918

    
919
      if (empty($pane->uuid) || !ctools_uuid_is_valid($pane->uuid)) {
920
        $pane->uuid = ctools_uuid_generate();
921
      }
922

    
923
      drupal_write_record('panels_pane', $pane, is_numeric($pid) ? array('pid') : array());
924

    
925
      // Allow other modules to take action after a pane is saved.
926
      if ($pane->pid == $old_pid) {
927
        module_invoke_all('panels_pane_update', $pane);
928
      }
929
      else {
930
        module_invoke_all('panels_pane_insert', $pane);
931
      }
932

    
933
      if ($pane->pid != $old_pid) {
934
        // Remove the old new-* entry from the displays content.
935
        unset($display->content[$pid]);
936

    
937
        // and put it back so our pids and positions can be used.
938
        $display->content[$pane->pid] = $pane;
939

    
940
        // If the title pane was one of our panes that just got its ID changed,
941
        // we need to change it in the database, too.
942
        if (isset($display->title_pane) && $display->title_pane == $old_pid) {
943
          $display->title_pane = $pane->pid;
944
          // Do a simple update query to write it so we don't have to rewrite
945
          // the whole record. We can't just save writing the whole record here
946
          // because it was needed to get the did. Chicken, egg, more chicken.
947
          db_update('panels_display')
948
            ->fields(array(
949
              'title_pane' => $pane->pid
950
            ))
951
            ->condition('did', $display->did)
952
            ->execute();
953
        }
954
      }
955

    
956
      // re-add this to the list of content for this panel.
957
      $new_panes[] = $pane->pid;
958

    
959
      // Remove this from the list of panes scheduled for deletion.
960
      if (isset($pids[$pane->pid])) {
961
        unset($pids[$pane->pid]);
962
      }
963
    }
964

    
965
    $display->panels[$id] = $new_panes;
966
  }
967
  if (!empty($pids)) {
968
    // Allow other modules to take action before a panes are deleted.
969
    module_invoke_all('panels_pane_delete', $pids);
970
    db_delete('panels_pane')->condition('pid', $pids)->execute();
971
  }
972

    
973
  // Clear any cached content for this display.
974
  panels_clear_cached_content($display);
975

    
976
  // Allow other modules to take action when a display is saved.
977
  module_invoke_all('panels_display_save', $display);
978

    
979
  // Log the change to watchdog, using the same style as node.module
980
  $watchdog_args = array('%did' => $display->did);
981
  if (!empty($display->title)) {
982
    $watchdog_args['%title'] = $display->title;
983
    watchdog('content', 'Panels: saved display "%title" with display id %did', $watchdog_args, WATCHDOG_NOTICE);
984
  }
985
  else {
986
    watchdog('content', 'Panels: saved display with id %did', $watchdog_args, WATCHDOG_NOTICE);
987
  }
988

    
989
  // to be nice, even tho we have a reference.
990
  return $display;
991
}
992

    
993
/**
994
 * Delete a display.
995
 */
996
function panels_delete_display($display) {
997
  if (is_object($display)) {
998
    $did = $display->did;
999
  }
1000
  else {
1001
    $did = $display;
1002
  }
1003
  module_invoke_all('panels_delete_display', $did);
1004
  db_delete('panels_display')->condition('did', $did)->execute();
1005
  db_delete('panels_pane')->condition('did', $did)->execute();
1006
}
1007

    
1008
/**
1009
 * Exports the provided display into portable code.
1010
 *
1011
 * This function is primarily intended as a mechanism for cloning displays.
1012
 * It generates an exact replica (in code) of the provided $display, with
1013
 * the exception that it replaces all ids (dids and pids) with place-holder
1014
 * values (consisting of the display or pane's uuid, with a 'new-' prefix).
1015
 *
1016
 * Only once panels_save_display() is called on the code version of $display
1017
 * will the exported display be written to the database and permanently saved.
1018
 *
1019
 * @see panels_page_export() or _panels_page_fetch_display() for sample implementations.
1020
 *
1021
 * @ingroup mainapi
1022
 *
1023
 * @param object $display instanceof panels_display \n
1024
 *  This export function does no loading of additional data about the provided
1025
 *  display. Consequently, the caller should make sure that all the desired data
1026
 *  has been loaded into the $display before calling this function.
1027
 * @param string $prefix
1028
 *  A string prefix that is prepended to each line of exported code. This is primarily
1029
 *  used for prepending a double space when exporting so that the code indents and lines up nicely.
1030
 *
1031
 * @return string $output
1032
 *  The passed-in $display expressed as code, ready to be imported. Import by running
1033
 *  eval($output) in the caller function; doing so will create a new $display variable
1034
 *  with all the exported values. Note that if you have already defined a $display variable in
1035
 *  the same scope as where you eval(), your existing $display variable WILL be overwritten.
1036
 */
1037
function panels_export_display($display, $prefix = '') {
1038
  ctools_include('export');
1039
  if (empty($display->uuid) || !ctools_uuid_is_valid($display->uuid)) {
1040
    $display->uuid = ctools_uuid_generate();
1041
  }
1042
  $display->did = 'new-' . $display->uuid;
1043
  $output = ctools_export_object('panels_display', $display, $prefix);
1044

    
1045
  // Initialize empty properties.
1046
  $output .= $prefix . '$display->content = array()' . ";\n";
1047
  $output .= $prefix . '$display->panels = array()' . ";\n";
1048
  $panels = array();
1049

    
1050
  $title_pid = 0;
1051
  if (!empty($display->content)) {
1052
    $region_counters = array();
1053
    foreach ($display->content as $pane) {
1054

    
1055
      if (!isset($pane->uuid) || !ctools_uuid_is_valid($pane->uuid)) {
1056
        $pane->uuid = ctools_uuid_generate();
1057
      }
1058
      $pid = 'new-' . $pane->uuid;
1059

    
1060
      if ($pane->pid == $display->title_pane) {
1061
        $title_pid = $pid;
1062
      }
1063
      $pane->pid = $pid;
1064
      $output .= ctools_export_object('panels_pane', $pane, $prefix . '  ');
1065
      $output .= "$prefix  " . '$display->content[\'' . $pane->pid . '\'] = $pane' . ";\n";
1066
      if (!isset($region_counters[$pane->panel])) {
1067
        $region_counters[$pane->panel] = 0;
1068
      }
1069
      $output .= "$prefix  " . '$display->panels[\'' . $pane->panel . '\'][' . $region_counters[$pane->panel]++ .'] = \'' . $pane->pid . "';\n";
1070
    }
1071
  }
1072
  $output .= $prefix . '$display->hide_title = ';
1073
  switch ($display->hide_title) {
1074
    case PANELS_TITLE_FIXED:
1075
      $output .= 'PANELS_TITLE_FIXED';
1076
      break;
1077
    case PANELS_TITLE_NONE:
1078
      $output .= 'PANELS_TITLE_NONE';
1079
      break;
1080
    case PANELS_TITLE_PANE:
1081
      $output .= 'PANELS_TITLE_PANE';
1082
      break;
1083
  }
1084
  $output .= ";\n";
1085

    
1086
  $output .= $prefix . '$display->title_pane =' . " '$title_pid';\n";
1087
  return $output;
1088
}
1089

    
1090
/**
1091
 * Render a display by loading the content into an appropriate
1092
 * array and then passing through to panels_render_layout.
1093
 *
1094
 * if $incoming_content is NULL, default content will be applied. Use
1095
 * an empty string to indicate no content.
1096
 * @ingroup hook_invocations
1097
 */
1098
function panels_render_display(&$display, $renderer = NULL) {
1099
  ctools_include('plugins', 'panels');
1100
  ctools_include('context');
1101

    
1102
  if (!empty($display->context)) {
1103
    if ($form_context = ctools_context_get_form($display->context)) {
1104
      $form_context->form['#theme'] = 'panels_render_display_form';
1105
      if (empty($form_context->form['#theme_wrappers']) || !in_array('form', $form_context->form['#theme_wrappers'])) {
1106
        $form_context['#theme_wrappers'][] = 'form';
1107
      }
1108
      $form_context->form['#display'] = &$display;
1109
      return $form_context->form;
1110
    }
1111
  }
1112
  return $display->render($renderer);
1113
}
1114

    
1115
/**
1116
 * Theme function to render our panel as a form.
1117
 *
1118
 * When rendering a display as a form, the entire display needs to be
1119
 * inside the <form> tag so that the form can be spread across the
1120
 * panes. This sets up the form system to be the main caller and we
1121
 * then operate as a theme function of the form.
1122
 */
1123
function theme_panels_render_display_form($vars) {
1124
  return $vars['element']['#display']->render();
1125
}
1126

    
1127
// @layout
1128
function panels_print_layout_icon($id, $layout, $title = NULL) {
1129
  ctools_add_css('panels_admin', 'panels');
1130
  $file = $layout['path'] . '/' . $layout['icon'];
1131
  return theme('panels_layout_icon', array('id' => $id, 'image' => theme('image', array('path' => $file, 'alt' => strip_tags($layout['title']), 'title' => strip_tags($layout['description']))), 'title' => $title));
1132
}
1133

    
1134
/**
1135
 * Theme the layout icon image
1136
 * @layout
1137
 * @todo move to theme.inc
1138
 */
1139
function theme_panels_layout_icon($vars) {
1140
  $id = $vars['id'];
1141
  $image = $vars['image'];
1142
  $title = $vars['title'];
1143

    
1144
  $output = '<div class="layout-icon">';
1145
  $output .= $image;
1146
  if ($title) {
1147
    $output .= '<div class="caption">' . $title . '</div>';
1148
  }
1149
  $output .= '</div>';
1150
  return $output;
1151
}
1152

    
1153
/**
1154
 * Theme the layout link image
1155
 * @layout
1156
 *
1157
 * @todo Why isn't this a template at this point?
1158
 * @todo Why does this take 4 arguments but only makes use of two?
1159
 */
1160
function theme_panels_layout_link($vars) {
1161
  $title = $vars['title'];
1162
  $image = $vars['image'];
1163
  $class = $vars['class'];
1164

    
1165
  $output = '<div class="' . implode(' ', $class) . '">';
1166
  $output .= $vars['image'];
1167
  $output .= '<div>' . $vars['title'] . '</div>';
1168
  $output .= '</div>';
1169
  return $output;
1170
}
1171

    
1172
/**
1173
 * Print the layout link. Sends out to a theme function.
1174
 * @layout
1175
 */
1176
function panels_print_layout_link($id, $layout, $link, $options = array(), $current_layout = FALSE) {
1177
  if (isset($options['query']['q'])) {
1178
    unset($options['query']['q']);
1179
  }
1180

    
1181
  // Setup classes for layout link, including current-layout information
1182
  $class = array('layout-link');
1183
  if ($current_layout == $id) {
1184
    $options['attributes']['class'][] = 'current-layout-link';
1185
    $class[] = 'current-layout';
1186
  }
1187

    
1188
  ctools_add_css('panels_admin', 'panels');
1189
  $file = $layout['path'] . '/' . $layout['icon'];
1190
  $image = l(theme('image', array('path' => $file)), $link, array('html' => true) + $options);
1191
  $title = l($layout['title'], $link, $options);
1192
  return theme('panels_layout_link', array('title' => $title, 'image' => $image, 'class' => $class));
1193
}
1194

    
1195

    
1196
/**
1197
 * Gateway to the PanelsLegacyState class/object, which does all legacy state
1198
 * checks and provides information about the cause of legacy states as needed.
1199
 *
1200
 * @return PanelsLegacyState $legacy
1201
 */
1202
function panels_get_legacy_state() {
1203
  static $legacy = NULL;
1204
  if (!isset($legacy)) {
1205
    ctools_include('legacy', 'panels');
1206
    $legacy = new PanelsLegacyState();
1207
  }
1208
  return $legacy;
1209
}
1210

    
1211
/**
1212
 * Get the display that is currently being rendered as a page.
1213
 *
1214
 * Unlike in previous versions of this, this only returns the display,
1215
 * not the page itself, because there are a number of different ways
1216
 * to get to this point. It is hoped that the page data isn't needed
1217
 * at this point. If it turns out there is, we will do something else to
1218
 * get that functionality.
1219
 */
1220
function panels_get_current_page_display($change = NULL) {
1221
  static $display = NULL;
1222
  if ($change) {
1223
    $display = $change;
1224
  }
1225

    
1226
  return $display;
1227
}
1228

    
1229
/**
1230
 * Clean up the panel pane variables for the template.
1231
 */
1232
function template_preprocess_panels_pane(&$vars) {
1233
  $content = &$vars['content'];
1234

    
1235
  $vars['contextual_links'] = array();
1236
  $vars['classes_array'] = array();
1237
  $vars['admin_links'] = '';
1238

    
1239
  if (module_exists('contextual') && user_access('access contextual links')) {
1240
    $links = array();
1241
    // These are specified by the content.
1242
    if (!empty($content->admin_links)) {
1243
      $links += $content->admin_links;
1244
    }
1245

    
1246
    // Take any that may have been in the render array we were given and
1247
    // move them up so they appear outside the pane properly.
1248
    if (is_array($content->content) && isset($content->content['#contextual_links'])) {
1249
      $element = array(
1250
        '#type' => 'contextual_links',
1251
        '#contextual_links' => $content->content['#contextual_links'],
1252
      );
1253
      unset($content->content['#contextual_links']);
1254

    
1255
      // Add content to $element array
1256
      if (is_array($content->content)) {
1257
        $element['#element'] = $content->content;
1258
      }
1259

    
1260
      $element = contextual_pre_render_links($element);
1261
      if(!empty($element['#links'])) {
1262
        $links += $element['#links'];
1263
      }
1264
    }
1265

    
1266
    if ($links) {
1267
      $build = array(
1268
        '#prefix' => '<div class="contextual-links-wrapper">',
1269
        '#suffix' => '</div>',
1270
        '#theme' => 'links__contextual',
1271
        '#links' => $links,
1272
        '#attributes' => array('class' => array('contextual-links')),
1273
        '#attached' => array(
1274
          'library' => array(array('contextual', 'contextual-links')),
1275
        ),
1276
      );
1277
      $vars['classes_array'][] = 'contextual-links-region';
1278
      $vars['admin_links'] = drupal_render($build);
1279
    }
1280
  }
1281

    
1282
  // basic classes
1283
  $vars['classes_array'][] = 'panel-pane';
1284
  $vars['id'] = '';
1285

    
1286
  // Add some usable classes based on type/subtype
1287
  ctools_include('cleanstring');
1288
  $type_class = $content->type ? 'pane-'. ctools_cleanstring($content->type, array('lower case' => TRUE)) : '';
1289
  $subtype_class = $content->subtype ? 'pane-'. ctools_cleanstring($content->subtype, array('lower case' => TRUE)) : '';
1290

    
1291
  // Sometimes type and subtype are the same. Avoid redundant classes.
1292
  $vars['classes_array'][] = $type_class;
1293
  if ($type_class != $subtype_class) {
1294
    $vars['classes_array'][] = $subtype_class;
1295
  }
1296

    
1297
  // Add id and custom class if sent in.
1298
  if (!empty($content->content)) {
1299
    if (!empty($content->css_id)) {
1300
      $vars['id'] = ' id="' . $content->css_id . '"';
1301
    }
1302
    if (!empty($content->css_class)) {
1303
      $vars['classes_array'][] = $content->css_class;
1304
    }
1305
  }
1306

    
1307
  // Set up some placeholders for constructing template file names.
1308
  $base = 'panels_pane';
1309
  $delimiter = '__';
1310

    
1311
  // Add template file suggestion for content type and sub-type.
1312
  $vars['theme_hook_suggestions'][] = $base . $delimiter . $content->type;
1313
  $vars['theme_hook_suggestions'][] = $base . $delimiter . strtr(ctools_cleanstring($content->type, array('lower case' => TRUE)), '-', '_') . $delimiter . strtr(ctools_cleanstring($content->subtype, array('lower case' => TRUE)), '-', '_');
1314

    
1315
  $vars['pane_prefix'] = !empty($content->pane_prefix) ? $content->pane_prefix : '';
1316
  $vars['pane_suffix'] = !empty($content->pane_suffix) ? $content->pane_suffix : '';
1317

    
1318
  $vars['title'] = !empty($content->title) ? $content->title : '';
1319
  $vars['title_attributes_array']['class'][] = 'pane-title';
1320

    
1321
  $vars['feeds'] = !empty($content->feeds) ? implode(' ', $content->feeds) : '';
1322

    
1323
  $vars['links'] = !empty($content->links) ? theme('links', array('links' => $content->links)) : '';
1324
  $vars['more'] = '';
1325
  if (!empty($content->more)) {
1326
    if (empty($content->more['title'])) {
1327
      $content->more['title'] = t('more');
1328
    }
1329
    $vars['more'] = l($content->more['title'], $content->more['href'], $content->more);
1330
  }
1331

    
1332
  $vars['content'] = !empty($content->content) ? $content->content : '';
1333

    
1334
}
1335

    
1336
/**
1337
 * Route Panels' AJAX calls to the correct object.
1338
 *
1339
 * Panels' AJAX is controlled mostly by renderer objects. This menu callback
1340
 * accepts the incoming request, figures out which object should handle the
1341
 * request, and attempts to route it. If no object can be found, the default
1342
 * Panels editor object is used.
1343
 *
1344
 * Calls are routed via the ajax_* method space. For example, if visiting
1345
 * panels/ajax/add-pane then $renderer::ajax_add_pane() will be called.
1346
 * This means commands can be added without having to create new callbacks.
1347
 *
1348
 * The first argument *must always* be the cache key so that a cache object
1349
 * can be passed through. Other arguments will be passed through untouched
1350
 * so that the method can do whatever it needs to do.
1351
 */
1352
function panels_ajax_router() {
1353
  $args = func_get_args();
1354
  if (count($args) < 3) {
1355
    return MENU_NOT_FOUND;
1356
  }
1357

    
1358
  ctools_include('display-edit', 'panels');
1359
  ctools_include('plugins', 'panels');
1360
  ctools_include('ajax');
1361
  ctools_include('modal');
1362
  ctools_include('context');
1363
  ctools_include('content');
1364

    
1365
  $plugin_name = array_shift($args);
1366
  $method = array_shift($args);
1367
  $cache_key = array_shift($args);
1368

    
1369
  $plugin = panels_get_display_renderer($plugin_name);
1370
  if (!$plugin) {
1371
    // This is the default renderer for handling AJAX commands.
1372
    $plugin = panels_get_display_renderer('editor');
1373
  }
1374

    
1375
  $cache = panels_edit_cache_get($cache_key);
1376
  if (empty($cache)) {
1377
    return MENU_ACCESS_DENIED;
1378
  }
1379

    
1380
  $renderer = panels_get_renderer_handler($plugin, $cache->display);
1381
  if (!$renderer) {
1382
    return MENU_ACCESS_DENIED;
1383
  }
1384

    
1385
  $method = 'ajax_' . str_replace('-', '_', $method);
1386
  if (!method_exists($renderer, $method)) {
1387
    return MENU_NOT_FOUND;
1388
  }
1389

    
1390
  $renderer->cache = &$cache;
1391
  ctools_include('cleanstring');
1392
  $renderer->clean_key = ctools_cleanstring($cache_key);
1393

    
1394
  $output = call_user_func_array(array($renderer, $method), $args);
1395

    
1396
  if (empty($output) && !empty($renderer->commands)) {
1397
    return array(
1398
      '#type' => 'ajax',
1399
      '#commands' => $renderer->commands,
1400
    );
1401
  }
1402
  else {
1403
    return $output;
1404
  }
1405
}
1406

    
1407
// --------------------------------------------------------------------------
1408
// Panels caching functions and callbacks
1409
//
1410
// When editing displays and the like, Panels has a caching system that relies
1411
// on a callback to determine where to get the actual cache.
1412

    
1413
// @todo This system needs to be better documented so that it can be
1414
// better used.
1415

    
1416
/**
1417
 * Get an object from cache.
1418
 */
1419
function panels_cache_get($obj, $did, $skip_cache = FALSE) {
1420
  ctools_include('object-cache');
1421
  // we often store contexts in cache, so let's just make sure we can load
1422
  // them.
1423
  ctools_include('context');
1424
  return ctools_object_cache_get($obj, 'panels_display:' . $did, $skip_cache);
1425
}
1426

    
1427
/**
1428
 * Save the edited object into the cache.
1429
 */
1430
function panels_cache_set($obj, $did, $cache) {
1431
  ctools_include('object-cache');
1432
  return ctools_object_cache_set($obj, 'panels_display:' . $did, $cache);
1433
}
1434

    
1435
/**
1436
 * Clear a object from the cache; used if the editing is aborted.
1437
 */
1438
function panels_cache_clear($obj, $did) {
1439
  ctools_include('object-cache');
1440
  return ctools_object_cache_clear($obj, 'panels_display:' . $did);
1441
}
1442

    
1443
/**
1444
 * Create the default cache for editing panel displays.
1445
 *
1446
 * If an application is using the Panels display editor without having
1447
 * specified a cache key, this method can be used to create the default
1448
 * cache.
1449
 */
1450
function panels_edit_cache_get_default(&$display, $content_types = NULL, $title = FALSE) {
1451
  if (empty($content_types)) {
1452
    $content_types = ctools_content_get_available_types();
1453
  }
1454

    
1455
  $display->cache_key = $display->did;
1456
  panels_cache_clear('display', $display->did);
1457

    
1458
  $cache = new stdClass();
1459
  $cache->display = &$display;
1460
  $cache->content_types = $content_types;
1461
  $cache->display_title = $title;
1462

    
1463
  panels_edit_cache_set($cache);
1464
  return $cache;
1465
}
1466

    
1467
/**
1468
 * Method to allow modules to provide their own caching mechanism for the
1469
 * display editor.
1470
 */
1471
function panels_edit_cache_get($cache_key) {
1472
  if (strpos($cache_key, ':') !== FALSE) {
1473
    list($module, $argument) = explode(':', $cache_key, 2);
1474
    return module_invoke($module, 'panels_cache_get', $argument);
1475
  }
1476

    
1477
  // Fall back to our normal method:
1478
  return panels_cache_get('display', $cache_key);
1479
}
1480

    
1481
/**
1482
 * Method to allow modules to provide their own caching mechanism for the
1483
 * display editor.
1484
 */
1485
function panels_edit_cache_set($cache) {
1486
  $cache_key = $cache->display->cache_key;
1487
  if (strpos($cache_key, ':') !== FALSE) {
1488
    list($module, $argument) = explode(':', $cache_key, 2);
1489
    return module_invoke($module, 'panels_cache_set', $argument, $cache);
1490
  }
1491

    
1492
  // Fall back to our normal method:
1493
  return panels_cache_set('display', $cache_key, $cache);
1494
}
1495

    
1496
/**
1497
 * Method to allow modules to provide their own mechanism to write the
1498
 * cache used in the display editor.
1499
 */
1500
function panels_edit_cache_save($cache) {
1501
  $cache_key = $cache->display->cache_key;
1502
  if (strpos($cache_key, ':') !== FALSE) {
1503
    list($module, $argument) = explode(':', $cache_key, 2);
1504
    if (function_exists($module . '_panels_cache_save')) {
1505
      return module_invoke($module, 'panels_cache_save', $argument, $cache);
1506
    }
1507
  }
1508

    
1509
  // Fall back to our normal method:
1510
  return panels_save_display($cache->display);
1511
}
1512

    
1513
/**
1514
 * Method to allow modules to provide their own mechanism to clear the
1515
 * cache used in the display editor.
1516
 */
1517
function panels_edit_cache_clear($cache) {
1518
  $cache_key = $cache->display->cache_key;
1519
  if (strpos($cache_key, ':') !== FALSE) {
1520
    list($module, $argument) = explode(':', $cache_key, 2);
1521
    if (function_exists($module . '_panels_cache_clear')) {
1522
      return module_invoke($module, 'panels_cache_clear', $argument, $cache);
1523
    }
1524
  }
1525

    
1526
  // Fall back to our normal method:
1527
  return panels_cache_clear('display', $cache_key);
1528
}
1529

    
1530
/**
1531
 * Method to allow modules to provide a mechanism to break locks.
1532
 */
1533
function panels_edit_cache_break_lock($cache) {
1534
  if (empty($cache->locked)) {
1535
    return;
1536
  }
1537

    
1538
  $cache_key = $cache->display->cache_key;
1539
  if (strpos($cache_key, ':') !== FALSE) {
1540
    list($module, $argument) = explode(':', $cache_key, 2);
1541
    if (function_exists($module . '_panels_cache_break_lock')) {
1542
      return module_invoke($module, 'panels_cache_break_lock', $argument, $cache);
1543
    }
1544
  }
1545

    
1546
  // Normal panel display editing has no locks, so we do nothing if there is
1547
  // no fallback.
1548
  return;
1549
}
1550

    
1551
// --------------------------------------------------------------------------
1552
// Callbacks on behalf of the panel_context plugin.
1553
//
1554
// The panel_context plugin lets Panels be used in page manager. These
1555
// callbacks allow the display editing system to use the page manager
1556
// cache rather than the default display cache. They are routed by the cache
1557
// key via panels_edit_cache_* functions.
1558

    
1559
/**
1560
 * Get display edit cache on behalf of panel context.
1561
 *
1562
 * The key is the second half of the key in this form:
1563
 * panel_context:TASK_NAME::HANDLER_NAME::args::url;
1564
 */
1565
function panel_context_panels_cache_get($key) {
1566
  ctools_include('common', 'panels');
1567
  ctools_include('context');
1568
  ctools_include('context-task-handler');
1569
  // this loads the panel context inc even if we don't use the plugin.
1570
  $plugin = page_manager_get_task_handler('panel_context');
1571

    
1572
  list($task_name, $handler_name, $args, $q) = explode('::', $key, 4);
1573
  $page = page_manager_get_page_cache($task_name);
1574
  if (isset($page->display_cache[$handler_name])) {
1575
    return $page->display_cache[$handler_name];
1576
  }
1577

    
1578
  if ($handler_name) {
1579
    $handler = &$page->handlers[$handler_name];
1580
  }
1581
  else {
1582
    $handler = &$page->new_handler;
1583
  }
1584
  $cache = new stdClass();
1585

    
1586
  $task = page_manager_get_task($page->task_id);
1587
  //ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
1588
  $arguments = array();
1589
  if ($args) {
1590
    $arguments = explode('\\', $args);
1591
    $contexts = ctools_context_handler_get_task_contexts($task, $page->subtask, $arguments);
1592
    $contexts = ctools_context_handler_get_handler_contexts($contexts, $handler);
1593
  }
1594
  else {
1595
    $contexts = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
1596
  }
1597

    
1598
  $cache->display = &panels_panel_context_get_display($handler);
1599
  $cache->display->context = $contexts;
1600
  $cache->display->cache_key = 'panel_context:' . $key;
1601
  $cache->content_types = panels_common_get_allowed_types('panels_page', $cache->display->context);
1602
  $cache->display_title = TRUE;
1603
  $cache->locked = $page->locked;
1604

    
1605
  return $cache;
1606
}
1607

    
1608
/**
1609
 * Get the Page Manager cache for the panel_context plugin.
1610
 */
1611
function _panel_context_panels_cache_get_page_cache($key, $cache) {
1612
  list($task_name, $handler_name, $args, $q) = explode('::', $key, 4);
1613
  $page = page_manager_get_page_cache($task_name);
1614
  $page->display_cache[$handler_name] = $cache;
1615
  if ($handler_name) {
1616
    $page->handlers[$handler_name]->conf['display'] = $cache->display;
1617
    $page->handler_info[$handler_name]['changed'] |= PAGE_MANAGER_CHANGED_CACHED;
1618
  }
1619
  else {
1620
    $page->new_handler->conf['display'] = $cache->display;
1621
  }
1622

    
1623
  return $page;
1624
}
1625

    
1626
/**
1627
 * Store a display edit in progress in the page cache.
1628
 */
1629
function panel_context_panels_cache_set($key, $cache) {
1630
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
1631
  page_manager_set_page_cache($page);
1632
}
1633

    
1634
/**
1635
 * Save all changes made to a display using the Page Manager page cache.
1636
 */
1637
function panel_context_panels_cache_clear($key, $cache) {
1638
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
1639
  page_manager_clear_page_cache($page->task_name);
1640
}
1641

    
1642
/**
1643
 * Save all changes made to a display using the Page Manager page cache.
1644
 */
1645
function panel_context_panels_cache_save($key, $cache) {
1646
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
1647
  page_manager_save_page_cache($page);
1648
}
1649

    
1650
/**
1651
 * Break the lock on a page manager page.
1652
 */
1653
function panel_context_panels_cache_break_lock($key, $cache) {
1654
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
1655
  ctools_object_cache_clear_all('page_manager_page', $page->task_name);
1656
}
1657

    
1658
// --------------------------------------------------------------------------
1659
// Callbacks on behalf of the panels page wizards
1660
//
1661
// The page wizards are a pluggable set of 'wizards' to make it easy to create
1662
// specific types of pages based upon whatever someone felt like putting
1663
// together. Since they will very often have content editing, we provide
1664
// a generic mechanism to allow them to store their editing cache in the
1665
// wizard cache.
1666
//
1667
// For them to use this mechanism, they just need to use:
1668
//   $cache = panels_edit_cache_get('panels_page_wizard:' . $plugin['name']);
1669

    
1670
/**
1671
 * Get display edit cache for the panels mini export UI
1672
 *
1673
 * The key is the second half of the key in this form:
1674
 * panels_page_wizard:TASK_NAME:HANDLER_NAME;
1675
 */
1676
function panels_page_wizard_panels_cache_get($key) {
1677
  ctools_include('page-wizard');
1678
  ctools_include('context');
1679
  $wizard_cache = page_manager_get_wizard_cache($key);
1680
  if (isset($wizard_cache->display_cache)) {
1681
    return $wizard_cache->display_cache;
1682
  }
1683

    
1684
  ctools_include('common', 'panels');
1685
  $cache = new stdClass();
1686
  $cache->display = $wizard_cache->display;
1687
  $cache->display->context = !empty($wizard_cache->context) ? $wizard_cache->context : array();
1688
  $cache->display->cache_key = 'panels_page_wizard:' . $key;
1689
  $cache->content_types = panels_common_get_allowed_types('panels_page', $cache->display->context);
1690
  $cache->display_title = TRUE;
1691

    
1692
  return $cache;
1693
}
1694

    
1695
/**
1696
 * Store a display edit in progress in the page cache.
1697
 */
1698
function panels_page_wizard_panels_cache_set($key, $cache) {
1699
  ctools_include('page-wizard');
1700
  $wizard_cache = page_manager_get_wizard_cache($key);
1701
  $wizard_cache->display_cache = $cache;
1702
  page_manager_set_wizard_cache($wizard_cache);
1703
}
1704

    
1705
// --------------------------------------------------------------------------
1706
// General utility functions
1707

    
1708
/**
1709
 * Perform a drupal_goto on a destination that may be an array like url().
1710
 */
1711
function panels_goto($destination) {
1712
  if (!is_array($destination)) {
1713
    return drupal_goto($destination);
1714
  }
1715
  else {
1716
    // Prevent notices by adding defaults
1717
    $destination += array(
1718
      'query' => NULL,
1719
      'fragment' => NULL,
1720
      'http_response_code' => NULL,
1721
    );
1722

    
1723
    return drupal_goto($destination['path'], $destination['query'], $destination['fragment'], $destination['http_response_code']);
1724
  }
1725
}
1726

    
1727

    
1728
/**
1729
 * For external use: Given a layout ID and a $content array, return the
1730
 * panel display.
1731
 *
1732
 * The content array is filled in based upon the content available in the
1733
 * layout. If it's a two column with a content array defined like
1734
 * @code
1735
 *   array(
1736
 *    'left' => t('Left side'),
1737
 *    'right' => t('Right side')
1738
 *  ),
1739
 * @endcode
1740
 *
1741
 * Then the $content array should be
1742
 * @code
1743
 * array(
1744
 *   'left' => $output_left,
1745
 *   'right' => $output_right,
1746
 * )
1747
 * @endcode
1748
 *
1749
 * The output within each panel region can be either a single rendered
1750
 * HTML string or an array of rendered HTML strings as though they were
1751
 * panes. They will simply be concatenated together without separators.
1752
 */
1753
function panels_print_layout($layout, $content, $meta = 'standard') {
1754
  ctools_include('plugins', 'panels');
1755

    
1756
  // Create a temporary display for this.
1757
  $display = panels_new_display();
1758
  $display->layout = is_array($layout) ? $layout['name'] : $layout;
1759
  $display->content = $content;
1760

    
1761
  // Get our simple renderer
1762
  $renderer = panels_get_renderer_handler('simple', $display);
1763
  $renderer->meta_location = $meta;
1764

    
1765
  return $renderer->render();
1766
}
1767

    
1768
/**
1769
 * Filter callback for array_filter to remove builders from a list of layouts.
1770
 */
1771
function _panels_builder_filter($layout) {
1772
  return empty($layout['builder']);
1773
}
1774

    
1775
// --------------------------------------------------------------------------
1776
// Deprecated functions
1777
//
1778
// Everything below this line will eventually go away.
1779

    
1780
/**
1781
 * panels path helper function
1782
 */
1783
function panels_get_path($file, $base_path = FALSE, $module = 'panels') {
1784
  $output = $base_path ? base_path() : '';
1785
  return $output . drupal_get_path('module', $module) . '/' . $file;
1786
}
1787

    
1788
/**
1789
 * Remove default sidebar related body classes and provide own css classes
1790
 */
1791
function panels_preprocess_html(&$vars) {
1792
  $panel_body_css = &drupal_static('panel_body_css');
1793
  if (!empty($panel_body_css['body_classes_to_remove'])) {
1794
    $classes_to_remove = explode(' ', $panel_body_css['body_classes_to_remove']);
1795
    foreach ($vars['classes_array'] as $key => $css_class) {
1796
      if (in_array($css_class, $classes_to_remove)) {
1797
        unset($vars['classes_array'][$key]);
1798
      }
1799
    }
1800
  }
1801
  if (!empty($panel_body_css['body_classes_to_add'])) {
1802
    $vars['classes_array'][] = check_plain($panel_body_css['body_classes_to_add']);
1803
  }
1804
}