/[drupal]/contributions/modules/gallery/gallery_base.inc
ViewVC logotype

Contents of /contributions/modules/gallery/gallery_base.inc

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.8 - (show annotations) (download) (as text)
Fri Nov 23 11:20:33 2007 UTC (2 years ago) by profix898
Branch: MAIN
CVS Tags: HEAD
Branch point for: DRUPAL-6--1
Changes since 1.7: +76 -176 lines
File MIME type: text/x-php
- very early D6 version (Oct-01, 2007)
1 <?php
2 // $Id: gallery_base.inc,v 1.6.2.26 2007/09/10 18:04:08 profix898 Exp $
3
4 /**
5 * gallery.module : gallery_base.inc
6 * Base functions
7 */
8
9 define('GALLERY_ERROR_WATCHDOG', 1);
10 define('GALLERY_ERROR_BROWSER', 2);
11 define('GALLERY_ERROR_VERBOSE', 3);
12
13 define('GALLERY_SEVERITY_SUCCESS', 1);
14 define('GALLERY_SEVERITY_ERROR', -1);
15 define('GALLERY_SEVERITY_WARNING', -2);
16 define('GALLERY_SEVERITY_ADVISE', -3);
17 define('GALLERY_SEVERITY_UNKNOWN', -4);
18
19 define('GALLERY_PLUGIN_ENABLED', 1);
20 define('GALLERY_PLUGIN_DISABLED', 0);
21 define('GALLERY_PLUGIN_STATUS_UNKNOWN', -1);
22 define('GALLERY_PLUGIN_NOT_ACTIVE', -2);
23 define('GALLERY_PLUGIN_NOT_INSTALLED', -3);
24 define('GALLERY_PLUGIN_MISSING', -4);
25
26 define('GALLERY_PLUGIN_WANTED', 1);
27 define('GALLERY_PLUGIN_UNWANTED', 2);
28 define('GALLERY_PLUGIN_DRUPAL', 3);
29
30 define('GALLERY_DEBUGTRACE', TRUE);
31
32 /**
33 * Function gallery_login().
34 * (login user into embedded gallery)
35 */
36 function gallery_login() {
37 _gallery_init();
38 }
39
40 /**
41 * Function gallery_logout().
42 * (end user session)
43 */
44 function gallery_logout() {
45 if (variable_get('gallery_valid', FALSE)) {
46 require_once(variable_get('gallery_dir', './gallery2/') .'embed.php');
47 GalleryEmbed::logout();
48 }
49 }
50
51 /**
52 * Function _gallery_init().
53 * (initialize embedded gallery)
54 */
55 function _gallery_init($full = FALSE, $vars = NULL, $report_error = TRUE) {
56 global $user;
57 static $ready = array('half' => FALSE, 'full' => FALSE);
58
59 // Initialize only once
60 if ($ready[$full ? 'full' : 'half']) {
61 return TRUE;
62 }
63
64 $embed_path = (isset($vars['gallery_dir']) ? $vars['gallery_dir'] : variable_get('gallery_dir', './gallery2/')) .'embed.php';
65 $g2_uri = isset($vars['gallery_uri']) ? $vars['gallery_uri'] : variable_get('gallery_uri', '/gallery2/');
66 $embed_uri = isset($vars['gallery_embed_uri']) ? $vars['gallery_embed_uri'] : variable_get('gallery_embed_uri', '?q=gallery');
67
68 $gallery_valid = isset($vars) ? (isset($vars['gallery_valid']) ? $vars['gallery_valid'] : TRUE) : variable_get('gallery_valid', 0);
69 $uid = isset($vars) ? (isset($vars['uid']) ? $vars['uid'] : '') : (($user->uid > 0) ? $user->uid : '');
70
71 $init_err_msg = t('Unable to initialize embedded Gallery. You need to <a href="@link"> configure your embedded Gallery</a>.',
72 array('@link' => url('admin/settings/gallery/install')));
73
74 if ((!$gallery_valid) || (!is_readable($embed_path))) {
75 if ($report_error) {
76 gallery_error($init_err_msg);
77 }
78 return FALSE;
79 }
80
81 include_once($embed_path);
82
83 $params = array('embedUri' => $embed_uri,
84 'g2Uri' => $g2_uri,
85 'loginRedirect' => url('user/login', array('query' => drupal_get_destination(), 'absolute' => TRUE)),
86 'activeUserId' => $uid,
87 'activeLanguage' => gallery_get_language($user),
88 'fullInit' => $full,
89 'apiVersion' => array(1, 2));
90
91 $ret = GalleryEmbed::init($params);
92 if ($ret) {
93 if ($ret->getErrorCode() & ERROR_PLUGIN_VERSION_MISMATCH) {
94 if ($report_error) {
95 gallery_error($vars ? t('Embedding API version is incompatible.') : $init_err_msg, $ret, TRUE);
96 }
97 return FALSE;
98 }
99 else {
100 if ($report_error) {
101 gallery_error($init_err_msg, $ret, TRUE);
102 }
103 return FALSE;
104 }
105 }
106
107 if (!class_exists('GalleryEmbed') || !class_exists('GalleryCoreApi')) {
108 if ($report_error) {
109 gallery_error(t('Classes \'GalleryEmbed\' and/or \'GalleryCoreApi\' are not available,
110 although initialization seemed successful.'));
111 }
112 return FALSE;
113 }
114
115 $ready['half'] = $full ? ($ready['full'] = TRUE) : TRUE;
116
117 return TRUE;
118 }
119
120 /**
121 * Function gallery_handle_request().
122 * (handleRequest extension with error handling)
123 */
124 function gallery_handle_request() {
125 ob_start();
126 $result = GalleryEmbed::handleRequest();
127 $output = ob_get_contents();
128 ob_end_clean();
129
130 if ($output) {
131 if (!preg_match('%<h2>\sError\s</h2>%', $output)) {
132 // If $output does not contain '<h2>Error</h2>', this is an AJAX/Image callback
133 print $output;
134 exit();
135 }
136 else {
137 // Otherwise (on regular pages) $output means that an error occured
138 preg_match('%<div id="giStackTrace" [^>]*>(.*?)</div>%is', $output, $matches);
139 if (variable_get('gallery_error_redirect', 0) && user_access('search content')) {
140 drupal_set_message('The requested Gallery URL does not exist. The item may have been
141 moved or deleted. You can search for it below.', 'notice');
142 drupal_goto('search/gallery');
143 }
144 gallery_error(t('Error handling request (invalid request)<br />or the requested Gallery URL does not exist.'), $matches[1], TRUE);
145 return NULL;
146 }
147 }
148
149 return $result;
150 }
151
152 /**
153 * Function gallery_get_language().
154 * (get the language for $user)
155 */
156 function gallery_get_language($user) {
157 global $language;
158
159 $lang = ($user->uid > 0 && !empty($user->language)) ? $user->language : $language->language;
160 // Convert certain lang codes, e.g. 'esl/spa es' => 'es' or 'fr-ca' => 'fr'
161 $lang = preg_replace(array('/([\w\/]+) ([a-z]{2,3})/i', '/([a-z]{2,3})-(\w+)/i'), array('${2}', '${1}'), $lang);
162
163 return $language->language;
164 }
165
166 /**
167 * Function gallery_get_image_frames().
168 * (retrieve all image frames from Gallery2)
169 */
170 function gallery_get_image_frames() {
171 if (!_gallery_init()) {
172 return array('none' => t('None'));
173 }
174 // List of available image frames
175 list($ret, $imageframe) = GalleryCoreApi::newFactoryInstance('ImageFrameInterface_1_1');
176 if ($ret || !isset($imageframe)) {
177 return array('none' => t('None'));
178 }
179 list($ret, $list) = $imageframe->getImageFrameList();
180 if ($ret) {
181 return array('none' => t('None'));
182 }
183
184 return $list;
185 }
186
187 /**
188 * Function gallery_generate_url().
189 */
190 function gallery_generate_url($params, $html = TRUE, $full = TRUE) {
191 if (!isset($GLOBALS['gallery'])) {
192 if (!_gallery_init()) {
193 return '';
194 }
195 }
196
197 $url_generator =& $GLOBALS['gallery']->getUrlGenerator();
198 if (!$url_generator) {
199 gallery_error(t('Error: UrlGenerator not available'));
200 return '';
201 }
202
203 $options = array();
204 $options['forceFullUrl'] = $full;
205 $options['htmlEntities'] = $html;
206
207 if (!isset($params['view'])) {
208 $params['view'] = 'core.ShowItem';
209 }
210
211 return $url_generator->generateUrl($params, $options);
212 }
213
214 /**
215 * Function gallery_album_tree().
216 */
217 function gallery_album_tree($root = NULL, $depth = NULL, $uid = NULL) {
218 if (!_gallery_init()) {
219 return array();
220 }
221 // If this is called for the Drupal guest user, pass in G2
222 // anonymous user id (otherwise fetchAlbumTree() returns nothing)
223 global $user;
224 if (!$uid && !$user->uid) {
225 list($ret, $uid) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.anonymousUser');
226 if ($ret) {
227 return array();
228 }
229 }
230 // Fetch G2 album tree
231 list($ret, $tree) = GalleryCoreApi::fetchAlbumTree($root, $depth, $uid);
232 if ($ret) {
233 gallery_error(t('Error fetching album tree'), $ret);
234 return array();
235 }
236
237 return $tree;
238 }
239
240 /**
241 * Function gallery_item_details().
242 */
243 function gallery_item_details($id, $verbose = FALSE) {
244 $details = array();
245 // Load entity
246 list($ret, $entity) = GalleryCoreApi::loadEntitiesById($id);
247 if ($ret) {
248 gallery_error(t('Error fetching album details (entityId: :id)',
249 array(':id' => $id)), $ret);
250 return $details;
251 }
252 // Extract details
253 $details['g2type'] = $entity->entityType;
254 $details['g2owner'] = $entity->ownerId;
255 $details['g2parent'] = $entity->parentId;
256 // Drupal node properties (no g2 prefix)
257 $details['title'] = _gallery_htmlcharsdecode($entity->title);
258 $details['created'] = $entity->creationTimestamp;
259
260 if ($verbose) {
261 $details['g2description'] = _gallery_htmlcharsdecode($entity->description);
262 $details['g2summary'] = _gallery_htmlcharsdecode($entity->summary);
263 $details['g2keywords'] = $entity->keywords;
264 $details['g2theme'] = $entity->theme;
265 }
266
267 return $details;
268 }
269
270 /**
271 * Function gallery_db_query().
272 */
273 function gallery_db_query($query, $data = NULL) {
274 if (!isset($GLOBALS['gallery'])) {
275 if (!_gallery_init()) {
276 return FALSE;
277 }
278 }
279 list ($ret, $search) = $GLOBALS['gallery']->search($query, $data);
280 if ($ret) {
281 return FALSE;
282 }
283 $results = array();
284 while ($result = $search->nextResult()) {
285 $results += $result;
286 }
287
288 return $results;
289 }
290
291 /**
292 * Function gallery_flush_entity_cache().
293 */
294 function gallery_flush_entity_cache() {
295 if (!isset($GLOBALS['gallery'])) {
296 if (!_gallery_init()) {
297 return FALSE;
298 }
299 }
300 $platform =& $GLOBALS['gallery']->getPlatform();
301 $cache_basedir = $GLOBALS['gallery']->getConfig('data.gallery.cache');
302 $cache_dir = $cache_basedir .'entity';
303
304 if ($platform->file_exists($cache_dir)) {
305 if (!$platform->recursiveRmDir($cache_dir)) {
306 return FALSE;
307 }
308 }
309
310 return TRUE;
311 }
312
313 /**
314 * Function gallery_set_head().
315 */
316 function gallery_set_head($html, $settitle = FALSE) {
317 if (!empty($html)) {
318 list($title, $css, $javascript) = GalleryEmbed::parseHead($html);
319 if ($settitle) {
320 drupal_set_title($title);
321 }
322 gallery_set_css($css);
323 gallery_set_javascript($javascript);
324 }
325 }
326
327 /**
328 * Function gallery_set_css().
329 */
330 function gallery_set_css($css) {
331 global $base_url;
332 static $css_memory = array();
333
334 if (count($css)) {
335 $css = preg_replace('/<link(.*?)href="([^"]*)"(.*?)\/>/i', '${2}', $css);
336 $css = preg_replace(array('#^'. $base_url .'#', '#^'. base_path() .'#', '#^/#'), '', $css);
337 foreach ($css as $include) {
338 if (!in_array(($md5 = md5($include)), $css_memory)) {
339 $css_memory[] = $md5;
340 if (substr($include, 0, 6) == '<style') {
341 // drupal_add_css() does not support inline styles
342 drupal_set_html_head($include);
343 }
344 elseif (substr($include, 0, 4) == 'http' || variable_get('gallery_outside', 0)) {
345 // drupal_add_css() does not support external paths
346 drupal_set_html_head('<link type="text/css" rel="stylesheet" media="all" href="'. $include .'" />'."\n");
347 }
348 else {
349 // Gallery's css must always be added first to allow overriding from the module(s)
350 drupal_add_css($include, 'module', 'all', FALSE);
351 }
352 }
353 }
354 }
355 }
356
357 /**
358 * Function gallery_set_javascript().
359 * (druapl_add_js() ensures proper cascading of included G2 javascript)
360 */
361 function gallery_set_javascript($javascript) {
362 global $base_url;
363 static $js_memory = array();
364
365 if (!empty($javascript)) {
366 $files = preg_grep('/<script(.*?)src=/i', $javascript);
367 // Inline Javascript
368 $inline = array_diff($javascript, $files);
369 $inline = preg_replace('/<script([^>]*)>(.*?)<\/script>/is', '\2', $inline);
370 drupal_add_js(implode("\n", $inline), 'inline');
371 // Javascript files
372 $files = preg_replace('/<script(.*?)src="([^"]*)"([^>]*)>(.*?)<\/script>/i', '${2}', $files);
373 $files = preg_replace(array('#^'. $base_url .'#', '#^'. base_path() .'#', '#^/#'), '', $files);
374 foreach ($files as $include) {
375 if (!in_array(($md5 = md5($include)), $js_memory)) {
376 $js_memory[] = $md5;
377 if (substr($include, 0, 4) == 'http' || variable_get('gallery_outside', 0)) {
378 // drupal_add_js() does not support external paths
379 drupal_set_html_head('<script type="text/javascript" src="'. $include .'"></script>'."\n");
380 }
381 else {
382 drupal_add_js($include);
383 }
384 }
385 }
386 }
387 }
388
389 /**
390 * Function _gallery_split_imageblock().
391 * (split an image block result into individual images)
392 */
393 function _gallery_split_imageblock($html) {
394 // From http://uk.php.net/manual/en/function.preg-split.php
395 // Split the html from image block into <...> parts
396 $pattern = '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/';
397 $html_array = preg_split($pattern, trim($html), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
398
399 $ndx = 0;
400 $images = array();
401 $image_html = '';
402 // Iterate through this array and combine again, but on a per-image basis
403 foreach ($html_array as $value) {
404 $value = trim($value);
405 $image_html .= $value;
406 if (!strcmp($value, '<div class="one-image">')) {
407 // Found the opening <div> for the image
408 $open_divs = 0;
409 }
410 elseif (!strncmp($value, '<div', 4)) {
411 // Found a <div> but not the main image one (eg a frame)
412 $open_divs++;
413 }
414 elseif (!strcmp($value, '</div>')) {
415 // Found a </div> but check if it's for the main image or a subcomponent (eg frame)
416 if ($open_divs > 0) {
417 $open_divs--;
418 }
419 else {
420 // This must be the closing div for "one-image" so move to next image
421 $images[] = $image_html;
422 $image_html = '';
423 }
424 }
425 }
426
427 return $images;
428 }
429
430 /**
431 * Function _gallery_htmlcharsdecode().
432 * (recover special character's HTML entities, see htmlspecialchars_decode() for php5)
433 */
434 function _gallery_htmlcharsdecode($string) {
435 return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
436 }
437
438 /*
439 * --------------------------------------------------------------------------
440 * Error, Debug and Status Functions
441 * --------------------------------------------------------------------------
442 */
443
444 /**
445 * Function gallery_error().
446 */
447 function gallery_error($msg, $ret = NULL, $serious = FALSE) {
448 $error_mode = variable_get('gallery_error_mode', array(GALLERY_ERROR_WATCHDOG));
449 $admin = user_access('administer site configuration');
450 $report = $admin && variable_get('gallery_report', 1);
451 // Verbose error messages
452 $debug_info = array();
453 if (in_array(GALLERY_ERROR_VERBOSE, $error_mode) || variable_get('gallery_debug', 0) || $admin) {
454 $msg = $ret ? (is_object($ret) ? ($msg .'<br />'. $ret->getAsHtml()) : $ret) : $msg;
455 if (GALLERY_DEBUGTRACE && function_exists('debug_backtrace')) {
456 $trace = debug_backtrace();
457 $source = t('Error in function \':func()\' (:file::line):<br />',
458 array(':func' => $trace[1]['function'], ':file' => basename($trace[0]['file']), ':line' => $trace[0]['line']));
459 $message = $source .'<ul><li>'. $msg .'</li></ul>';
460 $debug_info = array('Debug Trace' => $trace);
461 }
462 }
463 $message = !empty($message) ? $message : $msg;
464 // Debug output (skip watchdog)
465 if (variable_get('gallery_debug', 0) && $admin) {
466 if ($report) {
467 _gallery_report_error($debug_info);
468 }
469 drupal_set_message($message, 'error');
470 return;
471 }
472 // Error output to browser
473 if (in_array(GALLERY_ERROR_BROWSER, $error_mode)) {
474 if ($report) {
475 _gallery_report_error($debug_info);
476 }
477 drupal_set_message($message, 'error');
478 }
479 elseif ($serious) {
480 if ($report) {
481 _gallery_report_error($debug_info);
482 }
483 drupal_set_message($admin ? $message : t('Embedded Gallery2 is not available or requested Gallery URL does not exist.'), 'error');
484 }
485 // Error output to watchdog
486 if (in_array(GALLERY_ERROR_WATCHDOG, $error_mode)) {
487 watchdog('gallery', $message, WATCHDOG_ERROR);
488 }
489 }
490
491 /**
492 * Function _gallery_report_error().
493 */
494 function _gallery_report_error($report = array()) {
495 require_once(drupal_get_path('module', 'gallery') .'/gallery_help.inc');
496 require_once(drupal_get_path('module', 'gallery') .'/gallery_report.inc');
497
498 drupal_set_message(_gallery_report_help(), 'error');
499 _gallery_report(FALSE, $report, TRUE);
500 }
501
502 /**
503 * Function gallery_debug().
504 */
505 function gallery_debug($array, $label = 'Gallery Debug') {
506 if (variable_get('gallery_debug', 0) && user_access('administer site configuration')) {
507 drupal_set_message('<strong>'. $label .':</strong><br />'. nl2br(htmlspecialchars(print_r($array, TRUE))), 'error');
508 }
509 }
510
511 /**
512 * Function gallery_plugin_status().
513 */
514 function gallery_plugin_status($plugin_names) {
515 static $all_plugins_status = array();
516
517 $plugins_status = array();
518 if (!_gallery_init(FALSE)) {
519 gallery_error(t('Unable to initialize Gallery2.'), $ret);
520 foreach ($plugin_names as $plugin) {
521 $plugins_status[$plugin] = GALLERY_PLUGIN_STATUS_UNKNOWN;
522 }
523
524 return $plugins_status;
525 }
526 // Fetch status of G2 modules
527 if (empty($plugins_status_cache)) {
528 list($ret, $plugins_status_cache) = GalleryCoreApi::fetchPluginStatus('module');
529 if ($ret) {
530 gallery_error(t('Unable to get Gallery2 module status.'), $ret);
531 foreach ($plugin_names as $plugin) {
532 $plugins_status[$plugin] = GALLERY_PLUGIN_STATUS_UNKNOWN;
533 }
534
535 return $plugins_status;
536 }
537 }
538 // Generate array containing module status
539 foreach ($plugin_names as $plugin) {
540 if (isset($plugins_status_cache[$plugin])) {
541 if (isset($plugins_status_cache[$plugin]['active']) && $plugins_status_cache[$plugin]['available']) {
542 $plugins_status[$plugin] = GALLERY_PLUGIN_ENABLED;
543 }
544 elseif (!isset($plugins_status_cache[$plugin]['active']) && $plugins_status_cache[$plugin]['available']) {
545 $plugins_status[$plugin] = GALLERY_PLUGIN_NOT_INSTALLED;
546 }
547 elseif (($plugins_status_cache[$plugin]['active'] == 0) && $plugins_status_cache[$plugin]['available']) {
548 $plugins_status[$plugin] = GALLERY_PLUGIN_NOT_ACTIVE;
549 }
550 else {
551 $plugins_status[$plugin] = GALLERY_PLUGIN_DISABLED;
552 }
553 }
554 else {
555 $plugins_status[$plugin] = GALLERY_PLUGIN_MISSING;
556 }
557 }
558
559 return $plugins_status;
560 }
561
562 /**
563 * Function gallery_single_plugin_status().
564 */
565 function gallery_single_plugin_status($plugin_name) {
566 $status = gallery_plugin_status(array($plugin_name));
567 return $status[$plugin_name];
568 }
569
570 /**
571 * Function gallery_set_status().
572 */
573 function gallery_set_status($status = array(), $reset = FALSE) {
574 $status_array = $status;
575 if (!$reset) {
576 $status_array = unserialize(variable_get('gallery_status', serialize(array())));
577 foreach ($status as $key => $value) {
578 if (!empty($value)) {
579 $status_array[$key] = $value;
580 }
581 elseif (isset($status_array[$key])) {
582 unset($status_array[$key]);
583 }
584 }
585 }
586
587 variable_set('gallery_status', serialize($status_array));
588 }
589
590 /**
591 * Function gallery_get_status().
592 */
593 function gallery_get_status() {
594 return unserialize(variable_get('gallery_status', serialize(array())));
595 }
596
597 /**
598 * Function gallery_version().
599 */
600 function gallery_version() {
601 if (!_gallery_init(FALSE)) {
602 return array();
603 }
604
605 list($core_major, $core_minor) = GalleryCoreApi::getApiVersion();
606 list($embed_major, $embed_minor) = GalleryEmbed::getApiVersion();
607 $version = array(
608 'core' => array('major' => $core_major, 'minor' => $core_minor),
609 'embed' => array('major' => $embed_major, 'minor' => $embed_minor)
610 );
611
612 // Update version in status messages
613 $status = array('version' => array(
614 'title' => t('Gallery2 API version'),
615 'info' => "$core_major.$core_minor / $embed_major.$embed_minor")
616 );
617 gallery_set_status($status);
618
619 return $version;
620 }

  ViewVC Help
Powered by ViewVC 1.1.2