summaryrefslogtreecommitdiffstats
path: root/gallery_user.inc
blob: a06e932fd0cea199aba22284a908fe62e4564769 (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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<?php
// $Id$

/**
 * gallery.module : gallery_user.inc
 * User Functions (insert, update, delete, view, details, ...)
 */
 
define(G2MAP_UNKNOWN,                             0);
define(G2MAP_USER_EXISTS,                         1);
define(G2MAP_USER_EXISTS_BUT_NEEDS_MAPPING,       2);
define(G2MAP_USER_DOES_NOT_EXIST_BUT_IS_MAPPED,   3);
define(G2MAP_USER_DOES_NOT_EXIST,                 4);

define(G2USERINFO_ERROR_OK,                       1);
define(G2USERINFO_ERROR_MISSING,                  2);
define(G2USERINFO_ERROR_USERNAME,                 3);
define(G2USERINFO_ERROR_FULLNAME,                 4);
define(G2USERINFO_ERROR_FULLNAME_MISSING,         5);
define(G2USERINFO_ERROR_FULLNAME_INCORRECT,       6);
define(G2USERINFO_ERROR_EMAIL,                    7);
define(G2USERINFO_ERROR_PASSWORD,                 8);
define(G2USERINFO_ERROR_BLOCKED,                  9);

require_once(drupal_get_path('module', 'gallery') .'/gallery_groups.inc');
 
/**
 * Insert new user
 */
function gallery_user_insert(&$edit, $user) {
    $user->roles = isset($edit['roles']) ? $edit['roles'] : $user->roles;
    
    gallery_user_modify($user, 'create');
}

/**
 * Update a user with new information
 */
function gallery_user_update(&$edit, $user) {
  $user->language = ($edit['language']) ? $edit['language'] : gallery_get_language($user);
  $user->pass = ($edit['pass']) ? md5($edit['pass']) : $user->pass;
  $user->status = ($edit['status']) ? $edit['status'] : $user->status;
  $user->mail = ($edit['mail']) ? $edit['mail'] : $user->mail;
  $user->roles = isset($edit['roles']) ? $edit['roles'] : $user->roles;

  // fullname support
  if (module_exists('profile') && variable_get('gallery_use_full_name', FALSE)) {
    $fullname_field = variable_get('gallery_profile_full_name_field', 'profile_full_name');
    $user->$fullname_field = ($edit[$fullname_field]) ? $edit[$fullname_field] : $user->$fullname_field;
  }
  
  // username is about to change
  if ($namechange = $edit['name'] && ($edit['name'] != $user->name)) {
    // make sure the original user is up to date
    gallery_user_modify($user, 'update');
  }
  
  $user->name = ($edit['name']) ? $edit['name'] : $user->name;
  
  if ($namechange) {
    // change username
    gallery_user_modify($user, 'username');
  }
  else {
    // update user
    gallery_user_modify($user, 'update');
  }
}

/**
 * Delete the user from the Gallery 
 */ 
function gallery_user_delete($user) {
  gallery_user_modify($user, 'delete');
}

/**
 * Modify (create/update/delete) a user
 */
function gallery_user_modify($user, $action = 'create', $groups = FALSE, $vars = NULL) {
  if (!_gallery_init(TRUE, $vars)) {
    return FALSE;
  }

  // check for fullname support
  $fullname_field = variable_get('gallery_profile_full_name_field', 'profile_full_name');
  $usefullname = module_exists('profile') && variable_get('gallery_use_full_name', 0);
  $fullname = $usefullname ? (isset($user->$fullname_field) ? $user->$fullname_field : '') : $user->name;

  // generate random password for G2 if user is blocked
  $pass = ($user->status) ? $user->pass : user_password(20);

  switch ($action) {
    case 'username':
      $ret = GalleryEmbed::updateUser($user->uid,
              array('username' => $user->name,
                    'fullname' => $fullname,
                    'email' => $user->mail,
                    'language' => gallery_get_language($user),
                    'hashedpassword' => $pass,
                    'hashmethod' => 'md5'));
      if ($ret) {
        gallery_error(t('Error updating Gallery user (username changed)'), $ret);
        return FALSE;
      }
      break;
    case 'create' :
    case 'update' :
      // get map state of the user
      list($g2_user_state, $g2_user, $ret) = gallery_user_map_state($user);
      if ($ret) {
        gallery_error(t('Error determining user map state'), $ret);
        return FALSE;
      }
      
      // complete user mapping
      switch ($g2_user_state) {
        case G2MAP_USER_EXISTS_BUT_NEEDS_MAPPING:
          // create map entry for the user
          $ret = GalleryEmbed::addExternalIdMapEntry($user->uid, $g2_user->getId(), 'GalleryUser');
          if ($ret) {
            gallery_error(t('Error creating map entry (ExternlIdMapEntry)'), $ret);
            return FALSE;
          }
        case G2MAP_USER_EXISTS:
          // update user (Drupal -> G2)
          $ret = GalleryEmbed::updateUser($user->uid,
                  array('username' => $user->name,
                        'fullname' => $fullname,
                        'email' => $user->mail,
                        'language' => gallery_get_language($user),
                        'hashedpassword' => $pass,
                        'hashmethod' => 'md5'));
          if ($ret) {
            gallery_error(t('Error updating Gallery user'), $ret);
            return FALSE;
          }
          break;
        case G2MAP_USER_DOES_NOT_EXIST_BUT_IS_MAPPED:
          // remove mapping for non-existing user
          // (also happens if gallery_user_modify() is called with a changed username)
          $ret = GalleryCoreApi::removeMapEntry('ExternalIdMap', array('externalId' => $user->uid, 'entityType' => 'GalleryUser'));
          if ($ret) {
            gallery_error(t('Error removing map entry (ExternlIdMapEntry)'), $ret);
            return FALSE;
          }
        case G2MAP_USER_DOES_NOT_EXIST:
          // create new user
          if (!$user->uid)
            return FALSE;
          $ret = GalleryEmbed::createUser($user->uid,
                  array('username' => $user->name,
                        'email' => $user->mail,
                        'fullname' => $fullname,
                        'language' => gallery_get_language($user),
                        'hashedpassword' => $pass,
                        'hashmethod' => 'md5'));
          if ($ret) {
            gallery_error(t('Error creating Gallery user'), $ret);
            return FALSE;
          }
          list($ret, $g2_user) = GalleryCoreApi::loadEntityByExternalId($user->uid, 'GalleryUser');
          if ($ret) {
            gallery_error(t('Error loading Gallery user'), $ret);
            return FALSE;
          }
          break;
      }
      // update group info
      _gallery_groups_user($user, $groups);
      // admin role mapping
      $admin_role = variable_get('gallery_user_admin_role', 0);
      if (($admin_role && in_array($admin_role, array_keys($user->roles))) || ($user->uid == 1)) {
        // get G2 admin group id
        list($ret, $g2_admin_gid) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.adminGroup');
        if ($ret) {
          gallery_error(t('Error getting \'adminGroup\' id'), $ret);
          return FALSE;
        }
        // add user to admin group
        $ret = GalleryCoreApi::addUserToGroup($g2_user->getId(), $g2_admin_gid);
        if ($ret) {
          gallery_error(t('Error adding user to Gallery group (:gid)',
            array(':gid' => $g2_admin_gid)), $ret);
          return FALSE;
        }
      }
      break;
    case 'delete' :
      $ret = GalleryEmbed::deleteUser($user->uid);
      if ($ret) {
        gallery_error(t('Error deleting Gallery user'), $ret);
        return FALSE;
      }
      break;
  }

  GalleryEmbed::done();
  return TRUE;
}

/**
 * Sync user info for $uid
 */
function _gallery_user_sync($uid) {
  $user = user_load(array('uid' => $uid));
  gallery_user_modify($user, 'update', TRUE);
}

/**
 * View Gallery user details for a specific user
 */
function gallery_user_view($user) {
  if (variable_get('gallery_user_hide_profile', 0) || !_gallery_init(TRUE)) {
    return;
  }
  // get map status info
  $g2_userinfo = gallery_user_map_info($user);
  // load G2 user
  list($ret, $g2_user) = GalleryCoreApi::loadEntityByExternalId($user->uid, 'GalleryUser');
  if ($ret) {
    if (!($ret->getErrorCode() & ERROR_MISSING_OBJECT)) {
      gallery_error(t('Error loading Gallery user'), $ret);
      return;
    }
  }
  // fetch user album id
  if ($g2_user) {
    list($ret, $album_id) =
      GalleryCoreApi::getPluginParameter('module', 'useralbum', 'albumId', $g2_user->getId());
    if ($ret) {
      gallery_error(t('Error fetching user album id'), $ret);
      return;
    }
  }
  // generate link to user album
  if (!empty($album_id)) {
    $link = gallery_generate_url(array('view' => 'core.ShowItem', 'itemId' => $album_id), FALSE);
    $form['gallery_view_user_album'] = array(
      'value' => l(t('User Album'), $link),
      'class' => 'send-message');
  }
  else {
    $form['gallery_view_user_album'] = array(
      'value' => t('User has not created an album yet'),
      'class' => 'send-message');
  }
  // sync status
  if (($g2_userinfo['error']) && (user_access('administer users'))) {
    $form['gallery_view_user'] = array(
      'title' => t('Gallery2-Drupal Sync Status'), 
      'value' => implode(',<br />', gallery_user_map_info_status($g2_userinfo['error'])) .'<br />');
  }
  
  GalleryEmbed::done();
  if (!empty($form)) {
    return array(t('Gallery2') => $form);
  }
}

/**
 * Get info about user map status
 */
function gallery_user_map_info($user) {
  $g2_userinfo['error'] = array();
  // user map entry
  $ret = GalleryEmbed::isExternalIdMapped($user->uid, 'GalleryUser');
  if ($ret && !($ret->getErrorCode() & ERROR_MISSING_OBJECT)) {
    $g2_userinfo['g2_id'] = -1;
    $g2_userinfo['error'][] = G2USERINFO_ERROR_MISSING;
    $g2_userinfo['sync_ok'] = 0;

    return $g2_userinfo;
  }
  // but user not available
  list($ret, $g2_user) = GalleryCoreApi::loadEntityByExternalId($user->uid, 'GalleryUser');
  if ($ret) {
    $g2_userinfo['g2_id'] = -1;
    $g2_userinfo['error'][] = G2USERINFO_ERROR_MISSING;
    $g2_userinfo['sync_ok'] = 0;

    return $g2_userinfo;
  }
  // username
  $g2_userinfo['g2_id'] = $g2_user->id;
  if ($g2_user->getuserName() != $user->name) {
    $g2_userinfo['error'][] = G2USERINFO_ERROR_USERNAME;
  }
  // fullname
  if (module_exists('profile') && variable_get('gallery_use_full_name', 0)) {
    $fullname_field = variable_get('gallery_profile_full_name_field', 'profile_full_name');
    $fullname_result = db_query("SELECT v.value FROM {profile_values} v INNER JOIN {profile_fields} f ON v.fid = f.fid AND v.uid=%d WHERE f.name = '%s'", $user->uid, $fullname_field);
    $fullname = db_fetch_object($fullname_result);
    $fullname = $fullname->value;
    if ($g2_user->getfullName() != $fullname) {
      $g2_userinfo['error'][] = G2USERINFO_ERROR_FULLNAME;
    }
    elseif (!$fullname) {
      $g2_userinfo['error'][] = G2USERINFO_ERROR_FULLNAME_MISSING;
    }
  }
  else {
    if ($g2_user->getfullName() != $user->name) {
      $g2_userinfo['error'][] = G2USERINFO_ERROR_FULLNAME_INCORRECT;
    }
  }
  // email adress
  if ($g2_user->getemail() != $user->mail) {
    $g2_userinfo['error'][] = G2USERINFO_ERROR_EMAIL;
  }
  // password
  if ($g2_user->gethashedPassword() != $user->pass) {
    $g2_userinfo['error'][] = ($user->status) ? G2USERINFO_ERROR_PASSWORD : G2USERINFO_ERROR_BLOCKED;
  }
  // overall sync status
  $g2_userinfo['sync_ok'] = (!$g2_userinfo['error']);
  if ($g2_userinfo['sync_ok']) {
    $g2_userinfo['error'][] = G2USERINFO_ERROR_OK;
  }

  return $g2_userinfo;
}

/**
 * Get string representation of the use map status
 */
function gallery_user_map_info_status($info = array()) {
  $info_map = array(
    G2USERINFO_ERROR_OK => t('OK'),
    G2USERINFO_ERROR_MISSING => t('Missing from G2'),
    G2USERINFO_ERROR_USERNAME => t('Different Usernames'),
    G2USERINFO_ERROR_FULLNAME => t('Different Full Names'),
    G2USERINFO_ERROR_FULLNAME_MISSING => t('G2 Full Name missing'),
    G2USERINFO_ERROR_FULLNAME_INCORRECT => t('G2 Full Name incorrect'),
    G2USERINFO_ERROR_EMAIL => t('Different E-Mails'),
    G2USERINFO_ERROR_PASSWORD => t('Different Passwords'),
    G2USERINFO_ERROR_BLOCKED => t('Blocked User'),
  );
  
  if (count($info)) {
    $status = array();
    foreach ($info as $key => $value) {
      $status[] = $info_map[$value];
    }
    return $status;
  }
  
  return $info_map;
}

/**
 * Get state of user mapping
 */
function gallery_user_map_state($user) {
  // see if user already exists in G2
  list($ret, $g2_user) = GalleryCoreApi::fetchUserByUsername($user->name);
  if (!$ret) {
    // user is in G2, so map the user if needed
    $ret2 = GalleryEmbed::isExternalIdMapped($user->uid, 'GalleryUser');
    if ($ret2) {
      if ($ret2->getErrorCode() & ERROR_MISSING_OBJECT) {
        return array(G2MAP_USER_EXISTS_BUT_NEEDS_MAPPING, $g2_user, NULL);
      }
      else {
        // some other error
        return array(G2MAP_UNKNOWN, $g2_user, $ret2);
      }
    }
    else {
        return array(G2MAP_USER_EXISTS, $g2_user, NULL);
    }
  }
  elseif ($ret->getErrorCode() & ERROR_MISSING_OBJECT) {
    // user does not yet exist in G2
    // check if the extID was mapped (it should not be)
    $ret2 = GalleryEmbed::isExternalIdMapped($user->uid, 'GalleryUser');
    if ($ret2) {
      if ($ret2->getErrorCode() & ERROR_MISSING_OBJECT) {
        return array(G2MAP_USER_DOES_NOT_EXIST, $g2_user, NULL);
      }
      else {
        // some other error
        return array(G2MAP_UNKNOWN, $g2_user, $ret2);
      }
    }
    else {
      // user is mapped
      return array(G2MAP_USER_DOES_NOT_EXIST_BUT_IS_MAPPED, $g2_user, NULL);
    }
  }
  else {
    // some other error
    return array(NULL, $g2_user, $ret);
  }
}

/**
 * Import Gallery users into Drupal
 */
function _gallery_user_import($g2_users = array()) {
  // anonymous user id
  list($ret, $guest) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.anonymousUser');
  if (!$ret) {
    unset($g2_users[$guest]);
  }
  $users = _gallery_user_drupal_users();
  $roles_flip = array_flip(user_roles());
  // import all missing users into Drupal
  $g2_import_users = array_diff($g2_users, $users);
  foreach ($g2_import_users as $g2_id => $g2_username) {
    list($ret, $g2_user) = GalleryCoreApi::fetchUserByUsername($g2_username);
    if ($ret) {
      gallery_error(t('Error fetching user by username (:name)',
        array(':name' => $g2_username)), $ret);
      return FALSE;
    }
    else {
      $values['name'] = $g2_user->userName;
      $values['pass'] = $g2_user->hashedPassword;
      $values['mail'] = $g2_user->email;
      $values['status'] = TRUE;
      /**/
      $values['roles'] = array();
      list($ret, $g2_groups) = GalleryCoreApi::fetchGroupsForUser($g2_user->getId());
      if ($ret) {
        gallery_error(t('Error fetching groups for user (uid: :uid)',
          array(':uid' => $g2_id)), $ret);
        return array();
      }
      foreach ($g2_groups as $g2_gid => $g2_groupname) {
        $rid = $roles_flip[$g2_groupname];
        $values['roles'][$rid] = $rid;
      }
      unset($values['roles'][DRUPAL_ANONYMOUS_RID]);
      /**/
      $values['notify'] = FALSE;
      drupal_execute('user_register', $values);
      // override password (we only have the md5 hash)
      if (!variable_get('gallery_user_import_override', 1)) {
        _gallery_user_drupal_override($g2_user->userName, array('pass' => $g2_user->hashedPassword));
      }
    }
  }
  // create new mappings and override user details (if requested)
  $users = _gallery_user_drupal_users();
  $users = array_intersect($users, $g2_users);
  foreach ($users as $uid => $username) {
    if (variable_get('gallery_user_import_override', 1)) {
      list($ret, $g2_user) = GalleryCoreApi::fetchUserByUsername($username);
      if ($ret) {
        gallery_error(t('Error fetching user by username (:name)',
          array(':name' => $username)), $ret);
        return FALSE;
      }
      $values = array();
      $values['pass'] = $g2_user->hashedPassword;
      $values['mail'] = $g2_user->email;
      $values['language'] = $g2_user->language;
      $values['fullname'] = $g2_user->fullName;
      _gallery_user_drupal_override($username, $values);
    }
    // create new mappings
    $ret = GalleryEmbed::addExternalIdMapEntry($uid, $g2_user->getId(), 'GalleryUser');
    if ($ret) {
      gallery_error(t('Error creating map entry (ExternlIdMapEntry)'), $ret);
      return FALSE;
    }
  }
  
  return TRUE;
}

/**
 * Override Drupal user details (mail, password, language, ...)
 */
function _gallery_user_drupal_override($name, $values = array()) {
  $user = db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '%s'", $name));
  if ($user) {
    $user->pass = $values['pass'] ? $values['pass'] : $user->pass;
    $user->mail = $values['mail'] ? $values['mail'] : $user->mail;
    $user->language = $values['language'] ? $values['language'] : $user->language;
    db_query("UPDATE {users} SET pass = '%s', mail = '%s', language = '%s' WHERE name = '%s'",
      $user->pass, $user->mail, $user->language, $name);
    // fullname support
    if ($values['fullname'] && module_exists('profile') && variable_get('gallery_use_full_name', 0)) {
      $fullname_field = variable_get('gallery_profile_full_name_field', 'profile_full_name');
      $field_id = db_result(db_query("SELECT v.fid FROM {profile_values} v INNER JOIN {profile_fields} f ON v.fid = f.fid WHERE f.name = '%s'", $fullname_field));
      if ($field_id) {
        db_query("DELETE FROM {profile_values} WHERE fid = %d AND uid = %d", $field_id, $user->uid);
        db_query("INSERT INTO {profile_values} (fid, uid, value) VALUES (%d, %d, '%s')", $field_id, $user->uid, $values['fullname']);
      }
    }
  }
}

/**
 * Fetch all existing Drupal users (uid => username)
 */
function _gallery_user_drupal_users() {
  $users = array();
  $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0");
  while ($user = db_fetch_object($result)) {
    $users[$user->uid] = $user->name;
  }
  
  return $users;
}

?>