gallery_base.inc 25.9 KB
Newer Older
1 2 3 4 5 6 7
<?php
// $Id$

/**
 * gallery.module : gallery_base.inc
 * Base functions
 */
8

9 10
define('GALLERY_BASE_API', 1);

11 12 13
define('GALLERY_ERROR_WATCHDOG',  1);
define('GALLERY_ERROR_BROWSER',   2);
define('GALLERY_ERROR_VERBOSE',   3);
14

15 16 17 18 19
define('GALLERY_SEVERITY_SUCCESS',       1);
define('GALLERY_SEVERITY_ERROR',        -1);
define('GALLERY_SEVERITY_WARNING',      -2);
define('GALLERY_SEVERITY_ADVISE',       -3);
define('GALLERY_SEVERITY_UNKNOWN',      -4);
20

21 22 23 24 25 26
define('GALLERY_PLUGIN_ENABLED',         1);
define('GALLERY_PLUGIN_DISABLED',        0);
define('GALLERY_PLUGIN_STATUS_UNKNOWN', -1);
define('GALLERY_PLUGIN_NOT_ACTIVE',     -2);
define('GALLERY_PLUGIN_NOT_INSTALLED',  -3);
define('GALLERY_PLUGIN_MISSING',        -4);
27

28 29 30 31 32
define('GALLERY_PLUGIN_WANTED',          1);
define('GALLERY_PLUGIN_UNWANTED',        2);
define('GALLERY_PLUGIN_DRUPAL',          3);

define('GALLERY_DEBUGTRACE', TRUE);
33 34 35 36

/**
 * Function gallery_login().
 * (login user into embedded gallery)
37
 */
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
function gallery_login() {
  _gallery_init();
}

/**
 * Function gallery_logout().
 * (end user session)
 */
function gallery_logout() {
  if (variable_get('gallery_valid', FALSE)) {
    require_once(variable_get('gallery_dir', './gallery2/') .'embed.php');
    GalleryEmbed::logout();
  }
}

53
/**
54 55
 * Function _gallery_init().
 * (initialize embedded gallery)
56
 */
57
function _gallery_init($full = FALSE, $vars = NULL, $report_error = TRUE) {
58
  global $user, $language;
59
  static $ready = array('half' => FALSE, 'full' => FALSE);
60
    
61 62 63 64
  // Initialize only once
  if ($ready[$full ? 'full' : 'half']) {
    return TRUE;
  }
65
  
66 67 68
  $init_err_msg = t('Unable to initialize embedded Gallery. You need to <a href="@link"> configure your embedded Gallery</a>.',
                     array('@link' => url('admin/settings/gallery/install')));
  
69
  $g2_dir = isset($vars['gallery_dir']) ? $vars['gallery_dir'] : variable_get('gallery_dir', './gallery2/');
70 71
  $g2_uri = isset($vars['gallery_uri']) ? $vars['gallery_uri'] : variable_get('gallery_uri', '/gallery2/');
  $embed_uri = isset($vars['gallery_embed_uri']) ? $vars['gallery_embed_uri'] : variable_get('gallery_embed_uri', '?q=gallery');
72
  
73 74
  $gallery_valid = isset($vars) ? (isset($vars['gallery_valid']) ? $vars['gallery_valid'] : TRUE) : variable_get('gallery_valid', 0);
  $uid = isset($vars) ? (isset($vars['uid']) ? $vars['uid'] : '') : (($user->uid > 0) ? $user->uid : '');
75
  
76
  // Language-prefix url rewrite
77 78
  if (function_exists('language_url_rewrite') && $language->prefix) {
    $embed_uri = str_replace('index.php?q=', 'index.php?q='. $language->prefix .'/', $embed_uri);
79
  }
80
  
81
  // Prepare array with init parameters
82
  $debug = variable_get('gallery_g2debug', 0) && user_access('administer site configuration');
83
  $params = array('g2Dir' => $g2_dir,
84
                  'g2Uri' => $g2_uri,
85
                  'embedUri' => $embed_uri,
86
                  'loginRedirect' => url('user/login', array('query' => drupal_get_destination(), 'absolute' => TRUE)),
87
                  'activeUserId' => $uid,
88 89 90
                  'activeLanguage' => gallery_get_language($language->language),
                  'apiVersion' => array(1, 4),
                  'debug' => $debug ? 'buffered' : FALSE,
91
                  'eventListeners' => array());
92

93 94 95 96 97 98 99 100 101 102 103 104
  // Add theme to init parameters
  if (($g2_theme = variable_get('gallery_embed_theme', 'default')) != 'default') {
    $params['themeId'] = $g2_theme;
  }
  
  // Add root album to init parameters (but only for the gallery pages)
  $g2_root = variable_get('gallery_root_album', 'default');
  if ($g2_root != 'default' && arg(0) == variable_get('gallery_base', 'gallery')) {
    $params['defaultAlbumId'] = $params['breadcrumbRootId'] = $g2_root;
  }
  
  // Allow modules to alter the init parameters
105 106 107
  drupal_alter('gallery_init', $params, array('fullInit' => $full, 'ready' => $ready));
  $params['fullInit'] = $full;
  
108
  // Debug output of init parameters
109
  gallery_debug($params, t('Init parameters'));
110
  
111 112 113 114 115 116 117 118
  // Check for existence of 'embed.php'
  if (!$gallery_valid || !is_readable($params['g2Dir'] .'embed.php')) {
    if ($report_error) {
      gallery_error($init_err_msg);
    }
    return FALSE;
  }
  
119
  // Initialize Gallery2
120
  include_once($params['g2Dir'] .'embed.php');
121
  $ret = GalleryEmbed::init($params);
122
  if ($ret) {
123 124 125 126
    if ($ret->getErrorCode() & ERROR_PLUGIN_VERSION_MISMATCH) {
      $err_msg = t('Embedding API version is incompatible.');
      if ($vars) {
        drupal_set_message($err_msg, 'error');
127
      }
128 129 130 131
      gallery_error($vars ? $err_msg : $init_err_msg, $ret, !$vars);
    }
    else if ($report_error) {
      gallery_error($init_err_msg, $ret, TRUE);
132
    }
133
    return FALSE;
134
  }
135
      
136
  // Check if initialization was successful
137 138
  if (!class_exists('GalleryEmbed') || !class_exists('GalleryCoreApi')) {
    if ($report_error) {
139 140
      gallery_error(t('Initialization seemed successful, but classes \'GalleryEmbed\'
                       and/or \'GalleryCoreApi\' are still not available.'));
141 142 143 144
    }
    return FALSE;
  }
  
145 146 147 148 149 150 151 152 153 154
  // Multiroot: 'Virtual Root' (or 'Alternate guest user') view requested
  if (isset($params['defaultAlbumId'])) {
    $GLOBALS['gallery']->setConfig('defaultAlbumId', $params['defaultAlbumId']);
  }
  if (isset($params['breadcrumbRootId'])) {
    $GLOBALS['gallery']->setConfig('breadcrumbRootId', $params['breadcrumbRootId']);
  }
  if (isset($params['anonymousUserId'])) {
    $GLOBALS['gallery']->setConfig('anonymousUserId', $params['anonymousUserId']);
  }
155 156 157
    
  // Register event listeners
  if (count($params['eventListeners'])) {
158
    require_once(drupal_get_path('module', 'gallery') .'/G2DrupalHelper.class');
159
    $ret = G2DrupalHelper::registerEventListeners($params['eventListeners']);
160
    if ($ret && $report_error) {
161
      gallery_error(t('Failed to register event listeners.'), $ret);
162
    }
163
  }
164 165 166 167 168 169 170 171 172
  
  // Session handling
  $g2_session =& $GLOBALS['gallery']->getSession();
	$g2_session->doNotUseTempId();
	//
  list ($ret, $g2_admin) = GalleryCoreApi::isUserInSiteAdminGroup();
  if (!$ret && $g2_admin) {
    $g2_session->put('session.siteAdminActivityTimestamp', time());
  }
173 174
    
  $ready['half'] = $params['fullInit'] ? ($ready['full'] = TRUE) : TRUE;
175 176
  
  return TRUE;
177 178 179
}

/**
180 181
 * Function gallery_handle_request().
 * (handleRequest extension with error handling)
182
 */
183
function gallery_handle_request() {
184 185
  global $language;
  
186
  // Remove the language-prefix for G2
187 188 189 190 191 192
  if (!empty($_GET['g2_path']) && function_exists('language_url_rewrite')) {
    $args = explode('/', $_GET['g2_path']);
    $prefix = array_shift($args);
    if (!empty($language->prefix) && $language->prefix == $prefix) {
      $_GET['g2_path'] = implode('/', $args);
    }
193 194 195
  }
  
  // Handle the request
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  ob_start();
  $result = GalleryEmbed::handleRequest();
  $output = ob_get_contents();
  ob_end_clean();
  
  if ($output) {
    if (!preg_match('%<h2>\sError\s</h2>%', $output)) {
      // If $output does not contain '<h2>Error</h2>', this is an AJAX/Image callback
      print $output;
      exit();
    }
    else {
      // Otherwise (on regular pages) $output means that an error occured
      if (variable_get('gallery_error_redirect', 0) && user_access('search content')) {
        drupal_set_message('The requested Gallery URL does not exist. The item may have been
                            moved or deleted. You can search for it below.', 'notice');
        drupal_goto('search/gallery');
      }
214
      preg_match('%<div id="giStackTrace" [^>]*>(.*?)</div>%is', $output, $matches);
215 216 217
      gallery_error(t('Error handling request (invalid request)<br />or the requested Gallery URL does not exist.'), $matches[1], TRUE);
      return NULL;
    }
218
  }
219
  
220 221 222 223 224 225 226 227
  // Include theme-specific css overrides (gallery-themeid.css)
  if (isset($result['themeData']['themeId'])) {
    $stylesheet = drupal_get_path('module', 'gallery') .'/gallery-'. $result['themeData']['themeId'] .'.css';
    if (file_exists($stylesheet)) {
      drupal_add_css($stylesheet);
    }
  }
  
228 229 230 231 232 233 234 235 236 237
  // Catch debug output from G2
  if (($pos = strpos($result['bodyHtml'], '<div id="gpDebug">')) !== FALSE) {
    list($result['bodyHtml'], $suffix) = explode('<div id="gpDebug">', $result['bodyHtml']);
    if ($suffix) {
      list($debug, $suffix) = explode('</div>', $suffix, 2);
      $result['bodyHtml'] .= $suffix;
      gallery_debug($debug, t('G2 Debug Buffer'), TRUE);
    }    
  }
  
238
  return $result;
239 240 241
}

/**
242
 * Function gallery_get_language().
243
 */
244
function gallery_get_language($lang = '', $user = NULL) {
245
  global $language;
246 247 248 249 250 251
  
  // Get language from $user object
  $lang = (isset($user) && $user->uid > 0 && !empty($user->language)) ? $user->language : $lang;
  // Use current global $language, if no other language is specified
  $lang = empty($lang) ? $language->language : $lang;
  // Convert certain language codes, e.g. 'esl/spa es' => 'es' or 'fr-ca' => 'fr'
252
  $lang = preg_replace(array('/([\w\/]+) ([a-z]{2,3})/i', '/([a-z]{2,3})-(\w+)/i'), array('${2}', '${1}'), $lang);
253

254
  return $lang;
255 256
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
/**
 * Function gallery_get_themes().
 * (retrieve all (active) themes from Gallery2)
 */
function gallery_get_themes() {
  if (!_gallery_init()) {
    return array();
  }
  // List of themes
  list($ret, $g2_themes) = GalleryCoreApi::fetchPluginStatus('theme', TRUE);
  if ($ret) {
    gallery_error(t('Error retrieving theme list'), $ret);
    return array();
  }
  
  $themes = array();
  foreach (array_keys($g2_themes) as $themeid) {
    // Only active themes
    if (!empty($g2_themes[$themeid]['active'])) {
      // Get theme details
      list($ret, $theme) = GalleryCoreApi::loadPlugin('theme', $themeid, TRUE);
      if ($ret) {
        gallery_error(t('Error getting theme (:themeid) details',
          array(':themeid' => $themeid)), $ret);
        return array();
      }
      $themes[$themeid] = $theme->getName();
    }
  }
  
  return $themes;
}

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/**
 * Function gallery_get_image_frames().
 * (retrieve all image frames from Gallery2)
 */
function gallery_get_image_frames() {
  if (!_gallery_init()) {
    return array('none' => t('None'));
  }
  // List of available image frames
  list($ret, $imageframe) = GalleryCoreApi::newFactoryInstance('ImageFrameInterface_1_1');
  if ($ret || !isset($imageframe)) {
      return array('none' => t('None'));
  }
  list($ret, $list) = $imageframe->getImageFrameList();
  if ($ret) {
      return array('none' => t('None'));
  }
307

308 309 310
  return $list;
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/**
 * Function gallery_check_path2id(). 
 */
function gallery_check_path2id($path) {
  if (!_gallery_init(TRUE)) {
    return FALSE;
  }
  // Cache the request items here to save G2 API calls
  // (the menu system invokes _load repeatedly with the same arguments) 
  static $items = NULL;
  if (!isset($items[$path])) {
    $url_generator =& $GLOBALS['gallery']->getUrlGenerator();
    if (isset($url_generator->_shortUrls)) {
      // Fetch item id for this path (to check existence) and return id
      list($ret, $id) = GalleryCoreApi::fetchItemIdByPath($path);
      $items[$path] = $ret ? FALSE : $id;
    }
    else if (is_numeric($path) && ($id = intval($path))) {
      // Fetch item by id (to check existence) and return id
      list($ret, $entity) = GalleryCoreApi::loadEntitiesById($id);
      $items[$path] = $ret ? FALSE : $id;
    }
  }
  
  return $items[$path];
}

338 339 340 341
/**
 * Function gallery_generate_url().
 */
function gallery_generate_url($params, $html = TRUE, $full = TRUE) {
342
  if (!_gallery_init(TRUE)) {
343
    return '';
344
  }
345
  // Get URL generator and generate the url
346 347 348 349 350
  $url_generator =& $GLOBALS['gallery']->getUrlGenerator();
  if (!$url_generator) {
    gallery_error(t('Error: UrlGenerator not available'));
    return '';
  }
351

352 353 354
  $options = array();
  $options['forceFullUrl'] = $full;
  $options['htmlEntities'] = $html;
355

356 357 358
  if (!isset($params['view'])) {
    $params['view'] = 'core.ShowItem';
  }
359

360 361 362 363 364 365 366
  return $url_generator->generateUrl($params, $options);
}

/**
 * Function gallery_album_tree().
 */
function gallery_album_tree($root = NULL, $depth = NULL, $uid = NULL) {
367
  if (!_gallery_init(TRUE)) {
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    return array();
  }
  // If this is called for the Drupal guest user, pass in G2
  // anonymous user id (otherwise fetchAlbumTree() returns nothing)
  global $user;
  if (!$uid && !$user->uid) {
    list($ret, $uid) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.anonymousUser');
    if ($ret) {
      return array();
    }
  }
  // Fetch G2 album tree
  list($ret, $tree) = GalleryCoreApi::fetchAlbumTree($root, $depth, $uid);
  if ($ret) {
    gallery_error(t('Error fetching album tree'), $ret);
    return array();
  }

  return $tree;
}

/**
 * Function gallery_item_details().
 */
function gallery_item_details($id, $verbose = FALSE) {
  $details = array();
394 395 396
  if (!_gallery_init(TRUE)) {
    return $details;
  }
397 398 399
  // Load entity
  list($ret, $entity) = GalleryCoreApi::loadEntitiesById($id);
  if ($ret) {
400
    gallery_error(t('Error fetching item details (entityId: :id)',
401 402 403 404
      array(':id' => $id)), $ret);
    return $details;
  }
  // Extract details
405
  $details['g2id'] = $id;
406 407 408
  $details['g2type'] = $entity->entityType;
  $details['g2owner'] = $entity->ownerId;
  $details['g2parent'] = $entity->parentId;
409
  // Drupal node properties (without g2 prefix)
410 411
  $details['title'] = _gallery_htmlcharsdecode($entity->title);
  $details['created'] = $entity->creationTimestamp;
412
  $details['changed'] = $entity->modificationTimestamp;
413
  // Gallery2 item properties (with g2 prefix)
414 415 416 417
  if ($verbose) {
    $details['g2description'] = _gallery_htmlcharsdecode($entity->description);
    $details['g2summary'] = _gallery_htmlcharsdecode($entity->summary);
    $details['g2keywords'] = $entity->keywords;
418
    $details['g2theme'] = isset($entity->theme) ? $entity->theme : NULL;
419 420 421 422 423
  }

  return $details;
}

424 425 426 427
/**
 * Function gallery_item_access().
 */
function gallery_item_access($id, $permission = 'core.view', $user = NULL) {
428
  if (!_gallery_init(TRUE) || !is_numeric($id)) {
429 430 431 432 433 434 435 436 437 438 439 440
    return FALSE;
  }
  // Check access permissions
  list($ret, $access) = GalleryCoreApi::hasItemPermission($id, $permission, $user);
  if ($ret) {
    gallery_error(t('Error calling hasItemPermission()'), $ret);
    return FALSE;
  }

  return $access;
}

441 442 443 444
/**
 * Function gallery_db_query().
 */
function gallery_db_query($query, $data = NULL) {
445 446
  if (!_gallery_init(TRUE)) {
    return FALSE;
447
  }
448
  // Perform query
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  list ($ret, $search) = $GLOBALS['gallery']->search($query, $data);
	if ($ret) {
    return FALSE;
	}
	$results = array();
	while ($result = $search->nextResult()) {
    $results += $result;
  }

  return $results;
}

/**
 * Function gallery_flush_entity_cache().
 */
function gallery_flush_entity_cache() {
465 466
  if (!_gallery_init()) {
    return FALSE;
467
  }
468
  // Flush entity cache
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  $platform =& $GLOBALS['gallery']->getPlatform();
  $cache_basedir = $GLOBALS['gallery']->getConfig('data.gallery.cache');
  $cache_dir = $cache_basedir .'entity';

  if ($platform->file_exists($cache_dir)) {
    if (!$platform->recursiveRmDir($cache_dir)) {
      return FALSE;
    }
  }

  return TRUE;
}

/**
 * Function gallery_set_head().
 */
function gallery_set_head($html, $settitle = FALSE) {
  if (!empty($html)) {
487
    list($title, $css, $javascript, $meta) = GalleryEmbed::parseHead($html);
488 489 490
    if ($settitle) {
      drupal_set_title($title);
    }
491
    gallery_set_meta($meta);
492 493 494 495 496
    gallery_set_css($css);
    gallery_set_javascript($javascript);
  }
}

497 498 499 500 501 502
/**
 * Function gallery_set_meta().
 */
function gallery_set_meta($meta) {
  static $meta_memory = array();
  
503 504
  // Debug output
  gallery_debug($meta, t('Head [Meta]'));
505 506 507 508
  // Drupal adds these item by default already
  if (empty($meta_memory)) {
    $meta_memory[] = md5('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>');
  }
509
  // Handle head/meta data
510 511 512 513 514 515 516 517
  foreach ($meta as $include) {
    if (!in_array(($md5 = md5($include)), $meta_memory)) {
      $meta_memory[] = $md5;
      drupal_set_html_head($include);
    }
  }
}

518 519 520 521 522 523 524
/**
 * Function gallery_set_css().
 */
function gallery_set_css($css) {
  static $css_memory = array();
  
  if (count($css)) {
525 526 527
    // Debug output
    gallery_debug($css, t('Head [CSS]'));
    // Handle css styles and includes
528 529 530
    foreach ($css as $include) {
      if (!in_array(($md5 = md5($include)), $css_memory)) {
        $css_memory[] = $md5;
531
        drupal_set_html_head($include);
532 533 534 535 536 537 538 539 540 541 542 543 544
      }
    }
  }
}

/**
 * Function gallery_set_javascript().
 * (druapl_add_js() ensures proper cascading of included G2 javascript)  
 */
function gallery_set_javascript($javascript) {
  static $js_memory = array();
  
  if (!empty($javascript)) {
545 546 547
    // Debug output
    gallery_debug($javascript, t('Head [Javascript]'));
    // Handle inline javascript and includes
548 549 550 551 552 553 554 555 556
    $files = preg_grep('/<script(.*?)src=/i', $javascript);
    // Inline Javascript
    $inline = array_diff($javascript, $files);
    $inline = preg_replace('/<script([^>]*)>(.*?)<\/script>/is', '\2', $inline);
    drupal_add_js(implode("\n", $inline), 'inline');
    // Javascript files
    foreach ($files as $include) {
      if (!in_array(($md5 = md5($include)), $js_memory)) {
        $js_memory[] = $md5;
557
        drupal_set_html_head($include);
558 559 560 561 562
      }
    }
  }
}

563 564 565 566 567 568 569 570
/**
 * Function gallery_context().
 * (store and/or access the context of the current gallery page) 
 */
function gallery_context(&$params, $setcontext = FALSE) {
  static $context_cache = NULL;
  
  if ($setcontext) {
571
    // Store new context
572
    $context_cache = (isset($params) && count($params)) ? $params : array();
573
    gallery_debug($context_cache, t('Context cache'));
574 575
  }
  else if (isset($context_cache)) {
576
    // Get context parameters
577
    if (isset($params)) {
578
      // Return requested context parameters
579 580 581 582 583 584 585 586 587 588
      $params = is_array($params) ? $params : array($params);
      foreach($params as $param) {
        if (!isset($context_cache[$param])) {
          return FALSE;
        }
        $context[$param] = $context_cache[$param];
      }
      $params = $context;
    }
    else {
589
      // Return all stored context parameters
590 591 592 593 594 595 596 597 598
      $params = $context_cache;
    }
    
    return TRUE;
  }
  
  return FALSE;
}

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
/**
 * Function gallery_get_blocks().
 */
function gallery_get_blocks($plugin_names = NULL) {
  if (!_gallery_init()) {
    return array();
  }
  // List of available blocks
  list($ret, $g2_blocks) = GalleryCoreApi::loadAvailableBlocks();
  if ($ret) {
    gallery_error(t('Error retrieving available blocks list'), $ret);
    return array();
  }
  // Filter plugins
  if (isset($plugin_names)) {
    $plugin_names = is_array($plugin_names) ? $plugin_names : array($plugin_names);
    foreach ($g2_blocks as $plugin => $blocks) {
      if (!in_array($plugin, $plugin_names)) {
        unset($g2_blocks[$plugin]);
      }
    }
  }
  
  return $g2_blocks;
}

625 626 627 628 629 630 631 632 633 634 635
/**
 * Function gallery_get_block().
 *
 * This function allows developers to fetch an image or grid block with certain
 * parameters from Gallery2.
 *
 * @param $params
 *   An array of parameters to be passed to getImageBlock().
 *   (http://gallery.menalto.com/apidoc/GalleryCore/Classes/GalleryEmbed.html#methodgetImageBlock)
 *   If 'itemId' is set to 'user' (or 'user:uid') items are be taken from the
 *   current (or specified) user's useralbum.
636 637 638 639 640
 * @param $block
 *   Name of the block to get from Gallery2 (e.g. 'ImageBlock', etc.)
 * @param $extra
 *   $extra['class']:
 *     Optional class to apply to the block (if customized css styles are required).
641
 *   $extra['num_cols']:
642 643
 *     If given for a 'ImageBlock' a grid block with 'num_cols' columns is generated.
 *     Otherwise (default) a 'normal' image block is returned.
644
 */
645 646 647
function gallery_get_block($params, $block = 'ImageBlock', $extra = array()) {
  require_once(drupal_get_path('module', 'gallery') .'/gallery_block.inc');
  if (!_gallery_init(TRUE)) {
648 649
    return array('content' => '');
  }
650 651 652 653 654
  $block_map = _gallery_block_map();
  $plugin = $block_map[strtolower($block)]['plugin'];
  $plugin_block = $block_map[strtolower($block)]['block'];
  
  return _gallery_block_get_block($plugin, $plugin_block, $params, $extra);
655 656
}

657 658 659 660 661 662 663
/**
 * Function _gallery_htmlcharsdecode().
 * (recover special character's HTML entities, see htmlspecialchars_decode() for php5)
 */
function _gallery_htmlcharsdecode($string) {
  return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}
kiz_0987's avatar
kiz_0987 committed
664

665
/* --------------------------------------------------------------------------
666
 * Error, Debug and Status Functions
667
 * -------------------------------------------------------------------------- */
668 669 670 671 672 673 674 675

/**
 * Function gallery_error().
 */
function gallery_error($msg, $ret = NULL, $serious = FALSE) {
  $error_mode = variable_get('gallery_error_mode', array(GALLERY_ERROR_WATCHDOG));
  $admin = user_access('administer site configuration');
  $report = $admin && variable_get('gallery_report', 1);
676 677
  
  // Verbose error messages (include backtrace if available)
678 679 680 681 682 683 684 685 686 687 688 689
  $debug_info = array();
  if (in_array(GALLERY_ERROR_VERBOSE, $error_mode) || variable_get('gallery_debug', 0) || $admin) {
    $msg = $ret ? (is_object($ret) ? ($msg .'<br />'. $ret->getAsHtml()) : $ret) : $msg;
    if (GALLERY_DEBUGTRACE && function_exists('debug_backtrace')) {
      $trace = debug_backtrace();
      $source = t('Error in function \':func()\' (:file::line):<br />',
        array(':func' => $trace[1]['function'], ':file' => basename($trace[0]['file']), ':line' => $trace[0]['line']));
      $message  = $source .'<ul><li>'. $msg .'</li></ul>';
      $debug_info = array('Debug Trace' => $trace);
    }
  }
  $message = !empty($message) ? $message : $msg;
690 691
  
  // Debug output (do not log to watchdog)
692 693 694 695 696 697 698
  if (variable_get('gallery_debug', 0) && $admin) {
    if ($report) {
      _gallery_report_error($debug_info);
    }
    drupal_set_message($message, 'error');
    return;
  }
699
  
700 701 702 703 704 705 706 707 708 709 710 711 712
  // Error output to browser
  if (in_array(GALLERY_ERROR_BROWSER, $error_mode)) {
    if ($report) {
      _gallery_report_error($debug_info);
    }
    drupal_set_message($message, 'error');
  }
  elseif ($serious) {
    if ($report) {
      _gallery_report_error($debug_info);
    }
    drupal_set_message($admin ? $message : t('Embedded Gallery2 is not available or requested Gallery URL does not exist.'), 'error');
  }
713
  
714 715
  // Error output to watchdog
  if (in_array(GALLERY_ERROR_WATCHDOG, $error_mode)) {
716
    watchdog('gallery', $message, array(), WATCHDOG_ERROR);
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
  }
}

/**
 * Function _gallery_report_error().
 */
function _gallery_report_error($report = array()) {
  require_once(drupal_get_path('module', 'gallery') .'/gallery_help.inc');
  require_once(drupal_get_path('module', 'gallery') .'/gallery_report.inc');

  drupal_set_message(_gallery_report_help(), 'error');
  _gallery_report(FALSE, $report, TRUE);
}

/**
 * Function gallery_debug().
 */
734
function gallery_debug($output, $label = NULL, $html = FALSE) {
735
  if (variable_get('gallery_debug', 0) && user_access('administer site configuration')) {
736 737
    // Output debug log into a collapsible fieldset
    $fieldset = array(
738
      '#title' => t('Gallery Debug') . (isset($label) ? (': '. check_plain($label)) : ''),
739 740
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
741
      '#value' => '<pre>'. ($html ? $output : htmlspecialchars(print_r($output, TRUE))) .'</pre>',
742 743
    );
    drupal_set_content('content', theme('fieldset', $fieldset));
744 745 746 747 748 749 750 751 752 753
  }
}

/**
 * Function gallery_plugin_status().
 */
function gallery_plugin_status($plugin_names) {
  static $all_plugins_status = array();

  $plugins_status = array();
754
  if (!_gallery_init()) {
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    foreach ($plugin_names as $plugin) {
      $plugins_status[$plugin] = GALLERY_PLUGIN_STATUS_UNKNOWN;
    }
    
    return $plugins_status;
  }
  // Fetch status of G2 modules
  if (empty($plugins_status_cache)) {
    list($ret, $plugins_status_cache) = GalleryCoreApi::fetchPluginStatus('module');
    if ($ret) {
      gallery_error(t('Unable to get Gallery2 module status.'), $ret);
      foreach ($plugin_names as $plugin) {
        $plugins_status[$plugin] = GALLERY_PLUGIN_STATUS_UNKNOWN;
      }
      
      return $plugins_status;
    }
  }
  // Generate array containing module status
  foreach ($plugin_names as $plugin) {
    if (isset($plugins_status_cache[$plugin])) {
776
      if (isset($plugins_status_cache[$plugin]['active']) && $plugins_status_cache[$plugin]['available']) {
777 778 779 780 781
        $plugins_status[$plugin] = GALLERY_PLUGIN_ENABLED;
      }
      elseif (!isset($plugins_status_cache[$plugin]['active']) && $plugins_status_cache[$plugin]['available']) {
        $plugins_status[$plugin] = GALLERY_PLUGIN_NOT_INSTALLED;
      }
782
      elseif (($plugins_status_cache[$plugin]['active'] == FALSE) && $plugins_status_cache[$plugin]['available']) {
783 784 785 786 787 788 789 790 791
        $plugins_status[$plugin] = GALLERY_PLUGIN_NOT_ACTIVE;
      }
      else {
        $plugins_status[$plugin] = GALLERY_PLUGIN_DISABLED;
      }
    }
    else {
      $plugins_status[$plugin] = GALLERY_PLUGIN_MISSING;
    }
792
  }
793 794 795 796 797 798 799 800 801 802 803
  
  return $plugins_status;
}

/**
 * Function gallery_single_plugin_status().
 */
function gallery_single_plugin_status($plugin_name) {
  $status = gallery_plugin_status(array($plugin_name));
  return $status[$plugin_name];
}
804

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
/**
 * Function gallery_set_status().
 */
function gallery_set_status($status = array(), $reset = FALSE) {
  $status_array = $status;
  if (!$reset) {
    $status_array = unserialize(variable_get('gallery_status', serialize(array())));
    foreach ($status as $key => $value) {
      if (!empty($value)) {
        $status_array[$key] = $value;
      }
      elseif (isset($status_array[$key])) {
        unset($status_array[$key]);
      }
    }
820
  }
821 822 823
  
  variable_set('gallery_status', serialize($status_array));
}
824

825 826 827 828 829 830 831 832 833 834 835
/**
 * Function gallery_get_status().
 */
function gallery_get_status() {
  return unserialize(variable_get('gallery_status', serialize(array())));
}

/**
 * Function gallery_version().
 */
function gallery_version() {
836
  if (!_gallery_init()) {
837
    return array();
838
  }
839
  // Get API version
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
  list($core_major, $core_minor) = GalleryCoreApi::getApiVersion();
  list($embed_major, $embed_minor) = GalleryEmbed::getApiVersion();
  $version = array(
    'core' => array('major' => $core_major, 'minor' => $core_minor),
    'embed' => array('major' => $embed_major, 'minor' => $embed_minor)
  );

  // Update version in status messages
  $status = array('version' => array(
    'title' => t('Gallery2 API version'),
    'info' => "$core_major.$core_minor / $embed_major.$embed_minor")
  );
  gallery_set_status($status);
      
  return $version;
855
}