buddylist.module 68.9 KB
Newer Older
robertDouglass's avatar
robertDouglass committed
1 2 3 4 5 6 7 8 9 10
<?php
// $Id$

if (module_exists('views')) {
  include_once('buddylist_views.inc');
}


define('BUDDYLIST_ADD_SUBJECT', variable_get('buddylist_add_subject', "[@site] You are @adder_name's newest @buddy"));
define('BUDDYLIST_REMOVE_SUBJECT', variable_get('buddylist_remove_subject', "[@site] You have been removed from @adder_name's @buddy list"));
11 12
define('BUDDYLIST_REQUEST_SUBJECT', variable_get('buddylist_request_subject', "[@site] @adder_name has requested to add you to his/her @buddy list"));
define('BUDDYLIST_APPROVAL_SUBJECT', variable_get('buddylist_approval_subject', "[@site] @addee_name has approved your @buddy list add request"));
robertDouglass's avatar
robertDouglass committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

/**
 * returns an array of common translation placeholders
 */
function buddylist_translation() {
  $translations = array(
    '@buddy' => t('buddy'),
    '@Buddy' => t('Buddy'),

    '@buddylist' => t('buddylist'),
    '@Buddylist' => t('Buddylist'),

    '@buddies' => t('buddies'),
    '@Buddies' => t('Buddies'),

    '@buddyof' => t('buddy of'),
    '@Buddyof' => t('Buddy of'),
  );
31
  return variable_get('buddylist_translation', $translations);
robertDouglass's avatar
robertDouglass committed
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
}


/**
 * Implementation of hook_help
 */
function buddylist_help($section) {
  switch ($section) {
    case 'admin/help#buddylist':
      $output = t("
<p>@Buddy list enables users to keep a list of @buddies from their social network in their user account.
Users can also track what their @buddies are posting to the site.
Furthermore, they can track their <i>@buddies'</i> @buddies and thereby explore their social network.</p>
<p>If the administrator has enabled the profile module, users can add @buddies via their @buddies' user profiles.
On the \"View\" tab of each user's profile, there is a \"@Buddy list\" section.  Select the 'add @buddy' action to add the user to your @buddy list.
If a user is already in your @buddy list, the 'delete' action will remove the @buddy. Administrators can also enable the @buddylist block.
This block allows you to see a list of your @buddies. If the <a href=\"http://drupal.org/project/foaf\">Friends Of A Friend (FOAF)</a> module is enabled, it will be possible to share @buddy lists with other FOAF-aware social networking applications.</p>
<p>You can:</p>
<ul>
<li>add a @buddy by looking at their profile: <a href=\"@userprofiles\" title=\"View user profiles\">view user profiles</a></li>
<li>allow users to view profiles in <a href=\"@setaccesspermissions\" title=\"set access permissions\">administer &raquo; access control</a></li>
<li>enable the @buddy list block at <a href=\"@blockadministration\" title=\"block administration\">administer &raquo; block</a></li>
<li>administer the @buddy list block at <a href=\"@buddylistsettings\" title=\"@buddylist settings\">administer &raquo; settings &raquo; @buddylist</a></li>
</ul>

<p>For more information, read the configuration and customization handbook <a href=\"http://drupal.org/handbook/modules/Buddylist\" title=\"Buddylist page\">Buddylist page</a></p>",
array('@userprofiles' => url('profile'),
      '@setaccesspermissions' => url('admin/user/access'),
      '@blockadministration' => url('admin/build/block'),
      '@buddylistsettings' => url('admin/settings/buddylist')
      ) + buddylist_translation());
      return $output;
  }
}


/**
 * Implementation of hook_perm
 */
function buddylist_perm() {
  return array('maintain buddy list', 'view buddy lists');
}

/**
 * Implementation of hook_menu
 */
function buddylist_menu($may_cache) {
  global $user;

  $items = array();
  $id = is_numeric(arg(1)) ? arg(1) : $user->uid;

  if ($may_cache) {
    // buddylist settings page
    $items[] = array(
      'path' => 'admin/settings/buddylist',
      'title' => t('Buddylist'), // Note that this isn't translated on purpose since it is for the admin
      'description' => t('Buddylist configuration options for blocks, email, etc.'),
      'callback' => 'drupal_get_form',
      'callback arguments' => 'buddylist_admin_settings',
      'access' => user_access('administer site configuration'),
   );
    // my buddylist menu item
    $items[] = array(
      'path' => 'buddylist',
      'title' => t('My @buddylist', buddylist_translation()),
      'access' => (user_access('maintain buddy list') && $id),
      'callback' => 'buddylist_buddylisting_page',
100
      'callback arguments' => array($user->uid, 'buddies'),
robertDouglass's avatar
robertDouglass committed
101 102 103 104 105 106 107
    );
  }
  else {
    // 'edit access' only granted to user's own buddy list or to administrative users
    $editAccess = (
      ($id == $user->uid && user_access('maintain buddy list') && $user->uid)
      || user_access('administer users'));
108

109
    $approval_required = variable_get('buddylist_require_approval', 0);
robertDouglass's avatar
robertDouglass committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

    $items[] = array(
      'path' => 'buddy/add',
      'title' => t('Add to @buddylist', buddylist_translation()),
      'access' => $editAccess,
      'callback' => 'drupal_get_form',
      'callback arguments' => array('buddylist_addbuddy', arg(2)),
      'type' => MENU_CALLBACK,
    );
    $items[] = array(
      'path' => 'buddy/delete',
      'title' => t('Delete from @buddylist', buddylist_translation()),
      'access' => $editAccess,
      'callback' => 'drupal_get_form',
      'callback arguments' => array('buddylist_deletebuddy', arg(2)),
      'type' => MENU_CALLBACK,
    );

    // 'view only' tabs
129
    $viewAccess = (($id == $user->uid && user_access('maintain buddy list')) || user_access('view buddy lists'));
130

131
    // If buddylist approval is required, then upon approval, both parties become buddies of each other.
132
    // So, in effect, idea 'buddyof' becomes redundant.
133
    if (!$approval_required) {
134 135 136 137 138 139 140 141 142
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies',
        'title' => t('@Buddies', buddylist_translation()),
        'access' => $viewAccess,
        'callback' => 'buddylist_buddylisting_page',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'weight' => -1,
        'callback arguments' => array($id)
      );
143 144 145 146 147 148 149 150 151 152
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddyof',
        'title' => t('@Buddyof', buddylist_translation()),
        'access' => $viewAccess,
        'callback' => 'buddylist_buddylisting_page',
        'type' => MENU_LOCAL_TASK,
        'weight' => 1,
        'callback arguments' => array($id, 'buddyof')
      );
    }
robertDouglass's avatar
robertDouglass committed
153 154 155 156

    // subtabs
    $items[] = array(
      'path' => 'buddylist/'. $id .'/buddies/list',
157
      'title' => t('@Buddylist', buddylist_translation()),
robertDouglass's avatar
robertDouglass committed
158 159 160 161 162 163 164 165 166 167 168 169
      'access' => $viewAccess,
      'callback' => 'buddylist_buddylisting_page',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -1,
      'callback arguments' => array($id),
    );
    $items[] = array(
      'path' => 'buddylist/'. $id .'/buddies/recent',
      'title' => t('Recent posts'),
      'access' => ($viewAccess && module_exists('tracker')),
      'callback' => 'buddylist_buddiesrecent_page',
      'type' => MENU_LOCAL_TASK,
170
      'weight' => 3,
robertDouglass's avatar
robertDouglass committed
171 172
      'callback arguments' => array($id),
    );
173 174 175 176 177 178 179
    if (variable_get('buddylist_buddygroups', FALSE)) {
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/groups/view',
        'title' => t('View groups'),
        'access' => $viewAccess,
        'callback' => 'buddylist_buddiesgroups_page',
        'type' => MENU_LOCAL_TASK,
180
        'weight' => 5,
181 182 183 184 185 186 187 188
        'callback arguments' => array($id),
      );
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/groups/edit',
        'title' => t('Edit groups'),
        'access' => $editAccess,
        'callback' => 'buddylist_buddiesgroups_edit',
        'type' => MENU_LOCAL_TASK,
189
        'weight' => 6,
190 191 192 193
        'callback arguments' => array($id),
      );
    }

194 195 196 197
    // sub-subtabs
    if ($approval_required && $editAccess) {
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/requests',
198
        'title' => t('Pending requests'),
199
        'access' => $editAccess,
200
        'callback' => 'theme',
201 202
        'type' => MENU_LOCAL_TASK,
        'weight' => 0,
203
        'callback arguments' => array('buddylist_pending_requests', $id)
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
      
      $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/requested/accept',
        'title' => t('Accept Request'),
        'access' => $editAccess,
        'type' => MENU_CALLBACK,
        'callback' => 'drupal_get_form', 
        'callback arguments' => array('buddylist_pending_requested_accept',$id),
      );
	  
	  $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/requested/deny',
        'title' => t('Deny Request'),
        'access' => $editAccess,
        'type' => MENU_CALLBACK,
        'callback' => 'drupal_get_form', 
        'callback arguments' => array('buddylist_pending_requested_deny',$id),
      );
      
       $items[] = array(
        'path' => 'buddylist/'. $id .'/buddies/request/cancel',
        'title' => t('Cancel Request'),
        'access' => $editAccess,
        'type' => MENU_CALLBACK,
        'callback' => 'drupal_get_form', 
        'callback arguments' => array('buddylist_cancel_request',$id),
      );
      
233
    }
robertDouglass's avatar
robertDouglass committed
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

    // other callbacks
    if ($id != $user->uid) {
      // This callback can interfere with the 'my buddylist' menu item,
      // so we only load it if the user is viewing another user's list.
      $items[] = array(
        'path' => 'buddylist/'. $id,
        'title' => t('@Buddylist', buddylist_translation()),
        'access' => (($viewAccess || $editAccess) && $id),
        'callback' => 'buddylist_buddylisting_page',
        'type' => MENU_CALLBACK,
        'callback arguments' => array($id),
      );
    }
    $items[] = array(
      'path' => 'buddylist/'. $id .'/buddies/recent/feed',
      'title' => t('Xml feed'),
      'access' => $viewAccess,
      'callback' => 'buddylist_buddyfeed',
      'type' => MENU_CALLBACK,
      'callback arguments' => array($id),
    );
  }

  return $items;
}

/**
 * Buddylist administration settings page
 */
function buddylist_admin_settings() {
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
  $form['general'] = array(
    '#type' => 'fieldset',
    '#title' => t('General settings'),
  );

  $form['general']['buddylist_require_approval'] = array(
    '#type' => 'radios',
    '#title' => t('Require approval'),
    '#default_value' => variable_get('buddylist_require_approval', 0),
    '#description' => t("Select 'Yes' if a user's request to be someone's @buddy should be approved by the other user first.  Upon approval, both parties will be @buddies of each other.", buddylist_translation()),
    '#options' => array(1 => t('Yes'), 0 => t('No'))
  );
  $form['general']['buddylist_buddygroups'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable @buddy groups', buddylist_translation()),
    '#description' => t('Enables @buddylist @buddy groups. Users will be able to create @buddy groups to manage their @buddies.', buddylist_translation()),
    '#default_value' => variable_get('buddylist_buddygroups', FALSE),
  );

  // User profile page settings
  $form['profile_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Profile page options'),
  );
  $form['profile_settings']['buddylist_prof_buddies'] = array(
    '#type' => 'select',
    '#title' => t('Number of @buddies and users who\'ve added me', buddylist_translation()),
    '#default_value' => variable_get('buddylist_prof_buddies', 5),
    '#options' => drupal_map_assoc(range(0, 10)),
    '#description' => t('The default maximum number of @buddies and users who\'ve added me as a @buddy to display on a user\'s profile page.', buddylist_translation()),
  );
robertDouglass's avatar
robertDouglass committed
296 297 298 299 300 301 302 303 304 305 306

  // TODO: move these to block settings
  $form['block_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('@Buddylist block options', buddylist_translation()),
  );
  $form['block_settings']['buddylist_blocklisting_size'] = array(
    '#type' => 'select',
    '#title' => t("Number of @buddies to list in the user's @buddy block", buddylist_translation()),
    '#default_value' => variable_get('buddylist_blocklisting_size', 5),
    '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
307
    '#description' => t('This setting controls the maximum number of @buddies displayed in a user\'s "@buddylist block" given that the "@buddylist block" is enabled in the !link.', array('!link' => l(t('block settings'), 'admin/build/block')) + buddylist_translation()),
robertDouglass's avatar
robertDouglass committed
308 309 310 311 312 313
  );
  $form['block_settings']['buddylist_posts_block'] = array(
    '#type' => 'select',
    '#title' => t("Number of posts to list in the @buddies' recent posts block", buddylist_translation()),
    '#default_value' => variable_get('buddylist_posts_block', 7),
    '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
314
    '#description' => t('This setting controls the maximum number of posts to display in a user\'s "@buddy recent posts" block given that the "@buddies\' recent posts" block is enabled in the !link.', array('!link' => l(t('block settings'), 'admin/build/block')) + buddylist_translation()),
robertDouglass's avatar
robertDouglass committed
315 316 317 318 319 320 321 322 323
  );
  $form['block_settings']['buddylist_block_title'] = array(
    '#type' => 'textfield',
    '#title' => t('"My @buddies\' recent posts" block title', buddylist_translation()),
    '#default_value' => variable_get('buddylist_block_title', t("My @buddies' recent posts", buddylist_translation())),
    '#size' => 70,
    '#maxlength' => 128,
    '#description' => t('This will be the title for the recent @buddies post block. If none is specified, "My @buddies\' recent posts" will be used.', buddylist_translation()),
  );
324 325 326 327 328 329 330 331
  $form['block_settings']['buddylist_status_block_title'] = array(
    '#type' => 'textfield',
    '#title' => t('"My @buddy list status" block title', buddylist_translation()),
    '#default_value' => variable_get('buddylist_status_block_title', t("My @buddy list status", buddylist_translation())),
    '#size' => 70,
    '#maxlength' => 128,
    '#description' => t('This will be the title for the @buddy list status block. If none is specified, "My @buddy list status" will be used.', buddylist_translation()),
  );
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  $form['block_settings']['buddylist_list_block_title'] = array(
    '#type' => 'textfield',
    '#title' => t('"My @buddies list" block title', buddylist_translation()),
    '#weight' => 1,
    '#default_value' => variable_get('buddylist_list_block_title', t('My @buddy list', buddylist_translation())),
    '#size' => 70,
    '#maxlength' => 128,
    '#description' => t('This will be the title for the "My @buddy list" block. If none is specified, "My @buddy list" will be used.', buddylist_translation()),
  );
  $form['block_settings']['buddylist_block_if_no_buddies'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show "My @buddies list" block even if @buddylist is empty', buddylist_translation()),
    '#weight' => 2,
    '#default_value' => variable_get('buddylist_block_if_no_buddies', FALSE),
    '#description' => t('If a user has no @buddies, the @buddy block can show a message.', buddylist_translation()),
  );
  $form['block_settings']['buddylist_empty_text'] = array(
    '#type' => 'textarea',
    '#title' => t('Show this text in "My @buddies list" if @buddylist is empty', buddylist_translation()),
    '#weight' => 3,
    '#default_value' => variable_get('buddylist_empty_text', t(buddylist_empty_text_default(), buddylist_translation())),
    '#description' => t('If a user has no @buddies and the above checkbox is checked, this message is shown instead of a list.', buddylist_translation()),
  );
robertDouglass's avatar
robertDouglass committed
355 356 357 358 359

   $form['mail'] = array(
    '#type' => 'fieldset',
    '#title' => t('email'),
  );
360

361 362 363
  global $user;
  $macros = implode(', ', array_keys(buddylist_mail_replacements($user, $user)));
  $approval_macros = implode(', ', array_keys(buddylist_approval_mail_replacements($user, $user)));
robertDouglass's avatar
robertDouglass committed
364

365 366 367 368 369 370 371
  $form['mail']['buddylist_user_mail'] = array(
    '#type' => 'checkbox',
    '#title' => t('Allow users to turn off buddylist messages'),
    '#default_value' => variable_get('buddylist_user_mail', FALSE),
    '#description' => t('If you check this, users will have a new setting on their account edit page.'),
  );

robertDouglass's avatar
robertDouglass committed
372 373 374 375 376 377 378 379 380 381 382 383
  $form['mail']['buddylist_send_add'] = array(
    '#type' => 'checkbox',
    '#title' => t('Send add messages'),
    '#default_value' => variable_get('buddylist_send_add', FALSE),
  );

  $form['mail']['buddylist_add_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Added @buddy email subject', buddylist_translation()),
    '#default_value' => BUDDYLIST_ADD_SUBJECT,
  );

384
  $form['mail']['buddylist_add_message'] = array(
robertDouglass's avatar
robertDouglass committed
385 386
    '#type' => 'textarea',
    '#title' => t('Added @buddy email message', buddylist_translation()),
387
    '#default_value' => variable_get('buddylist_add_message', buddylist_mail_add_default()),
robertDouglass's avatar
robertDouglass committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    '#description' => t('Replacement strings are: %macros', array('%macros' => $macros)),
  );

  $form['mail']['buddylist_send_remove'] = array(
    '#type' => 'checkbox',
    '#title' => t('Send remove messages'),
    '#default_value' => variable_get('buddylist_send_remove', FALSE),
  );

  $form['mail']['buddylist_remove_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Removed @buddy email subject', buddylist_translation()),
    '#default_value' => BUDDYLIST_REMOVE_SUBJECT,
  );

403
  $form['mail']['buddylist_remove_message'] = array(
robertDouglass's avatar
robertDouglass committed
404
    '#type' => 'textarea',
405
    '#title' => t('Removed @buddy email message', buddylist_translation()),
406
    '#default_value' => variable_get('buddylist_remove_message', buddylist_mail_remove_default()),
robertDouglass's avatar
robertDouglass committed
407 408
    '#description' => t('Replacement strings are: %macros', array('%macros' => $macros)),
  );
409

410 411 412
  $form['mail']['buddylist_send_request'] = array(
    '#type' => 'checkbox',
    '#title' => t('Send request messages.'),
413
    '#description' => t('Check this box if you want users to receive an email when someone requests to be their buddy.  This setting only has effect if approval is required to be on someone\'s buddylist.'),
414 415
    '#default_value' => variable_get('buddylist_send_request', FALSE)
  );
416

417 418 419 420 421
  $form['mail']['buddylist_request_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('@buddy request email subject', buddylist_translation()),
    '#default_value' => BUDDYLIST_REQUEST_SUBJECT,
  );
422

423
  $form['mail']['buddylist_request_message'] = array(
424 425
    '#type' => 'textarea',
    '#title' => t('@buddy request email message', buddylist_translation()),
426
    '#default_value' => variable_get('buddylist_request_message', buddylist_mail_request_default()),
427 428
    '#description' => t('Replacement strings are: %macros', array('%macros' => $macros)),
  );
429

430 431 432 433
  $form['mail']['buddylist_send_approval'] = array(
    '#type' => 'checkbox',
    '#title' => t('Send approval messages'),
    '#default_value' => variable_get('buddylist_send_approval', FALSE),
434
    '#description' => t('Check this box if you want users to receive an email to the requester when someone approves an add request.  This setting only has effect if approval is required to be on someone\'s @buddylist.', buddylist_translation())
435
  );
436

437 438 439 440 441
  $form['mail']['buddylist_approval_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('@buddy request email subject', buddylist_translation()),
    '#default_value' => BUDDYLIST_APPROVAL_SUBJECT,
  );
442

443
  $form['mail']['buddylist_approval_message'] = array(
444 445
    '#type' => 'textarea',
    '#title' => t('@buddy approval email message', buddylist_translation()),
446
    '#default_value' => variable_get('buddylist_approval_message', buddylist_mail_approval_default()),
447
    '#description' => t('Replacement strings are: %macros', array('%macros' => $approval_macros)),
448
  );
robertDouglass's avatar
robertDouglass committed
449 450 451 452

  return system_settings_form($form);
}

453

robertDouglass's avatar
robertDouglass committed
454 455 456 457 458 459 460 461 462 463 464
/**
 * Implementation of hook_user
 */
function buddylist_user($type, &$edit, &$thisuser, $category = NULL) {
  global $user;

  $output = array();
  // show any buddylist notifications upon login and upon viewing own profile
  if (user_access('maintain buddy list') && (($type == 'login') || ($type == 'view') && ($thisuser->uid == $user->uid))) {
    buddylist_setmsg_received($thisuser);
  }
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  if ($type == 'view') {
    if ($list = buddylist_get_buddylist($thisuser)) {
      $output[] = array('title' => t('@Buddies', buddylist_translation()), 'value' => $list, 'class' => 'buddylist');
    }
    if ($list = buddylist_get_buddylist($thisuser, TRUE)) {
      $output[] = array('title' => t('@buddy of', buddylist_translation()), 'value' => $list, 'class' => 'buddyoflist');
    }
    if ($actions = buddylist_get_buddy_actions($user, $thisuser)) {
      $output[] = array('title' => t('@Buddy actions', buddylist_translation()), 'value' => theme('item_list', $actions), 'class' => 'buddylist_actions');
    }
    if(count($output) > 0) {
      return array(t('@Buddy List', buddylist_translation()) => $output);
    }
  }
  else if ($type == 'delete') {
    db_query("DELETE FROM {buddylist} WHERE uid = %d OR buddy = %d", $thisuser->uid, $thisuser->uid);
    db_query("DELETE FROM {buddylist_buddy_group} WHERE uid = %d OR buddy = %d", $thisuser->uid, $thisuser->uid);
    db_query("DELETE FROM {buddylist_groups} WHERE uid = %d", $thisuser->uid);
    db_query("DELETE FROM {buddylist_pending_requests} WHERE requester_uid = %d OR requestee_uid = %d", $thisuser->uid, $thisuser->uid);
  }
485 486 487
  else if ($type == 'load') {
    $thisuser->buddies = buddylist_get_buddies($thisuser->uid);
  }
488
  else if ($type == 'form' && $category == 'account' && variable_get('buddylist_user_mail', FALSE) && user_access('maintain buddy list', $thisuser)) {
489 490 491 492 493 494 495 496 497 498 499
    // when user tries to edit his own data
    $form['buddylist_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t('Buddylist settings'),
      '#weight' => 5);
    $form['buddylist_settings']['buddylist_mail'] = array(
      '#type' => 'checkbox',
      '#title' => t('Receive @buddylist notification mails', buddylist_translation()),
      '#default_value' => isset($edit['buddylist_mail']) ? $edit['buddylist_mail'] : 1,
      '#description' => t('If you check this, you will be notified about important actions regarding your @Buddylist.', buddylist_translation()));
    return $form;
500
  }
501 502 503 504 505 506 507
}

/*
 * Return a formatted list of buddies for the given user
 * @param $buddy_of If set to TRUE, a formatted list of users is returned, for whom this user is a buddy.
 */
function buddylist_get_buddylist($user, $buddy_of = FALSE) {
robertDouglass's avatar
robertDouglass committed
508

509
	if (user_access('view buddy lists') && !$buddy_of) {
robertDouglass's avatar
robertDouglass committed
510
    $i = 0;
511
    if ($buddies = buddylist_get_buddies($user->uid)) {
robertDouglass's avatar
robertDouglass committed
512 513 514 515
      foreach(array_keys($buddies) as $buddy) {
        $account = user_load(array('uid' => $buddy));
        $listbuddies[] = $account;
        $i++;
516
        if ($i > variable_get('buddylist_prof_buddies', 5)) {
robertDouglass's avatar
robertDouglass committed
517 518 519
          break;
        }
      }
520
      return theme('user_list', $listbuddies);
robertDouglass's avatar
robertDouglass committed
521
    }
522 523
	}
  else if (user_access('view buddy lists') && !variable_get('buddylist_require_approval', 0)) {
robertDouglass's avatar
robertDouglass committed
524 525 526
    // This portion of code is used to see if this $thisuser is a buddy of others and, if s/he is, returns a list
    // of people s/he is a buddy of.
    // Note the distinction between having a buddy and being someone else's buddy (i.e., 'buddyof')
527
    // Of course, this distinction doesn't exist if approval is required to add a buddy (in which case, buddy relationships are symmetric)
528 529 530 531 532 533 534
    $sql = 'SELECT b.uid, u.name FROM {buddylist} b INNER JOIN {users} u ON b.uid = u.uid WHERE b.buddy = %d ORDER BY u.access DESC';
    $result = db_query_range($sql, $user->uid, 0, variable_get('buddylist_prof_buddies', 5));
    while ($row = db_fetch_object($result)) {
      $listbuddyof[$row->uid] = $row;
    }
    if ($listbuddyof) {
      return theme('user_list', $listbuddyof);
robertDouglass's avatar
robertDouglass committed
535 536
    }
  }
537
}
robertDouglass's avatar
robertDouglass committed
538

539

540 541
/*
 * Returns an array of posible actions (html) for the viewing user,
542
 * e.g. a link to make the viewed user a buddy
543 544 545 546 547 548
 */
function buddylist_get_buddy_actions(&$viewing_user, &$viewed_user) {

  $actions = array();
  if (!user_access('maintain buddy list') || $viewing_user->uid == $viewed_user->uid) {
    return $actions;
robertDouglass's avatar
robertDouglass committed
549
  }
550 551

  if (variable_get('buddylist_require_approval', FALSE) && in_array($viewed_user->uid, array_keys(buddylist_get_requestees($viewing_user->uid)))) {
552
    $actions[] = t('You have requested to add this user to your @buddylist. (See !your_pending_requests)', array('!your_pending_requests' => l(t('your pending requests'), 'buddylist/'. $viewing_user->uid .'/buddies/requests')) + buddylist_translation());
553 554 555 556 557 558 559 560 561 562 563 564 565
  }
  else if (in_array($viewed_user->uid, array_keys(buddylist_get_buddies($viewing_user->uid)))) {
    $actions[] = theme('remove_from_buddylist_link', $viewed_user);
  }
  else if (in_array($viewing_user->uid, array_keys(buddylist_get_requestees($viewed_user->uid)))) {
    $actions[] = t('This user has requested to add you to your @buddylist.', buddylist_translation()) .
                 drupal_get_form('buddylist_approval_form', $viewing_user->uid, $viewed_user->uid);
  }
  else {
    $actions[] = theme('add_to_buddylist_link', $viewed_user);
  }

  return $actions;
robertDouglass's avatar
robertDouglass committed
566 567 568 569 570 571 572 573 574 575 576 577
}


/**
 * Implementation for hook_block
 */
function buddylist_block($op = 'list', $delta = 0) {
  global $user;

  if ($op == 'list') {
    $block[0]['info'] = variable_get('buddylist_list_block_title', t('My @buddy list', buddylist_translation()));
    $block[1]['info'] = variable_get('buddylist_block_title', t('My @buddies\' recent posts', buddylist_translation()));
578 579 580
    if (variable_get('buddylist_require_approval', 0)) {
      $block[2]['info'] = variable_get('buddylist_status_block_title', t('My @buddy status', buddylist_translation()));
    }
robertDouglass's avatar
robertDouglass committed
581 582
    return $block;
  }
583
  else if ($op == 'view' && user_access('access content') && user_access('maintain buddy list') && $user->uid > 0) {
robertDouglass's avatar
robertDouglass committed
584 585 586
    switch ($delta) {
      case 0 : // Shows buddylist block
        if ($buddies = buddylist_get_buddies()) {
587
          // we have buddies defined and generate the list
robertDouglass's avatar
robertDouglass committed
588 589 590 591 592 593 594 595 596
          $i = 0;
          foreach (array_keys($buddies) as $buddy) {
            $users[] = user_load(array('uid' => $buddy));
            $i++;
            if ($i == variable_get('buddylist_blocklisting_size', 5)) {
              break;
            }
          }
          $block['content'] = theme('user_list', $users);
597 598 599 600 601 602 603 604 605 606 607 608
        } else {
          // buddylist is empty
          if(variable_get('buddylist_block_if_no_buddies', FALSE)) {
            // Show a message that we have no buddies yet
            $block['content'] = variable_get('buddylist_empty_text', t(buddylist_empty_text_default(), buddylist_translation()));
          } else {
            // If no buddies defined and no message available, end 'case' without returning block.
            break;
          }
        }
        // this is the same output whether buddylist or not
        $block['subject'] = variable_get('buddylist_list_block_title', t('My @buddy list', buddylist_translation()));
robertDouglass's avatar
robertDouglass committed
609

610 611
        // check if a "more" link should generated by seeing if there are more buddies than the specified $upperlimit
        if (count($buddies) > variable_get('buddylist_blocklisting_size', 5)) {
robertDouglass's avatar
robertDouglass committed
612 613
            $block['content'] .=  '<div class="more-link">' . l(t('more'), 'buddylist', array('title' => t('View more.'))) . '</div>';
        }
614 615
        return $block;
      break;
robertDouglass's avatar
robertDouglass committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

      case 1: // Shows my buddies recent posts block
        $buddies = buddylist_get_buddies();
        $keys = array_keys($buddies);
        if (count($keys) > 0) {
          $str_buddies = implode(',', $keys);
          $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.status, n.type, u.uid, u.name, n.created, n.title FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE n.status = 1 AND n.uid IN ($str_buddies) ORDER BY n.nid DESC"), 0, variable_get('buddylist_posts_block', 7));

          if (db_num_rows($result)) {
            $block['subject'] = variable_get('buddylist_block_title', t('My @buddies\' recent posts', buddylist_translation()));
            $block['content'] = node_title_list($result);

            // check if a "more" link should generated by seeing if there are more buddies than the specified $upperlimit
            $result = db_query(db_rewrite_sql('SELECT COUNT(n.nid) AS node_count FROM {buddylist} b LEFT JOIN {node} n ON n.uid=b.buddy LEFT JOIN {users} u ON n.uid = u.uid WHERE n.status = 1 AND b.uid=%d'), $user->uid);
            $countresult = db_fetch_object($result);

            if (variable_get('buddylist_posts_block', 7) < $countresult->node_count) {
              $block['content'] .= '<div class="more-link">'. l(t('more'), 'buddylist/'. $user->uid .'/buddies/recent', array('title' => t('View more.'))) .'</div>';
            }
            return $block;
          }
        }
        break;
639

640 641 642 643 644 645
        case 2: // Buddylist status
          $block['subject'] = variable_get('buddylist_status_block_title', t('My @buddy status', buddylist_translation()));

          $count = db_result(db_query("SELECT COUNT(uid) FROM {buddylist} WHERE uid = %d", $user->uid));
          $sent = db_result(db_query("SELECT COUNT(requester_uid) FROM {buddylist_pending_requests} WHERE requester_uid = %d", $user->uid));
          $received = db_result(db_query("SELECT COUNT(requestee_uid) FROM {buddylist_pending_requests} WHERE requestee_uid = %d", $user->uid));
646

647 648 649
          $block['content'] = theme('buddylist_status_block', $count, $received, $sent);
          return $block;
        break;
robertDouglass's avatar
robertDouglass committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    }
  }
}

/**
 * Public API for retrieving buddies. Feel free to use this from other
 * modules.
 * $key can be 'uid' or 'label'.
*/
function buddylist_get_buddies($uid = NULL, $key = 'uid') {
  static $buddies;

  if (!$uid) {
    global $user;
    $uid = $user->uid;
  }
  if (!isset($buddies[$key][$uid])) {
    $buddies[$key][$uid] = array();
668
    $sql = 'SELECT b.buddy, u.name, u.mail, u.uid FROM {buddylist} b
robertDouglass's avatar
robertDouglass committed
669 670 671 672
            INNER JOIN {users} u ON b.buddy = u.uid
            WHERE b.uid = %d';
    $result = db_query($sql, $uid);
    while ($row = db_fetch_object($result)) {
673
      $buddies[$key][$uid][$row->buddy]['uid'] = $row->uid;
robertDouglass's avatar
robertDouglass committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      $buddies[$key][$uid][$row->buddy]['name'] = $row->name;
      $buddies[$key][$uid][$row->buddy]['mail'] = $row->mail;
      $buddies[$key][$uid][$row->buddy]['groups'] = buddylist_get_buddy_groups($uid, $row->buddy);
      $buddies[$key][$uid][$row->buddy]['online'] = 0;
      $selectlist .= $row->buddy.",";
    }
    // Add the online flag
    if (db_num_rows($result)) {
      $sql = 'SELECT uid FROM {sessions} WHERE uid IN (%s) AND timestamp > %d';
      $result = db_query($sql, substr($selectlist,0,-1), time()-1800);
      while ($row = db_fetch_object($result)) {
        $buddies[$key][$uid][$row->uid]['online'] = 1;
      }
    }
  }

  return $buddies[$key][$uid];
}

693 694 695
/**
 * Returns an array of uid => name of people that user with param $uid has made a buddy request to
 */
696 697
function buddylist_get_requestees($uid) {
  $buddies = array();
698

699
  $result = db_query('SELECT bpr.requestee_uid, u.name FROM {buddylist_pending_requests} bpr INNER JOIN {users} u ON bpr.requestee_uid = u.uid WHERE requester_uid = %d', $uid);
700

701 702 703
  while ($row = db_fetch_object($result)) {
    $buddies[$row->requestee_uid] = $row->name;
  }
704

705 706 707
  return $buddies;
}

robertDouglass's avatar
robertDouglass committed
708 709 710
function buddylist_setmsg_received($thisuser) {
  global $user;

711 712
  if (variable_get('buddylist_require_approval', 0)) {
    // Go through and find new buddylist add-requests, (i.e., the ones in {buddylist_pending_requests} w/ received column == 0
713
    $result = db_query('SELECT bpr.requester_uid as uid, u.name FROM {buddylist_pending_requests} bpr INNER JOIN {users} u ON bpr.requester_uid = u.uid WHERE bpr.requestee_uid = %d AND bpr.received = 0', $user->uid);
714 715
    $acknowledged_uids = array();
    while ($row = db_fetch_object($result)) {
716 717
      drupal_set_message(t('!linktouser has requested to add you to his/her @buddylist.  Please view your !pending_buddy_requests to approve/deny.', array('!linktouser' => theme('username', $row), '!pending_buddy_requests' => l(t('pending buddy requests'), 'buddylist/'. $user->uid .'/buddies/requests')) + buddylist_translation()));
      $acknowledged_uids[] = $row->uid;
718 719 720 721 722 723 724 725 726 727
    }
    if (count($acknowledged_uids)) {
      db_query('UPDATE {buddylist_pending_requests} SET received = 1 WHERE requestee_uid = %d AND requester_uid IN (%s)', $user->uid, implode(',', $acknowledged_uids));
    }
  }
  else {
    $check_received = db_query('SELECT received, b.uid as uid, u.name FROM {buddylist} b LEFT JOIN {users} u ON u.uid = b.uid WHERE buddy = %d AND received = 1', $thisuser->uid);
    while ($rec = db_fetch_object($check_received)) {
      if (($rec->received) and ($thisuser->uid == $user->uid)) {
        // TODO: This is where integration with Privatemsg could happen. If enabled, send a private message instead.
728
        drupal_set_message(t('!linktouser has added you to his/her @buddylist.', array('!linktouser' => theme('username', $rec)) + buddylist_translation()));
729 730
        db_query('UPDATE {buddylist} SET received = 0 WHERE buddy = %d', $user->uid);
      }
robertDouglass's avatar
robertDouglass committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    }
  }
}

/**
 * expose add and remove links to theming.
 */
function theme_remove_from_buddylist_link($buddyuser) {
  return l(t('Remove %name from my @buddy list', array('%name' => $buddyuser->name) + buddylist_translation()), 'buddy/delete/' . $buddyuser->uid, NULL, drupal_get_destination(), NULL, FALSE, TRUE);
}

function theme_add_to_buddylist_link($buddyuser) {
  return l(t('Add %name to my @buddy list', array('%name' => $buddyuser->name) + buddylist_translation()), 'buddy/add/' . $buddyuser->uid, NULL, drupal_get_destination(), NULL, FALSE, TRUE);
}

746 747 748 749 750 751 752 753 754 755 756
function theme_buddylist_accept_request_link($requestee_uid, $requester_uid) {
  return l(t('Accept'), 'buddylist/' . $requestee_uid . '/buddies/requested/accept/' . $requester_uid, array('title' => 'Accept'), drupal_get_destination(), NULL, FALSE, TRUE);
}

function theme_buddylist_deny_request_link($requestee_uid, $requester_uid) {
  return l(t('Deny'), 'buddylist/' . $requestee_uid . '/buddies/requested/deny/' . $requester_uid, array('title' => 'Deny'), drupal_get_destination(), NULL, FALSE, TRUE);
}

function theme_buddylist_sent_requests_cancel_link($requestee_uid, $requester_uid) {
  return l(t('Cancel'), 'buddylist/' . $requestee_uid . '/buddies/request/cancel/' . $requester_uid, array('title' => 'Cancel'), drupal_get_destination(), NULL, FALSE, TRUE);
}
robertDouglass's avatar
robertDouglass committed
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

/**
 * Displays a list of a given user's buddies.
 */
function buddylist_buddylisting_page($uid = NULL, $mode = 'buddies') {
  global $user;

  if (empty($uid)) {
    $uid = $user->uid;
  }
  // Check that the uid is valid, not the anonymous user, and the user exists
  if (!(is_numeric($uid) && ($uid > 0) && $thisuser = user_load(array('uid' => $uid)))) {
    drupal_not_found();
    exit();
  }

  drupal_set_title(t('%username\'s @buddylist', array('%username' => $thisuser->name) + buddylist_translation()));

  $buddies_per_page = 20;

  //TODO: use the get_buddies function instead
  if ($mode == 'buddies') {
    $sql = "SELECT DISTINCT(b.buddy), u.access FROM {buddylist} b INNER JOIN {users} u ON b.buddy = u.uid WHERE b.uid = %d ORDER BY u.access DESC";
  }
  else {
    $sql = "SELECT DISTINCT(u.uid) as buddy, u.access FROM {buddylist} b INNER JOIN {users} u ON b.uid = u.uid WHERE b.buddy = %d ORDER BY u.access DESC";
  }
  $result = pager_query($sql, $buddies_per_page, 0 , NULL, $uid);

  $header = array(t('@buddy', buddylist_translation()), t('online'));
  $online_interval = time() - variable_get('user_block_seconds_online', 180);

  if (db_num_rows($result)) {
    while ($account = db_fetch_object($result)) {
      $online = $account->access > $online_interval;
      $rows[] = array(theme('username', user_load(array('uid' => $account->buddy))), theme('buddylist_online', $online));
    }
    $output .= theme('table', $header, $rows);
  }
  else {
797
    $output .= variable_get('buddylist_empty_text', t(buddylist_empty_text_default(), buddylist_translation()));
robertDouglass's avatar
robertDouglass committed
798 799 800 801 802 803 804
  }

  $output .= theme('pager', NULL, $buddies_per_page);

  return $output;
}

805 806 807 808 809 810 811 812 813
/**
 * Returns a list of people who've requested to be added to the given user's buddylist
 * and a list of people who this given user has requested to be buddies with.
 */
function theme_buddylist_pending_requests($id) {

  $thisuser = user_load(array('uid' => $id));
  drupal_set_title(t('@username\'s @buddylist', array('@username' => $thisuser->name) + buddylist_translation()));

814
  return theme('box', t('Received requests'), buddylist_pending_requester_list($thisuser)) .
815 816
         theme('box', t('Sent requests'), buddylist_pending_requested_list($thisuser));
}
817 818

/**
819
 * Returns a list of people who've requested to be added to the given user's buddylist
820
 */
821
function buddylist_pending_requester_list(&$account) {
822
  global $user;
823

824 825
  $viewing_own_account = ($user->uid == $account->uid);
  $result = db_query('SELECT bpr.requester_uid as uid, u.name FROM {buddylist_pending_requests} bpr INNER JOIN {users} u ON bpr.requester_uid = u.uid WHERE requestee_uid = %d', $account->uid);
826

827 828 829 830 831
  if (!db_num_rows($result)) {
    $output = '<p>'. t("!someone currently !does_or_do not have any pending @buddy requests from other users.", array('!someone' => ($viewing_own_account ? t('You') : $account->name), '!does_or_do' => $viewing_own_account ? t('do') : t('does')) + buddylist_translation()) .'</p>';
  }
  else {
    $output = '<p>'. t("The following people have requested to be !someones @buddy.", array('!someones' => ($viewing_own_account ? t('your') : $account->name ."'s ")) + buddylist_translation()) .'</p>';
832

833 834 835
    $html_rows = array();
    while ($row = db_fetch_object($result)) {
      $html_row = array();
836
      $html_row[] = theme('username', $row);
837
      $html_row[] = theme('buddylist_accept_request_link', $account->uid, $row->uid) . " | " . theme('buddylist_deny_request_link', $account->uid, $row->uid);
838 839
      $html_rows[] = $html_row;
    }
840

841 842
    $output .= theme('table', NULL, $html_rows);
  }
843

844 845 846
  return $output;
}

847 848 849 850 851
/**
 * Returns a list of user's who this given user has requested to be buddies with.
 */
function buddylist_pending_requested_list(&$account) {
  global $user;
852

853 854
  $viewing_own_account = ($user->uid == $account->uid);
  $result = db_query('SELECT bpr.requestee_uid as uid, u.name FROM {buddylist_pending_requests} bpr INNER JOIN {users} u ON bpr.requestee_uid = u.uid WHERE requester_uid = %d', $account->uid);
855

856
  if (!db_num_rows($result)) {
857
    $output = t('!Person !do_or_does not have any pending @buddy requests that !person !have_or_has made.',
858
                array(
859 860 861
                  '!Person' => ($viewing_own_account ? t('You') : $account->name),
                  '!do_or_does' => ($viewing_own_account ? t('do') : t('does')),
                  '!have_or_has' => ($viewing_own_account ? t('have') : t('has')),
862 863 864 865
                  '!person' => ($viewing_own_account ? t('you') : $account->name) ) + buddylist_translation());
  }
  else {
    $output = t('!person !have_or_has requested to be added to the @buddylist of the following users.', array('!person' => ($viewing_own_account ? t('You') : $account->name), '!have_or_has' => ($viewing_own_account ? t('have') : t('has'))) + buddylist_translation());
866

867 868 869 870
    $html_rows = array();
    while ($row = db_fetch_object($result)) {
      $html_row = array();
      $html_row[] = theme('username', $row);
871
      $html_row[] = theme('buddylist_sent_requests_cancel_link', $account->uid, $row->uid);
872 873
      $html_rows[] = $html_row;
    }
874

875 876 877 878 879 880
    $output .= theme('table', NULL, $html_rows);
  }

  return $output;
}

881 882 883 884 885 886 887 888 889 890 891 892 893
function buddylist_pending_requested_accept($requestee_uid, $requester_uid) {
  $requestee_account = user_load(array('uid' => $requestee_uid));
  $requester_account = user_load(array('uid' => $requester_uid));
  $output = confirm_form(
    buddylist_confirm_form($requester_account, $requestee_account),
    t('Accept Request'),
    'buddylist/'.$requestee_uid.'/buddies/requests',
    t("Are you sure you want to accept the request from !name?", array('!name' => theme('username', $requester_account))),
    t('Yes'), t('No'),
    'buddylist_request_accept_confirm');
    
  return $output;
}
894

895 896 897 898 899 900 901 902 903 904 905 906
function buddylist_cancel_request($requestee_uid, $requester_uid){
  $requestee_account = user_load(array('uid' => $requestee_uid));
  $requester_account = user_load(array('uid' => $requester_uid));
  $output = confirm_form(
    buddylist_request_cancel_form($requestee_uid, $requester_uid),
    t('Cancel Request'),
    'buddylist/'.$requestee_uid.'/buddies/requests',
    t("Are you sure you want to cancel the request to !name?", array('!name' => theme('username', $requester_account))),
    t('Yes'), t('No'),
    'buddylist_cancel_request_confirm');
    
  return $output;
907

908
}
909

910 911
function buddylist_cancel_request_submit($form_id, $form_values){
	  db_query('DELETE FROM {buddylist_pending_requests} WHERE requestee_uid = %d AND requester_uid = %d', $form_values['requester_uid'], $form_values['requestee_uid']);
912

913 914
      $former_potential_buddy = user_load(array('uid' => $form_values['requester_uid']));
      drupal_set_message(t('The request to add !user_name has been cancelled.', array('!user_name' => theme('username', $former_potential_buddy))));
915

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
      return 'buddylist/'. $form_values['requester_uid'] .'/buddies/requests';
}

function buddylist_pending_requested_deny($requestee_uid, $requester_uid) {
  $requestee_account = user_load(array('uid' => $requestee_uid));
  $requester_account = user_load(array('uid' => $requester_uid));
  $output = confirm_form(
    buddylist_confirm_form($requester_account, $requestee_account),
    t('Accept Request'),
    'buddylist/'.$requestee_uid.'/buddies/requests',
    t("Are you sure you want to deny the request from !name?", array('!name' => theme('username', $requester_account))),
    t('Yes'), t('No'),
    'buddylist_request_deny_confirm');
    
  return $output;
}

function buddylist_pending_requested_accept_submit($form_id, $form_values) {
  $requestee_account = $form_values['requestee_account']; // most likely global user, unless admin looking
  $requester_account = $form_values['requester_account'];

  // Delete pending request from {buddylist_penging_requests}
  $result = db_query('SELECT * FROM {buddylist_pending_requests} WHERE requestee_uid = %d AND requester_uid = %d', $requestee_account->uid, $requester_account->uid);

  if (db_num_rows($result) == 0) {
    // The other user cancelled since viewing this page
    drupal_set_message(t('!linktouser has cancelled the request to join your @buddylist.', array('!linktouser' => theme('username', $requester_account)) + buddylist_translation()));      
    return  'buddylist/'. $requestee_account->uid .'/buddies/requests';
  }
  
  db_query('DELETE FROM {buddylist_pending_requests} WHERE requestee_uid = %d AND requester_uid = %d', $requestee_account->uid, $requester_account->uid);
  
  // Make sure, for some weird reason, we don't already have these guys marked as buddies of each other in the database
  $result = db_query('SELECT * FROM {buddylist} WHERE uid = %d AND buddy = %d', $requestee_account->uid, $requester_account->uid);
  
  $time = time();
  
  if (!db_num_rows($result)) {
    db_query('INSERT INTO {buddylist} (uid, buddy, timestamp, received) VALUES (%d, %d, %d, %d)', $requestee_account->uid, $requester_account->uid, $time, 1);
  }
  
  $result = db_query('SELECT * FROM {buddylist} WHERE uid = %d AND buddy = %d', $requester_account->uid, $requestee_account->uid);
  if (!db_num_rows($result)) {
    db_query('INSERT INTO {buddylist} (uid, buddy, timestamp, received) VALUES (%d, %d, %d, %d)', $requester_account->uid, $requestee_account->uid, $time, 1);
  }
  
  if (variable_get('buddylist_send_approval', FALSE)) {
    buddylist_mail_user('approval', $requester_account, $requestee_account);
  }

  drupal_set_message(t('Congratulations! !linktouser is now your buddy.', array('!linktouser' => theme('username', $requester_account)) + buddylist_translation()));      
  
  return  'buddylist/'. $requestee_account->uid .'/buddies/requests';
}

function buddylist_pending_requested_deny_submit($form_id, $form_values) {
  $requestee_account = $form_values['requestee_account']; // most likely global user, unless admin looking
  $requester_account = $form_values['requester_account'];
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
  // Delete pending request from {buddylist_penging_requests}
  db_query('DELETE FROM {buddylist_pending_requests} WHERE requestee_uid = %d AND requester_uid = %d', $requestee_account->uid, $requester_account->uid);
 
  drupal_set_message(t("!user's request to be your buddy has been denied.", array('!user' => theme('username', $requester_account)) + buddylist_translation()));
  
  return  'buddylist/'. $requestee_account->uid .'/buddies/requests';
}

function buddylist_confirm_form($requester_account, $requestee_account) {
  $form = array();
  
  $form['requester_account'] = array(
    '#type' => 'value',
    '#value' => $requester_account
  );
  
  $form['requestee_account'] = array(
  	'#type' => 'value',
  	'#value' => $requestee_account
  );
  
996 997 998
  return $form;
}

999
function buddylist_confirm_form_submit($form_id, $form_values) {
1000
  $requestee_account = user_load(array('uid' => $form_values['requestee_uid'])); // most likely global user, unless admin looking
1001 1002
 
  
1003 1004
  // Delete pending request from {buddylist_penging_requests}
  db_query('DELETE FROM {buddylist_pending_requests} WHERE requestee_uid = %d AND requester_uid = %d', $form_values['requestee_uid'], $form_values['requester_uid']);
1005

1006
  $requester_account = user_load(array('uid' => $form_values['requester_uid']));
1007

1008 1009 1010
  if ($form_values['op'] == t('Approve')) {
    // Make sure, for some weird reason, we don't already have these guys marked as buddies of each other in the database
    $result = db_query('SELECT * FROM {buddylist} WHERE uid = %d AND buddy = %d', $form_values['requestee_uid'], $form_values['reqeuster_uid']);
1011

1012
    $time = time();
1013

1014 1015 1016
    if (!db_num_rows($result)) {
      db_query('INSERT INTO {buddylist} (uid, buddy, timestamp, received) VALUES (%d, %d, %d, %d)', $form_values['requestee_uid'], $form_values['requester_uid'], $time, 1);
    }
1017

1018 1019 1020 1021
    $result = db_query('SELECT * FROM {buddylist} WHERE uid = %d AND buddy = %d', $form_values['requester_uid'], $form_values['requestee_uid']);
    if (!db_num_rows($result)) {
      db_query('INSERT INTO {buddylist} (uid, buddy, timestamp, received) VALUES (%d, %d, %d, %d)', $form_values['requester_uid'], $form_values['requestee_uid'], $time, 1);
    }
1022

1023 1024 1025 1026
    if (variable_get('buddylist_send_approval', FALSE)) {
      buddylist_mail_user('approval', $requester_account, $requestee_account);
    }

1027
    drupal_set_message(t('Congratulations! !linktouser is now your @buddy.', array('!linktouser' => theme('username', $requester_account)) + buddylist_translation()));
1028 1029
  }
  else {
1030
    drupal_set_message(t("!user's request to be your @buddy has been denied.", array('!user' => theme('username', $requester_account)) + buddylist_translation()));
1031 1032 1033
  }
}

1034 1035 1036
function buddylist_approval_form($requestee_uid, $requester_uid) {
  $form = array();

1037 1038 1039 1040
  $form['requestee_uid'] = array(
    '#type' => 'hidden',
    '#value' => $requestee_uid,
  );
1041

1042 1043 1044 1045
  $form['requester_uid'] = array(
    '#type' => 'hidden',
    '#value' => $requester_uid
  );
1046

1047 1048 1049 1050 1051 1052
  $form['approve'] = array(
    '#type' => 'submit',
    '#value' => t('Approve')
  );

  $form['deny'] = array(
1053
    '#type' => 'submit',
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    '#value' => t('Deny'),
  );

  return $form;
}

function buddylist_request_cancel_form($requestee_uid, $requester_uid) {
  $form['requestee_uid'] = array(
    '#type' => 'hidden',
    '#value' => $requestee_uid,
  );

  $form['requester_uid'] = array(
    '#type' => 'hidden',
    '#value' => $requester_uid
1069
  );
1070

1071 1072 1073 1074 1075
  return $form;
}

function buddylist_request_cancel_form_submit($form_id, $form_values) {
  db_query('DELETE FROM {buddylist_pending_requests} WHERE requester_uid = %d AND requestee_uid = %d', $form_values['requester_uid'], $form_values['requestee_uid']);
1076

1077
  $former_potential_buddy = user_load(array('uid' => $form_values['requestee_uid']));
1078
  drupal_set_message(t('The request to add !user_name has been cancelled.', array('!user_name' => theme('username', $former_potential_buddy))));
1079

1080
  return 'buddylist/'. $form_values['requester_uid'] .'/buddies/requests';
1081 1082
}

robertDouglass's avatar
robertDouglass committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
function buddylist_form_buddiesrecent_page($buddies) {
  foreach ($buddies as $user_id => $buddy) {
    $form[] = array('#type' => 'fieldset',
      '#title' => $buddy['name'],
      '#collapsible' => 'true',
      '#value' => tracker_page($user_id),
    );
  }
  return $form;
}

function buddylist_buddiesrecent_page($uid) {
  global $user;

  $thisuser = user_load(array('uid' => $uid));
  drupal_set_title(t('%username\'s @buddylist', array('%username' => $thisuser->name) + buddylist_translation()));

  $buddies = buddylist_get_buddies($uid);
  $output .= drupal_get_form('buddylist_form_buddiesrecent_page', $buddies);
  $output .= theme('xml_icon', url('buddylist/'. $uid .'/buddies/recent/feed'));
  drupal_set_html_head('<link rel="alternate" type="application/rss+xml" title="'. t('RSS - @buddies posts', buddylist_translation()). '" href="'. url('buddylist/'. $user->uid .'/buddies/recent/feed') .'" />');

  return $output;
}

function buddylist_buddiesgroups_page($uid) {
  global $user;
  $thisuser = user_load(array('uid' => $uid));
  drupal_set_title(t('%username\'s @buddy groups', array('%username' => $thisuser->name) + buddylist_translation()));

  $headers = array(t('@buddy', buddylist_translation()), t('online'), t('# of @buddies', buddylist_translation()), t("@buddy's posts", buddylist_translation()));

1115
  $result = db_query('SELECT label, label_id FROM {buddylist_groups} WHERE uid = %d ORDER BY label ASC', $thisuser->uid);
robertDouglass's avatar
robertDouglass committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  $groups = array();
  while ($row = db_fetch_object($result)) {
    $groups[$row->label_id] = $row->label;
  }

  if (count($groups) == 0) {
    if ($thisuser->uid == $user->uid) {
      drupal_set_message(
        t("To organize your @buddies into groups, visit the !edit_groups page",
          array('!edit_groups' =>
                l(t('edit groups'), "buddylist/$uid/buddies/groups/edit")) + buddylist_translation())
      );
    }
    return t('No groups found.');
  }

  $online_interval = time() - variable_get('user_block_seconds_online', 180);
  $buddies = buddylist_get_buddies($thisuser->uid);

  foreach ($groups as $label_id => $label) {
    $result = pager_query('SELECT bg.buddy, u.access FROM {buddylist_buddy_group} bg INNER JOIN {users} u ON bg.buddy = u.uid WHERE bg.uid = %d and bg.label_id = %d', 10, 0, NULL, $thisuser->uid, $label_id);
    $rows = array();
    while ($row = db_fetch_object($result)) {
      $online = $row->access > $online_interval;
      $rows[] = array(
1141
        theme('username', (object)$buddies[$row->buddy]),
robertDouglass's avatar
robertDouglass committed
1142 1143 1144 1145 1146
        theme('buddylist_online', $online),
        buddylist_count_buddies($row->buddy),
        l(t('view posts'), 'user/'. $row->buddy. '/track')
      );
    }
1147
    $output .= theme('box', check_plain($label), $rows ? theme('table', $headers, $rows) : t('Group is empty.'));
robertDouglass's avatar
robertDouglass committed
1148
  }
1149
  return $output;
robertDouglass's avatar
robertDouglass committed
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
}

function buddylist_count_buddies($uid) {
  $result = db_query("SELECT count(DISTINCT buddy) AS buddies FROM {buddylist} WHERE uid = %d", $uid);
  return db_result($result);
}


function buddylist_get_buddy_groups($uid, $buddy = NULL) {
  if (isset($buddy)) {
1160 1161 1162
    $result = db_query("SELECT bg.label_id, bg.label, bg.visible FROM {buddylist_groups} bg INNER JOIN {buddylist_buddy_group} bbg ON bbg.uid = bg.uid WHERE bbg.uid = %d AND bg.label_id = bbg.label_id AND bbg.buddy = %d ", $uid, $buddy);
  }
  else {
1163
    $result = db_query("SELECT * FROM {buddylist_groups} WHERE uid=%d", $uid);
robertDouglass's avatar
robertDouglass committed
1164 1165 1166
  }
  $buddy_groups = array();
  while ($row = db_fetch_array($result)) {
1167
    $buddy_groups[$row['label_id']] = $buddy ? $row : $row['label'];
robertDouglass's avatar
robertDouglass committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  }
  return $buddy_groups;
}


function buddylist_form_edit_groups_add() {
  // Add group form
  $form['add_group'] = array(
    '#type' => 'textfield',
    '#title' => t('Add new group'),
    '#description' => t('Groups are a way to keep your @buddies organized. Groups can be named whatever you like.', buddylist_translation()),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
  );

  return $form;
}

function buddylist_form_edit_groups_remove($all_groups) {
  // Make a form to remove groups
  $form['remove']['groups'] = array(
    '#type' => 'checkboxes',
    '#return_value' => 1,
    '#title' => '',
    '#default_value' => null,
1196
    '#options' => array_map('check_plain', $all_groups),
robertDouglass's avatar
robertDouglass committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
  );

  $form['remove']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Remove'),
  );

  return $form;
}

function buddylist_form_edit_groups_table($buddies, $all_groups, $thisuser) {
  // Build the table with buddies and their groups
  $form['table']['groups'] = array ('#tree' => true);
  foreach ($buddies as $uid => $buddy) {
    $items = array();
    foreach ($buddy['groups'] as $group) {
      $items[] = $group['label_id'];
    }

    if (count($all_groups) > 0) {
      $form['table']['groups'][$uid] = array(
        '#type' => 'checkboxes',
        '#title' => '',
        '#default_value' => $items,
1221
        '#options' => array_map('check_plain', $all_groups),
robertDouglass's avatar
robertDouglass committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
      );
    }
  }

  $form['table']['user'] = array(
    '#type' => 'value',
    '#value' => $thisuser->uid,
  );

  if (count($form['table']['groups']) > 0) {
    $form['table']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
  }

  return $form;
}

/**
 * Callback for the buddygroup editing page
 */
function buddylist_buddiesgroups_edit($uid) {
  $thisuser = user_load(array('uid' => $uid));
  drupal_set_title(t('%username\'s @buddy groups', array('%username' => $thisuser->name) + buddylist_translation()));

  if ($buddies = buddylist_get_buddies($thisuser->uid)) {
    $output['add'] = drupal_get_form('buddylist_form_edit_groups_add');

1251
    $groups = buddylist_get_buddy_groups($uid);
robertDouglass's avatar
robertDouglass committed
1252

1253 1254 1255
    if (count($groups) > 0) {
      $output['remove'] = drupal_get_form('buddylist_form_edit_groups_remove', $groups);
      $output['table'] = drupal_get_form('buddylist_form_edit_groups_table', $buddies, $groups, $thisuser);
robertDouglass's avatar
robertDouglass committed
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    }
    else {
      drupal_set_message(t("You don't have any groups defined."));
    }

    return theme('buddylist_edit_groups', $output);
  }
  else {
    drupal_set_message(t('Unable to edit @buddy groups. Add @buddies to your @buddylist before making groups.', buddylist_translation()));
    return t('No @buddies found.', buddylist_translation());
  }
}

function theme_buddylist_edit_groups($forms) {
 $output = '<span id="buddylist-group-add-form">'.
              $forms['add'].
            '</span>'.
            '<span id="buddylist-group-remove-form">'.
              $forms['remove'].
            '</span>'.
            '<span id="buddlist-groups-form">'.
              $forms['table'].
            '</span>';
  return $output;
}

function theme_buddylist_form_edit_groups_table($form) {
  $rows = array();

  foreach ($form['table']['groups'] as $key => $value) {
    if(is_numeric($key)) {
      $rows[] = array(theme('username', user_load(array('uid' => $key))), drupal_render($form['table']['groups'][$key]));
    }
  }

  $headers = array(t('buddy'), t('@buddy groups', buddylist_translation()));
  $output .= theme('table', $headers, $rows);

  $output .= drupal_render($form);

  return $output;
}

1299 1300 1301 1302 1303 1304
function theme_buddylist_status_block($count, $received_count, $sent_count) {
  global $user;

  $stats .= "<div class='buddylist-status'>";
  $stats .= "<div class='total'>" . l(format_plural($count, '@count buddy', '@count buddies'), 'buddylist') . "</div>";
  $stats .= "<div class='pending_received'>" . l(format_plural($received_count, '@count pending received request', '@count pending received requests'), 'buddylist/'. $user->uid .'/buddies/requests') . "</div>";
1305
  $stats .= "<div class='pending_sent'>" . l(format_plural($sent_count, '@count pending sent request', '@count pending sent requests'), 'buddylist/'. $user->uid .'/buddies/requests') . "</div>";
1306 1307 1308 1309 1310
  $stats .= "</div>";

  return $stats;
}

robertDouglass's avatar
robertDouglass committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
function buddylist_form_edit_groups_add_submit($form_id, $form_values) {
  global $user;
  $label_id = buddylist_buddygroup_new($user->uid, $form_values['add_group']);
}

function buddylist_form_edit_groups_remove_submit($form_id, $form_values) {
  global $user;
  foreach ($form_values['groups'] as $label_id => $remove) {
    if ($remove > 0) {
      buddylist_buddygroup_remove($user->uid, $label_id);
    }
  }
}

function buddylist_form_edit_groups_table_submit($form_id, $form_values) {
  $userid = $form_values['user'];
  foreach ($form_values['groups'] as $buddy => $groups) {
    foreach ($groups as $label_id => $checked) {
      if ($checked == 0) {
        buddylist_buddygroup_remove_buddy($userid, $buddy, $label_id);
      }
      else {
        buddylist_buddygroup_add_buddy($userid, $buddy, $label_id);
      }
    }
  }

  drupal_set_message(t('@buddy groups saved.', buddylist_translation()));
}

/**
 * Creates a new buddy group for a user
 *
 * @param $uid user id of the user to whom the group will belong.
 * @param $group string; name of the group
 * @param $visible determines whether the user's buddies can see which groups they've been put in.
 *
 * @return $label_id the existing or newly created id for the name of this group.
 */
1350
function buddylist_buddygroup_new($uid, $group, $visible = TRUE) {
robertDouglass's avatar
robertDouglass committed
1351
  $label_id = db_result(db_query("SELECT label_id FROM {buddylist_groups} WHERE uid = %d AND label = '%s'", $uid, $group));
1352
  if ($label_id === FALSE) {
robertDouglass's avatar
robertDouglass committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    $new_label_id = db_next_id('buddygroup');
    db_query("INSERT INTO {buddylist_groups} VALUES (%d, %d, '%s', %d)", $uid, $new_label_id, $group, $visible);
    return $new_label_id;
  }
  else {
    return $label_id;
  }
}

/**
 * Removes a buddy group for a user
 *
 * @param $uid user id of the user to whom the group belongs.
 * @param $label_id id of the group
 */
function buddylist_buddygroup_remove($uid, $label_id) {
  db_query("DELETE FROM {buddylist_groups} WHERE uid = %d AND label_id = %d", $uid, $label_id);
  db_query("DELETE FROM {buddylist_buddy_group} WHERE uid = %d AND label_id = %d", $uid, $label_id);
}

function buddylist_buddygroup_remove_buddy($uid, $buddy, $label_id) {
  db_query("DELETE FROM {buddylist_buddy_group} WHERE uid = %d AND buddy = %d AND label_id = %d", $uid, $buddy, $label_id);
}

function buddylist_buddygroup_add_buddy($uid, $buddy, $label_id) {
  db_lock_table('buddylist_buddy_group');
  buddylist_buddygroup_remove_buddy($uid, $buddy, $label_id);
  db_query('INSERT INTO {buddylist_buddy_group} VALUES (%d, %d, %d)', $uid, $buddy, $label_id);
  db_unlock_tables();
}

/**
 * Feed for buddies recent posts
 */
function buddylist_buddyfeed($uid) {
  if (!(is_numeric($uid) && $uid > 0)) {
    return drupal_not_found();
    exit();
  }

  $buddy_ids = array_keys(buddylist_get_buddies($uid));

  // false query to be used if no posts from buddies are available (as in this user has no buddies).
  $result = db_query('SELECT nid FROM {node} WHERE 0');
  if (count($buddy_ids)) {
    $buddy_ids_str = '('. implode(',', $buddy_ids). ')';
    $result = db_query(db_rewrite_sql('SELECT nid FROM {node} WHERE status = 1 AND uid IN %s ORDER BY nid DESC'), $buddy_ids_str);
  }
  $channel['title'] = t('@buddies recent posts on %site', array('%site' => variable_get('site_name', 'drupal')) + buddylist_translation());
  $channel['link'] = url('buddylist/'. $uid .'/buddies/recent', NULL, NULL, TRUE);

  node_feed($result, $channel);
}

function buddylist_addbuddy($uid) {
  global $user;
  $buddy = user_load(array('uid' => $uid));

  if (empty($buddy->name)) {
    drupal_set_message(t('This user does not exist'));
  }
  elseif (in_array($uid, array_keys(buddylist_get_buddies($user->uid)))) {
    drupal_set_message(t('This user is already on your @buddy list', buddylist_translation()));
  }
  elseif ($user->uid == $uid) {
    drupal_set_message(t('Cannot add yourself to @buddy list', buddylist_translation()));
  }
  else {
    $form['uid'] = array('#type' => 'hidden', '#value' => $uid);
    $form['name'] = array('#type' => 'hidden', '#value' => $buddy->name);
    $output = confirm_form(
      $form,
      t('Add user %name to your @buddy list?', array('%name' => $buddy->name) + buddylist_translation()),
      $_GET['destination'],
      '',
      t('Add'), t('Cancel'),
      'buddylist_addbuddy_confirm');
    return $output;
  }
  drupal_goto();
}
//function buddylist_form_alter($a, $b) {dprint_r($a); dprint_r($b);}

/**
 * Confirm and add a buddy.
 */
function buddylist_addbuddy_submit($form_id, $form_values) {
1440 1441 1442 1443 1444 1445 1446
  if (variable_get('buddylist_require_approval', 0)) {
    buddylist_add_request($form_values['uid']);
  }
  else {
    buddylist_add($form_values['uid']);
    drupal_set_message(t('%name will be be notified the next time s/he logs in.', array('%name' => $form_values['name'])));
  }
robertDouglass's avatar
robertDouglass committed
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
  return 'user';
};

/**
 * Removes the user $uid from the global user's account.
 * TODO: generalize this so that two uids can be given
 */
function buddylist_deletebuddy($uid) {
  global $user;
  $buddy = user_load(array('uid' => $uid));

  if (empty($buddy->name)) {
    drupal_set_message('This user does not exist');
  }
  else if (!in_array($uid, array_keys(buddylist_get_buddies($user->uid)))) {
    drupal_set_message('This user is not on your @buddy list', buddylist_translation());
  }
  else {
    $form['uid'] = array('#type' => 'hidden', '#value' => $uid);
    $form['name'] = array('#type' => 'hidden', '#value' => $buddy->name);
    $output = confirm_form(
      $form,
      t('Remove user %name from your @buddy list?', array('%name' => $buddy->name) + buddylist_translation()),
      $_GET['destination'],
      '',
      t('Remove'), t('Cancel'),
      'buddylist_deletebuddy_confirm');
    return $output;
  }
  drupal_goto();
}

/**
 * Confirm and add a buddy.
 */
function buddylist_deletebuddy_submit($form_id, $form_values) {
  buddylist_remove($form_values['uid']);
  drupal_set_message(t('@name will be be notified of being removed.', array('@name' => $form_values['name'])));
  return 'user';
};

function buddylist_add($id) {
  global $user;
  $user_to_add = user_load(array('uid' => $id));

  if (!in_array($id, array_keys(buddylist_get_buddies($user->uid)))) {
    db_query('INSERT INTO {buddylist} (received, uid, buddy, timestamp) VALUES (1, %d, %d, %d)' , $user->uid , $id , time());
    // DB value buddylist.received set to 1, meaning buddy has a message waiting
    // letting them know you added them as a buddy
    // buddylist.received set back to 0 when user logs in along with being informed of new buddy
    if (variable_get('buddylist_send_add', FALSE)) {
      buddylist_mail_user('add', $user_to_add);
    }
    drupal_set_message(t('%username has been added to your @buddy list', array('%username' => $user_to_add->name) + buddylist_translation()));
  }
  else {
    drupal_set_message(t('%username is already on your @buddylist', array('%username' => $user_to_add->name) + buddylist_translation()));
  }
}

1507 1508 1509
function buddylist_add_request($id) {
  global $user;
  $user_to_add = user_load(array('uid' => $id));
1510

1511 1512
  $already_requested = in_array($id, array_keys(buddylist_get_requestees($user->uid)));
  $already_buddies = in_array($id, array_keys(buddylist_get_buddies($user->uid)));
1513

1514 1515
  if (!$already_requested && !$already_buddies) {
    db_query('INSERT INTO {buddylist_pending_requests} (requester_uid, requestee_uid, received) VALUES (%d, %d, %d)', $user->uid, $id, 0);
1516

1517 1518 1519 1520 1521 1522 1523 1524 1525
    if (variable_get('buddylist_send_request', FALSE)) {
      buddylist_mail_user('request', $user_to_add);
    }
    drupal_set_message(t('Your request to add %username to your @buddy list has been submitted.  %username will be notified.', array('%username' => $user_to_add->name) + buddylist_translation()));
  }
  else {
    if ($already_requested) {
      drupal_set_message(t('You have already requested to add %username to your @buddylist', array('%username' => $user_to_add->name) + buddylist_translation()));
    }
1526

1527 1528 1529 1530 1531 1532
    if ($already_buddies) {
      drupal_set_message(t('%username is already on your @buddylist', array('%username' => $user_to_add->name) + buddylist_translation()));
    }
  }
}

robertDouglass's avatar
robertDouglass committed
1533 1534 1535
function buddylist_remove($id) {
  global $user;
  db_query('DELETE FROM {buddylist} WHERE uid = %d AND buddy = %d' , $user->uid , $id);
1536
  db_query('DELETE FROM {buddylist_buddy_group} WHERE uid = %d AND buddy = %d' , $user->uid , $id);
robertDouglass's avatar
robertDouglass committed
1537 1538 1539 1540 1541
  $thisuser = user_load(array('uid' => $id));
  if (variable_get('buddylist_send_remove', FALSE)) {
    buddylist_mail_user('remove', $thisuser);
  }
  drupal_set_message(t('%username has been removed from your @buddylist', array('%username' => $thisuser->name) + buddylist_translation()));
1542

1543 1544
  if (variable_get('buddylist_require_approval', 0)) {
    db_query('DELETE FROM {buddylist} WHERE uid = %d AND buddy = %d', $id, $user->uid);
1545
    db_query('DELETE FROM {buddylist_buddy_group} WHERE uid = %d AND buddy = %d', $id, $user->uid);
1546
  }
robertDouglass's avatar
robertDouglass committed
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
}

function buddylist_cancel_add($id) {
  $thisuser = user_load(array('uid' => $id));
  drupal_set_message(t('User %name was NOT added to your @buddylist.', array('%name' => $thisuser->name) + buddylist_translation()));
}

function buddylist_cancel_remove($id) {
  $thisuser = user_load(array('uid' => $id));
  drupal_set_message(t('User %name was NOT removed from your @buddylist.', array('%name' => $thisuser->name) + buddylist_translation()));
}

function theme_buddylist_online($online) {
  return $online ? t('yes') : t('no');
}

1563 1564 1565 1566
/*
 * Sends mail to a buddy, which is added/removed/deleted/requested by $user
 */
function buddylist_mail_user($op, $buddy, $user = NULL) {
1567 1568 1569 1570 1571

  if (variable_get('buddylist_user_mail', FALSE) && isset($buddy->buddylist_mail) && !$buddy->buddylist_mail) {
    return; //the user has turned mails off
  }

robertDouglass's avatar
robertDouglass committed
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
  if (is_null($user)){
    global $user;
  }
  switch($op) {
    case 'add':
      $subject = BUDDYLIST_ADD_SUBJECT;
      $message = variable_get('buddylist_add_message', buddylist_mail_add_default());
      break;
    case 'remove':
      $subject = BUDDYLIST_REMOVE_SUBJECT;
      $message = variable_get('buddylist_remove_message', buddylist_mail_remove_default());
1583 1584 1585 1586 1587 1588 1589 1590 1591
      break;
    case 'request':
      $subject = BUDDYLIST_REQUEST_SUBJECT;
      $message = variable_get('buddylist_request_message', buddylist_mail_request_default());
      break;
    case 'approval':
      $subject = BUDDYLIST_APPROVAL_SUBJECT;
      $message = variable_get('buddylist_approval_message', buddylist_mail_approval_default());
      break;
robertDouglass's avatar
robertDouglass committed
1592 1593
  }

1594
  $replacements = buddylist_translation() + (($op == 'approval') ? buddylist_approval_mail_replacements($user, $buddy) : buddylist_mail_replacements($buddy, $user));
robertDouglass's avatar
robertDouglass committed
1595 1596 1597 1598 1599
  $subject = t($subject, $replacements);
  $message = t($message, $replacements);

  $site_mail = variable_get('site_mail', "");
  if (!strlen($site_mail)) {
1600 1601
    if (user_access('administer site configuration')){
      drupal_set_message(t('You should create an !link for your site.', array('!link' => l(t('an administrator mail address'), 'admin/settings/site-information'))), 'warning');
robertDouglass's avatar
robertDouglass committed
1602 1603 1604 1605 1606
    }
    $site_mail = 'nobody@localhost';
  }

  // send the email
1607
  if ($op != 'approval') {
1608 1609
    if (drupal_mail("buddylist_mail_user_$op", $buddy->mail, $subject, $message, $site_mail)) {
      $message = t('%type message was sent to %username', array('%type' => $op, '%username' => $buddy->name));
1610 1611 1612
      watchdog('buddylist', $message);
    }
    else {
1613
      $message = t('There was a problem sending the %type message to %username', array('%type' => $op, '%username' => $buddy->name));
1614 1615
      watchdog('buddylist', $message, WATCHDOG_WARNING);
    }
robertDouglass's avatar
robertDouglass committed
1616 1617
  }
  else {
1618 1619
    if (drupal_mail("buddylist_mail_user_$op", $buddy->mail, $subject, $message, $site_mail)) {
      $message = t('%type message was sent to %username', array('%type' => $op, '%username' => $buddy->name));
1620 1621 1622
      watchdog('buddylist', $message);
    }
    else {
1623
      $message = t('There was a problem sending the %type message to %username', array('%type' => $op, '%username' => $buddy->name));
1624
      watchdog('buddylist', $message, WATCHDOG_WARNING);
1625
    }
robertDouglass's avatar
robertDouglass committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  }
}

function buddylist_mail_add_default() {
  return <<<MESSAGE
Hi @addee_name,

You are @adder_name's newest @buddy.

Here's a link to @adder_name's profile. If you'd like, you can add them as one of your @buddies:

  @adder_link

Regards,
The @site team
MESSAGE;
}

function buddylist_mail_remove_default() {
  return <<<MESSAGE
Hi @addee_name,

You have been removed from  @adder_name's  @buddy list.

Here's a link to @adder_name's profile:

  @adder_link

Enjoy your new freedom!

Regards,
The @site team
MESSAGE;
}

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
function buddylist_mail_request_default() {
  return <<<MESSAGE
Hi @addee_name,

@adder_name has requested to add you to his/her @buddy list.

Here's a link to @adder_name's profile:

  @adder_link