summaryrefslogtreecommitdiffstats
path: root/gallery.module
blob: aada9a4032e474afae5c2ca2e7b4ae99fa023e27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
// $Id$

/**
 * Implementation of hook_help
 */
function gallery_help($section) {
  switch($section) {
  case 'admin/modules#description':
    return t('Integration with Gallery2 (%gallery_url)', array('%gallery_url' => 'http://gallery.menalto.com/'));
  }
}

/**
 * Implementation of hook_menu
 */
function gallery_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'gallery',
                     'callback' => 'gallery_page',
                     'access' => user_access('access content'),
                     'type' => MENU_SUGGESTED_ITEM);
  }

  return $items;
}

/**
 * Implementation of hook_settings
 */
function gallery_settings() {
  $output = '';
  $output.= form_textfield(t('Location of Gallery2'), 'gallery_dir', variable_get('gallery_dir', 'gallery2/'), 64, 64, t('Path to your gallery2 directory, relative to the root directory of your drupal installation. Please include a trailing slash ("/").'));
  $output .= form_checkboxes(t('Error logging'), 'gallery_error_mode',
			     variable_get('gallery_error_mode', array(1)),
			     array(1 => t('Watchdog'),
				   2 => t('Output to the browser')),
			     t('Choose where errors are displayed'));
  return $output;
}

/**
 * Implementation of hook_user
 */
function gallery_user($op, &$edit, &$user, $category = NULL) {
  switch ($op) {
  case 'login':
    /* _gallery_init() will try to create the user, if necessary */
    list ($success, $ret) = _gallery_init();
    if (!$success) {
      gallery_error(t('Unable to log in to Gallery'), $ret);
      return;
    }
    break;

  case 'insert':
    list ($success, $ret) = _gallery_init();
    if (!$success) {
      gallery_error(t('Unable to initialize embedded Gallery'), $ret);
      return;
    }

    $ret = GalleryEmbed::createUser($user->uid,
				    array('username' => $user->name,
					  'email' => $user->mail,
					  'fullname' => $user->name,
					  'language' => $user->language,
					  'hashedpassword' => $user->pass,
					  'hashmethod' => 'md5'
					  ));
    if ($ret->isError()) {
      gallery_error(t('Error creating Gallery user'), $ret);
      return;
    }
    GalleryEmbed::done();
    break;

  case 'update':
    list ($success, $ret) = _gallery_init();
    if (!$success) {
      gallery_error(t('Unable to initialize embedded Gallery'), $ret);
      return;
    }

    // on update we can't be sure how much info $edit will contain.
    $name = ($edit['name']) ? $edit['name'] : $user->name;
    $language = ($edit['language']) ? $edit['language'] : $user->language;
    $pass = ($edit['pass']) ? md5($edit['pass']) : $user->pass;
    $email = ($edit['email']) ? $edit['mail'] : $user->mail;
    $ret = GalleryEmbed::updateUser($user->uid,
				    array('username' => $name,
                                          'fullname' => $name,
					  'email' => $mail,
                                          'language' => $language,
                                          'hashedpassword' => $pass,
                                          'hashmethod' => 'md5'));
    if ($ret->isError()) {
      // try to create user then.
      $ret = GalleryEmbed::createUser($user->uid,
				      array('username' => $name,
                                            'fullname' => $name,
					    'email' => $mail,
					    'language' => $language,
                                            'hashedpassword' => $pass,
                                            'hashmethod' => 'md5'
					    ));
      if ($ret->isError()) {
	gallery_error(t('Error updating Gallery user'), $ret);
	return;
      }
    }
    GalleryEmbed::done();
    break;

  case 'delete':
    list ($success, $ret) = _gallery_init();
    if (!$success) {
      gallery_error(t('Unable to initialize embedded Gallery'), $ret);
      return;
    }

    $ret = GalleryEmbed::deleteUser($user->uid);
    if ($ret->isError()) {
      gallery_error(t('Error deleting Gallery user'), $ret);
    }
    GalleryEmbed::done();
    break;
  }
}

/**
 * Implementation of hook_block
 *
 * - gallery navigation block (recommended)
 * - gallery imageblock (random, most viewed, etc)
 */
function gallery_block($op = 'list', $delta = 0, $edit = array()) {
  $typeMap = array('randomImage' => t('Random image'),
		   'recentImage' => t('Recent image'),
		   'viewedImage' => t('Viewed image'),
		   'randomAlbum' => t('Random album'),
		   'recentAlbum' => t('Recent album'),
		   'viewedAlbum' => t('Viewed album'),
		   'dailyImage' => t('Daily image'),
		   'weeklyImage' => t('Weekly image'),
		   'monthlyImage' => t('Monthly image'),
		   'dailyAlbum' => t('Daily album'),
		   'weeklyAlbum' => t('Weekly album'),
		   'monthlyAlbum' => t('Monthly album'));

  switch ($op) {
  case 'list':
    $blocks[0]['info'] = t('Gallery Block');
    return $blocks;

  case 'configure':
    $output = form_select(t('Image type'),
			  'gallery_block_block_' . $delta,
			  variable_get('gallery_block_block_' . $delta, 'randomImage'),
			  $typeMap,
			  t('Pick the type of image you\'d like to see'));
    $output .= form_checkboxes(
      t('Image data'),
      'gallery_block_show_' . $delta,
      variable_get('gallery_block_show_' . $delta, array('title', 'heading')),
      array('title' => 'Title',
	    'date' => 'Date',
	    'views' => 'View Count',
	    'owner' => 'Item owner',
	    'heading' => 'Heading',
	    'fullSize' => 'Full Size'),
      t('Choose the item metadata you\'d like to display'));
    return $output;

  case 'save':
    variable_set('gallery_block_block_' . $delta, $edit['gallery_block_block_' . $delta]);
    variable_set('gallery_block_show_' . $delta, $edit['gallery_block_show_' . $delta]);
    break;

  case 'view':
    list ($success, $ret) = _gallery_init(true);
    if (!$success) {
      gallery_error(t('Unable to initialize embedded Gallery'), $ret);
      return;
    }

    $params['block'] = variable_get('gallery_block_block_' . $delta, 'randomImage');
    $params['show'] = implode('|', variable_get('gallery_block_show_' . $delta, array()));

    // TODO: parameterize this
    $params['maxSize'] = 160;

    $block = array();
    list($ret, $content) = GalleryEmbed::getImageBlock($params);
    if ($ret->isError()) {
      gallery_error(t('Unable to get Gallery image block'), $ret);
      return;
    } else {
      if ($content) {
	$block['subject'] = $typeMap[$params['block']];
	$block['content'] = '<center>' . $content . '</center>';
      }
    }

    $ret = GalleryEmbed::done();
    if ($ret->isError()) {
      gallery_error(t('Unable to complete Gallery request'), $ret);
      return;
    }
    return $block;
  }
}

/**
 * implementation of hook_search
 */
function gallery_search($op = 'search', $keys = null) {
  switch ($op) {
  case 'name':
    return t('gallery');
  case 'search':
    $find = array();

    list ($success, $ret) = _gallery_init(true);
    if (!$success) {
      gallery_error(t('Unable to initialize embedded Gallery'), $ret);
      return;
    }

    list ($ret, $results) = GalleryEmbed::searchScan($keys, 20);
    if (!$ret->isError()) {
      $urlGenerator =& $GLOBALS['gallery']->getUrlGenerator();
      foreach ($results as $name => $module) {
	if (count($module['results']) > 0) {
	  foreach ($module['results'] as $result) {
	    $excerpt = array();
	    foreach ($result['fields'] as $field) {
	      $words = search_keywords_split($keys);
	      foreach ($words as $word) {
		if (preg_match("/$word/", $field['value'])) {
		  $excerpt[] = $field['key'] .': '.search_excerpt($keys, $field['value']);
		}
	      }
	    }
	    $find[] = array('title' => $result['fields'][0]['value'],
			    'link'  => $urlGenerator->generateUrl(array('itemId' => $result['itemId'])),
			    'type'  => $module['name'],
			    'snippet' => implode('<br />', $excerpt));
	  }
	}
      }
    }
    return $find;
  }
}

/**
 * Main gallery display page
 */
function gallery_page() {
  list ($success, $ret) = _gallery_init(true);
  if (!$success) {
    gallery_error(t('Unable to initialize embedded Gallery'), $ret);
    print theme('page', 'You need to <a href="/admin/settings/gallery">configure your embedded Gallery</a>');
    return;
  }

  /* Pass any excess path info to G2 */
  $path = substr($_GET['q'], 7 /* length of 'gallery/' */);
  if (!empty($path)) {
    $_GET[GALLERY_FORM_VARIABLE_PREFIX . 'path'] = $path;
  }

  $result = GalleryEmbed::handleRequest();
  if (!$result['isDone']) {
    list($title, $css, $javascript) = GalleryEmbed::parseHead($result['headHtml']);
    if (!empty($javascript)) {
      drupal_set_html_head(implode("\n",$javascript));
    }
    drupal_set_html_head(implode("\n",$css));
    drupal_set_title($title);
    print theme('page', $result['bodyHtml']);
  }
}

/**
 * fetch a galleryEmbed object
 */
function _gallery_init($full = false) {
  global $user, $base_url;

  $galleryDir = variable_get('gallery_dir', 'gallery2/');

  $embedPath = $galleryDir . '/embed.php';
  if (!is_readable($embedPath)) {
    return array(false, null);
  }

  include_once($galleryDir . '/embed.php');

  // TODO: using the galleryDir as the relativeG2Path requires that
  // Gallery2 be installed as a subdir of Drupal, which is not necessarily
  // ideal.  Make this a configuration option.
  $relativeG2Path = $galleryDir;

  $embedUri = url('gallery');
  $embedPath = str_replace('http://'.$_SERVER['HTTP_HOST'], '', $base_url) . '/';
  $params = array('embedUri' => $embedUri,
                  'embedPath' => $embedPath,
                  'relativeG2Path' => $relativeG2Path,
                  'loginRedirect' => url('user/login'),
                  'activeUserId' => $user->uid,
                  'activeLanguage' => $user->language,
                  'fullInit' => $full);
  $ret = GalleryEmbed::init($params);
  if ($ret->getErrorCode() & ERROR_MISSING_OBJECT) {
    // Our user mapping is missing.  Make a mapping, or create a new user.
    $g2_user = null;

    // Get the G2 user that matches the Drupal username
    list ($ret, $g2_user) = GalleryCoreApi::fetchUserByUsername($user->name);
    if ($ret->isError() && !($ret->getErrorCode() & ERROR_MISSING_OBJECT)) {
      return array(false, $ret);
    }

    if (!isset($g2_user)) {
      // No G2 user with a matching username.  If this is the admin user, we're going to
      // try a little harder and match it to the oldest admin in G2.
      if ($user->uid == 1) {
	list ($ret, $admin_group_id) =
	  GalleryCoreApi::getPluginParameter('module', 'core', 'id.adminGroup');
	if ($ret->isError()) {
	  return array(false, $ret);
	}

	list ($ret, $g2_users) = GalleryCoreApi::fetchUsersForGroup($admin_group_id);
	if ($ret->isError()) {
	  return array(false, $ret);
	}

	$keys = array_keys($g2_users);
	$g2_user_name = $users[$keys[0]];
	list ($ret, $g2_user) = GalleryCoreApi::fetchUserByUsername($g2_user_name);
	if ($ret->isError()) {
	  return array(false, $ret);
	}
      }
    }

    if (isset($g2_user)) {
      $ret = GalleryEmbed::addExternalIdMapEntry($user->uid, $g2_user->getId(), 'GalleryUser');
      if ($ret->isError()) {
	return array(false, $ret);
      }
    } else {
      // No matching G2 user found -- create one.
      $ret = GalleryEmbed::createUser($user->uid, array('username' => $user->name,
							'email' => $user->mail,
							'fullname' => $user->name,
							'language' => $user->language,
							'hashedpassword' => $user->pass,
							'hashmethod' => 'md5'));
      if ($ret->isError()) {
	return array(false, $ret);
      }
    }
  }

  return array(true, GalleryStatus::success());
}

function gallery_error($message, $ret) {
  $error_mode = variable_get('gallery_error_mode', array());
  if (in_array(2, $error_mode)) {
    drupal_set_message($message);
  }

  if (isset($ret)) {
    $full_message = $message . '<br/>' . $ret->getAsHtml();
  } else {
    $full_message = $message;
  }

  if (in_array(1, $error_mode)) {
    watchdog('gallery', $full_message, WATCHDOG_ERROR);
  }
}
?>