Brian Krausz

I build internet things

<?php

include_once $_SERVER['PHP_ROOT'].'/html/init.php';
include_once $_SERVER['PHP_ROOT'].'/lib/mailbox.php';
include_once $_SERVER['PHP_ROOT'].'/lib/profilediff.php';
include_once $_SERVER['PHP_ROOT'].'/lib/notebook.php';
include_once $_SERVER['PHP_ROOT'].'/lib/screenname.php';
include_once $_SERVER['PHP_ROOT'].'/lib/display/profile.php';
include_once $_SERVER['PHP_ROOT'].'/lib/orientation.php';
include_once $_SERVER['PHP_ROOT'].'/lib/feed/minifeed.php';
include_once $_SERVER['PHP_ROOT'].'/lib/elections.php';
include_once $_SERVER['PHP_ROOT'].'/lib/profilediff.php';
include_once $_SERVER['PHP_ROOT'].'/lib/application.php';
include_once $_SERVER['PHP_ROOT'].'/lib/growth/greatwall.php';
include_once $_SERVER['PHP_ROOT'].'/lib/cache_object.php';
include_once $_SERVER['PHP_ROOT'].'/lib/fbml/include.php';
include_once $_SERVER['PHP_ROOT'].'/lib/chat/channel_common.php';
include_once $_SERVER['PHP_ROOT'].'/lib/gifts.php';
include_once $_SERVER['PHP_ROOT'].'/lib/giftshop.php';
include_once $_SERVER['PHP_ROOT'].'/lib/classifieds.php';
include_once $_SERVER['PHP_ROOT'].'/lib/relationship.php';
include_once $_SERVER['PHP_ROOT'].'/lib/media_header.php';
include_once $_SERVER['PHP_ROOT'].'/lib/video/video.php';
include_once $_SERVER['PHP_ROOT'].'/lib/privacy_platform.php';

print_time('profile.php include init');
param_get_slashed(array(
    'id'         => $PARAM_ID,
    'view'       => $PARAM_STRING,
    'l'          => $PARAM_STRING,
    'd'          => $PARAM_STRING, // invitee id
    'e'          => $PARAM_STRING, // code for profile id
    'hiq'        => $PARAM_STRING,
    'hif'        => $PARAM_STRING,
    'extinguish' => $PARAM_EXISTS,
    'highlight' => $PARAM_EXISTS,
    'layout'    => $PARAM_EXISTS,
    // st - test by showing many stories of given type in the local db of the
    //    person whose profile we ar viewing
    'st'         => $PARAM_INT,
    'n'          => $PARAM_INT,
    'extinguish' => $PARAM_EXISTS,
    'name'       => $PARAM_STRING,
    )); // LN CSRF - This should technically be some sort of POST since it
    // modifies the DB TODO: use do_post to fix this

if ($api_params = api_param_get(array('uid'))) {
  $get_id = $api_params['uid'];
} else {
  // process any POST operations here
}

// if there's no id, try to extra from borked aim profile get variable
if (!$get_id) {
  $get_id = (int) extract_arg_from_get_key('id');
  $get_l  =       extract_arg_from_get_key('l');
}

if ($get_l) {
  flag_allow_aim($get_id, $get_l);
}
flag_allow_guest();
$user = get_loggedin_user();

// unlock the page for the invited user
$is_unregistered_guest = 0;
if ($user <= 0 && $get_d && $get_e && profile_code($get_id) == $get_e) {
  $is_unregistered_guest = 1;
  $user = $get_d;
}
if (!check_super($user)) {
  $get_st = 0;
}

// if there's no id, go to the user's profile
if (!$get_id && $user) {
  $get_id = $user;
}

// need to prime the short profile cache for the viewed user so that
// emailgen never has to go to the db. also primes is_memorialized
if ($get_id) {
  profile_get_short($get_id);
}

// Determine is this is a memorialized profile, or your own profile
$is_memorialized = $get_id && is_memorialized($get_id);
$this_is_you = ($user == $get_id);

// Determine if we are looking at a public listing, there are 3 cases to consider
// (1) user is logged out, looking at a public listing URL
// (2) user is logged in, looking at their own public listing URL
// (3) user is logged in, looking at someone else's public listing URL
$public_listing_logged_out_user = false;
$public_listing_logged_in_self = false;
$public_listing_logged_in_user = false;
if (((!isset($GLOBALS['AIM_MODE']) || $GLOBALS['AIM_MODE'] != 1) && ($user <= 0))
  ||($is_unregistered_guest)) {
  $public_listing_logged_out_user = true;
} else if ($user>0 && $this_is_you && $get_name) {
  $public_listing_logged_in_self = true;
} else if ($user>0 && !$this_is_you && $get_name) {
  $public_listing_logged_in_user = true;
}


// Only continue, if the user passed one of the 3 public listing conditions
if ($public_listing_logged_out_user
 || $public_listing_logged_in_self
 || $public_listing_logged_in_user) {

  // Go home if account is not active or a dark account
  if (!is_active_user($get_id)
    || is_unregistered($get_id)
    || $is_memorialized) {
    go_home();
  }

  // Determine if account and privacy settings make public profile visible
  if (public_profile_is_visible($get_id, $get_name, $is_unregistered_guest, $this_is_you)) {

    // Get the public profile data
    $pp = public_profile_get_data($get_id);

    // Set all the template variables
    tpl_set('owner',      $this_is_you);
    tpl_set('actions',    $pp['actions']);
    tpl_set('friends',    $pp['friends_to_show']);
    tpl_set('counts',     $pp['counts']);
    tpl_set('name',       $pp['name']);
    tpl_set('first_name', $pp['first_name']);
    tpl_set('gender',     $pp['gender']);
    tpl_set('image_path', $pp['image_path']);
    tpl_set('id',         $get_id);
    tpl_set('login_href', 'login.php?next=http%3A%2F%2Fwww.facebook.com%2Fp%2F'
                         .clean_external_profile_name($pp['name']).'/'.$get_id);
    tpl_set('is_merman', user_has_obj_attached($get_id));

    // Render and exit, ie. don't execute the code below for a regular profile
    render_template($_SERVER['PHP_ROOT'].'/html/public_profile.phpt');
    exit();

  } else {
    // The public profile is not visible, so we require a login
    require_login();
  }

}

// If we made it this far, we know the public listing (above) was not rendered,
// so we must be looking at a regular profile

// Merman's Admin profile always links to the Merman's profile
if (user_has_obj_attached($get_id)) {
  $person_id = operson_user_get_obj($get_id);
  redirect(obj_get_relative_profile_url($person_id, $user));
}


// if viewing id is not valid or current user is not valid the send home
if (!is_fb_user($get_id) || $user <= 0) {
  go_home();
}


// always set $conn to the db for the profile you are viewing
if (isset($get_id)) {
  $conn = id_get_conn($get_id);
  if (!$conn) {
    tpl_set('db_down_error', 'Sorry, this profile is not available at the moment.<br/>Please try again shortly.');
    render_template($_SERVER['PHP_ROOT'].'/html/profile.phpt');
  }
}

// NOTE(mcslee): ok, at this point we know we are going to display the full
// page, so it is time to do a PHATTY PHATTY MULTIGET of all the shit that
// we are going to need to make this page, or at least the most common things

// need to know friendship status to optimize prefetching
user_get_contact_info($get_id, true);
user_get_basic_info($get_id, true);
user_get_personal_info($get_id, true);
user_get_hs_info($get_id, true);
user_get_installed_apps_all_types($get_id, true);
platform_get_all_app_settings($get_id, true);
user_get_all_friends($get_id, false, true);
user_get_blocks($user, true);
whitelist_get_users($get_id, true);
orientation_get_status($get_id, true);
user_get_extra_emails($get_id, true);
user_get_education($get_id, true);
user_get_work_history($get_id, true);
user_get_hide_intro_bitmask($user, true);
if ($user != $get_id) {
  profile_get_short($user, true);
  user_get_installed_apps_all_types($user, true);
  platform_get_all_app_settings($user, true);
  user_get_relationship($get_id, true);
}
memcache_dispatch();

//hzhao: this is a bit questionable, but since we have fetched all apps this
// user has installed, updating this cache isn't going to be that expensive
dirty_user_has_unique_nav_order($user);

// Can see depends upon some other stuff
multiget_can_see($user, array($get_id), true);
if ($are_friends = are_friends($get_id, $user)) {
  // This stuff is only needed if you are friends
  user_get_social_friends($get_id, 0, true);
  user_get_social_friends($get_id, 1, true);
  user_get_social_links($get_id, array($user), 1, true);
  memcache_dispatch();
}

// Now onto the main page
require_home_map($get_id);
$profile = array_merge(
  profile_get_short($get_id),
  user_get_basic_info($get_id),
  user_get_contact_info($get_id),
  user_get_personal_info($get_id),
  user_get_hs_info($get_id)
);

tpl_set('id',      $get_id);
tpl_set('user',    $user);

tpl_set('profile', $profile);
$apps_data[$GLOBALS['APP_ID_INFORMATION']]['profile'] = $profile;
$apps_data[$GLOBALS['APP_ID_INFORMATION']]['user'] = $user;

// ubersearch highlighing, decode get vars
$us_can_highlight = false;
$ss_term_in_name = false;
$us_terms_highlight = null;
$us_fields_highlight = null;

// only do the high-lighting if coming from a search result or login.  User's hacking
// URLs is not fun.
if (isset($get_hiq) &&
    (starts_with(basename($_SERVER['HTTP_REFERER']), 's.php') ||
     starts_with(basename($_SERVER['HTTP_REFERER']), 'login.php'))) {
  // query terms to match whole word
  $us_terms_highlight  = explode(',', $get_hiq);
  $us_can_highlight = true;
  foreach ($us_terms_highlight as $this_term) {
    if (!empty($this_term) && strstr($profile['name'], $this_term)) {
      $ss_term_in_name = 1;
    }
  }
}


if (isset($get_hif)) {
  $ftemp = explode(',', $get_hif);

  if (is_array($ftemp)) {
    $us_can_highlight = true;
    foreach($ftemp as $idterm) {
      if (!empty($idterm)) {
        $ftemp2 = explode(chr(1), $idterm);
        if (isset($GLOBALS['cid_to_colname'][1][$ftemp2[0]])) {
          $us_fields_highlight[$GLOBALS['cid_to_colname'][1][$ftemp2[0]]] = $ftemp2[1];
        }
        if (strstr($profile['name'], $idterm)) {
          $ss_term_in_name = 1;
        }
      }
    }
  }
}


if ($us_can_highlight) {
  $us_highlight = array('terms' => $us_terms_highlight,
      'fields' => $us_fields_highlight);
  tpl_set('us_highlight', $us_highlight);
}

$are_friends   = are_friends($get_id, $user);
$user_is_guest = user_is_guest($user);
$can_see_diff  = $are_friends || check_super($user);
$diff_view = false;
$old_fields_array = null;

$now = time();
$three_days_ago = $now - 259200;
if ($get_highlight && $can_see_diff &&
    $profile['profile_update_time'] > $three_days_ago) {
  // parse array into key value pairs for display
  $old_fields_array = get_diff_array($get_id);
  if (is_array($old_fields_array) && count($old_fields_array))  {
    $diff_view = true;
  }
}


// if we got invalid info or the account is deactivated, go home

if ($profile['confirmed'] > 0 && !$is_memorialized) {
  if(IS_DEV_SITE || IS_QA_SITE) {
    tpl_set('profile_disabled', true);
  } else {
    go_home();
  }
}

// lets orient ourselves. Is this my profile? a friend, a girlfriend?
tpl_set('this_is_friend', ($get_id != $user) && $are_friends);
$orientation = orientation_get_status($get_id, false);
tpl_set('orientation', $orientation);

$pending_confirm = false;
$is_on_whitelist = false;
$show_public_profile_link = false;
$my_profile = false;
$my_sig_other = false;

if ($get_id != $user) {
  if ($user == user_get_relationship($get_id)) {
    $my_sig_other = true;
  }
  if ($are_friends) {
    // Social map
    $friend_links = get_links_for_profile($user, $get_id, $are_friends, $my_sig_other);
    tpl_set('unconfirmed_friend_links', $friend_links['unconfirmed']);
    tpl_set('confirmed_friend_links', $friend_links['confirmed']);
  }

  // Check profile visibility
  list($can_see_profile, $pending_confirm, $is_on_whitelist) =
    profile_can_see_meta($user, $get_id, $are_friends);

} else {
  // of course you can see your own profile
  $can_see_profile = $can_see_diff = true;
  $my_profile = true;
  if (!privacy_search_is_restricted($user)) {
    $menu_options['public_profile'] = get_external_profile_url($user);
  }
}
tpl_set('this_is_you', $my_profile);
tpl_set('this_is_sig_other', $my_sig_other);


// If they're in the AIM mode or super we can see the profile regardless
$can_see_profile = ((isset($AIM_MODE) && $AIM_MODE) || check_super($user)) ? true : $can_see_profile;

// if we don't have permissions to see this profile, try to show a search
// listing of the person, else go home
if (!$can_see_profile && !$is_unregistered_guest) {

  //debug_print("profile.php: calling can_see(user=$user, id=$get_id, type=search");
  if (!can_see($user,$get_id, 'search')) {
    go_home();
  } else {
    redirect(get_search_profile_url($get_id, false), id_get_map($get_id));
  }
}
print_time("profile.php after check_okay");


// Share and Save
$share_hrefs = share_make_profile_hrefs($get_id);
tpl_set('share_hrefs', $share_hrefs);


print_time("profile.php start logging");

if (isset($friend_links['falcon'])) {
  $friend_links_falcon = $friend_links['falcon'];
 } else {
  $friend_links_falcon = null;
 }
falcon_log('view_profile', $user, true, array($get_id, id_get_primary_network($get_id), $friend_links_falcon));


/*
 *
 * PUT LOGGING STUFF HERE
 *
 */

// LOGGING STUFF IS HERE
// do a karma check if user is not looking at himself or his friends
// also, we need to make sure there is a logged in user b/c this
// check doesn't make sense if the profile is being viewed via aim link
$hidden_by_karma = false;
if ($user && !$my_profile && !$are_friends) {
  $hidden_by_karma = karma_log_profile_view($user);
}
tpl_set('hidden_by_karma', $hidden_by_karma);

// PRIVACY
$can_see = can_see_profile_fields_array($user,
                                        $get_id,
                                        $is_on_whitelist,
                                        isset($AIM_MODE) ? $AIM_MODE : null,
                                        $is_unregistered_guest);

print_time("profile.php privacy");

$show_apps = array();

// determine if we want to display the minifeed intro message
$hide_minifeed_intro = 0;
$feed_intro_consts = hide_intro_constants();
$feed_intro = user_get_hide_intro_bitmask($user);
$hide_minifeed_intro = $feed_intro & $feed_intro_consts['HIDE_INTRO_MINIFEED'];
$HIDE_INTRO_BITMASK = get_site_variable('HIDE_INTRO_BITMASK');  // set to 3 if we want to always hide the intros

// hide message on profiles that aren't yours
if ($user != $get_id) {
  $hide_minifeed_intro = 3;
}

tpl_set('hide_minifeed_intro', ($hide_minifeed_intro | $HIDE_INTRO_BITMASK) & $feed_intro_consts['HIDE_INTRO_MINIFEED']);

// get their image if one exists
if ($profile['link']) {
  tpl_set('image_path', make_profile_image_src($user, $get_id, 'normal'));
  tpl_set('orientation_picture', false);
} else {
  tpl_set('image_path', '');
  tpl_set('orientation_picture', $user==$get_id);
}

print_time("profile.php pic");


//#
//# MENU
//#

$photo_tagcount = null;
// only when either one has installed the photo application
if (platform_can_see_app_profile_action($GLOBALS['APP_ID_PHOTOS'], $get_id, $user)) {
  if ($my_profile || $can_see['photosofme'] || $is_unregistered_guest) {
    if ($my_profile) {
      $menu_options['can_browse_photos_me'] = 'photo_search.php?id='.$get_id;
      $photo_tagcount = count_user_tags($user);
    } else {
      $numtags = count_user_tags($get_id);

      if (($numtags > 0)) {
        $menu_options['can_browse_photos'] = 'photo_search.php?id='.$get_id;
        $photo_tagcount = $numtags;
      }
    }
  }
}
if (can_see_installed_app($GLOBALS['APP_ID_PHOTOS'], $get_id, $user)) {
  $show_apps['photos'] = true;
}

tpl_set('photo_tagcount', $photo_tagcount);

$can_talk = '';
$first_name = txt_set(user_get_first_name($get_id));
if (is_chat_user($user) && can_chat($user, $get_id)) {
  $can_talk = "javascript:chatWindow.focus_tab($get_id, '$first_name');";
 }
$menu_options['can_talk'] = $can_talk;

if (!$my_profile) {
  if (!$user_is_guest) {
    $menu_options['can_message'] = redirect_str('inbox/?compose&id='.$get_id);
  }
  //allow only if they are not my friend -- also allow super users
  if (($user && !$are_friends && !$is_memorialized) || check_super($user)) {
    $menu_options['report_user'] = 'report.php?uid=' . $get_id . '&amp;h=' . gen_report_hash($user, $get_id);
  }
}

// remove from friends
if ($are_friends && !$user_is_guest) {
  $menu_options['remove_friends'] = redirect_str('friends.php?remove_friend=1&friend_id='.$get_id.'&rr=1');
}

// see if you can poke the person
if (!$my_profile && !$is_memorialized && !$user_is_guest) {
  $menu_options['can_poke']['href'] = 'poke.php?id=' . $get_id;
  $menu_options['can_poke']['onclick'] = 'show_poke_dialog('.$get_id.');return false;';
}

// see if you can add the person as a friend
if (!$my_profile && !$are_friends && !$is_memorialized && !$user_is_guest) {
  if ($pending_confirm) {
    $requests_constants = requests_constants();
    $menu_options['pending_confirm'] = redirect_str('reqs.php?confirm='.$get_id.'&type='.
                                                    $requests_constants['PERSON_TYPE'],
                                                    id_get_map($user));
  } else if(user_has_obj_attached($user)) { // Merman profiles cannot add as friends
    // no Op
  } elseif (friend_request_pending($get_id, $user)) {
    $menu_options['pending_friend_reply'] = true;
  } else {
    $menu_options['can_add_friend']['href'] = 'addfriend.php?id=' . $get_id;
          $menu_options['can_add_friend']['onclick'] = 'show_addfriend_dialog('.$get_id.', this);return false;';
  }
 }
tpl_set('pending_confirm', $pending_confirm);

// see if we need other edit options
if ($my_profile && !$user_is_guest) {
  $menu_options['can_edit'] = 'editprofile.php?basic';
}

if ($can_see['friends'] && !$my_profile) {
  $menu_options['view_all_friends'] = "friends.php?id=$get_id";
}

// Add link to create banner
if ($my_profile && !$orientation) {
  $menu_options['create_badge'] = "badges.php";
}
print_time("profile.php menu");

$primary_network = id_get_primary_network($get_id); // primary network of the person we're viewing
tpl_set('primary_network_type', extract_network_type($primary_network));
tpl_set('primary_network', $primary_network);

// friends
$friends_to_show = array();

if ($can_see['friends']) {
  $total = 0;

  // friend_pool is the pool of friends we can choose from.
  // as we add people to boxes (like mutual friends, for example),
  // we remove them from the pool so that we don't see the same friend
  // multiple times on the same page at once
  $friend_pool = user_get_all_friends($get_id, true);
  $total_friend_count = sizeof($friend_pool);

  // number of people we show in the "friends at blah" box
  $max_primary_to_show = 6;

  if (!$my_profile) {
    // get mutual friend count (but don't do it if there are more than 5000 combined friends
    $id_friends = array_keys($friend_pool);
    $user_friends = user_get_all_friends($user);

    $num_user_friends = count($user_friends);
    $num_id_friends = count($id_friends);

    if ($num_id_friends + $num_user_friends > 5000) {
      $total = 0;
    } else {
      // this is faster than array_intersect
      $mutual_friends = array();
      $key_id_friends = array_flip($id_friends);
      foreach($user_friends as $user_id) {
        if (isset($key_id_friends[$user_id])) {
          $mutual_friends[] = $user_id;
        }
      }

      $total = count($mutual_friends);
      shuffle($mutual_friends);

      $mutual_profiles = multiget_short_profiles(array_slice($mutual_friends, 0, 15));

      $i = 0;
      $people = array();
      foreach ($mutual_friends as $friend_id) {
        if (can_see($user, $friend_id, 'search')) {
          $friend_sp = $mutual_profiles[$friend_id];
          $people[$i] = array(
              'name' => $friend_sp['name'],
              'href' => get_best_profile_url($user, $friend_id),
              'image' => make_profile_image_src($user, $friend_id, 'thumb'),
              );
          /* always keep friend pool more than max number of friend photos to show (duplicates okay in this case),
           otherwise get weirdness where it says they 5 friends but only one shows up. */
          if (sizeof($friend_pool) > $max_primary_to_show) {
            unset($friend_pool[$friend_id]); // remove this person from the friend pool
          }
          if (++$i >= 3) { // show a max of 3 mutual friend
            break;
          }
        }
      }

      $mutual_friends = array(
          'count' => $total,
          'all_href' => redirect("/friends.php?id=$get_id&ca=4", null, 0),
          'people' => $people,
          );

      $friends_to_show['mutual'] = $mutual_friends;
    }
  }

  $friend_affiliations = user_get_friend_affiliations($get_id);
  $primary_friends = $friend_affiliations['primary_friends'];
  $primed_id_friends = array();
  if (count($primary_friends) > 0) { //if they have friends to display from their primary network
    shuffle($primary_friends);
    $primed_found = 0;
    // loop through list of primary friends - stop when you've found 6 we haven't shown before
    foreach ($primary_friends as $primary_friend) {
      // make sure they are part of the available friend pool (everyone else has been shown already)
      if (isset($friend_pool[$primary_friend])) {
        $primed_id_friends[] = $primary_friend;
        if (++$primed_found == $max_primary_to_show) { // found our 6
          break;
        }
      }
    }
    $num_primary_friends = sizeof($primary_friends);
    $pr_network_name = network_get_name($profile['pr_net']);
  } else {
    // unaffiliated users OR users with no friends in their pri network - just pick any 6 from pool of unshown friends
    $primary_network = 0;
    $primary_friends = array_keys($friend_pool);
    shuffle($primary_friends);
    $primed_id_friends = array_slice($primary_friends, 0, $max_primary_to_show);

    // when you're unaffiliated, the whole world is your primary network
    $num_primary_friends = $total_friend_count;
    $pr_network_name = "";
  }

  // primary network friends
  $primary_network_people = array();

  multiget_short_profiles($primed_id_friends);
  multiget_can_see($user, $primed_id_friends);

  $total = 0;
  foreach ($primary_friends as $friend_id) {
    if (can_see($user, $friend_id, 'search')) {
      $sp = profile_get_short($friend_id);
      $primary_network_people[$total] = array(
          'name' => $sp['name'],
          'href' => !is_unregistered($friend_id) ? get_best_profile_url($user, $friend_id) : '',
          'image' => make_profile_image_src($user, $friend_id, 'thumb'),
          );
      unset($friend_pool[$friend_id]); // remove this person from the friend pool
      if (++$total >= $max_primary_to_show) {
        break;
      }
    }
  }

  $primary_network_friends = array(
      'count' => $num_primary_friends,
      'all_href' => redirect("/friends.php?id=$get_id&nk=$primary_network", null, 0),
      'network_name' => $pr_network_name,
      'people' => $primary_network_people,
      'is_geo' => ($TYPE_GEO == extract_network_type($profile['pr_net']))
      );

  // set friends to show, used for both affiliated and non-affiliated users
  $friends_to_show['primary'] = $primary_network_friends;

  $friends_to_show['count'] = $total_friend_count;
  $friends_to_show['all_href'] = redirect("/friends.php?id=$get_id", null, 0);


  tpl_set('friends2point0', true);
  tpl_set('friends', $friends_to_show);
  tpl_set('this_is_you', $my_profile);
  if ($total_friend_count<7 && $get_id==$user) {
    tpl_set('orientation_friends', true);
    tpl_set('hs_info', user_get_hs_info($get_id)); // we need this for the orientation profiles and it's not set anywhere else
  }
}

print_time('primary network friends');


// get the other networks that the person has friends at and how many there are, etc.
$i = 0;
$friend_networks = array();
$special_networks = array();
$num_special_networks = 8; // special because they're the ones that matter most to you when viewing someone else's profile =)
$aff_count = 1;

if ($can_see['friends']) {

  $friend_affiliations = user_get_friend_affiliations($get_id);
  print_time('other networks');
  $my_affiliations = id_get_networks($user);
  print_time('special networks');

  // optimize all network name requests into one huge apc multiget :)
  $profile_network_keys = array_merge(array_keys($friend_affiliations['alphabetically']),
                                      array_keys($friend_affiliations['by_number_of_friends'])
                                     );
  $profile_network_names = multiget_network_name($profile_network_keys);
  print_time('profile network names');

  foreach ($friend_affiliations['alphabetically'] as $network_key => $count) {
    $friend_networks[] = array(
        'name' => $profile_network_names[$network_key],
        'count' => $count,
        'href' => redirect("/friends.php?id=$get_id&nk=$network_key", null, 0),
        );
  }

  foreach($my_affiliations as $network_key) {
    if (isset($friend_affiliations['by_number_of_friends'][$network_key])) {
      $special_networks['in_common'][] = array(
          'name' => $profile_network_names[$network_key],
          'count' => $friend_affiliations['by_number_of_friends'][$network_key],
          'href' => redirect("/friends.php?id=$get_id&nk=$network_key", null, 0),
          );
    }
  }

  foreach($friend_affiliations['by_number_of_friends'] as $network_key => $count) {
    if ($aff_count >= $num_special_networks) break;
    $special_networks['lots_of_friends'][] = array(
        'name' => $profile_network_names[$network_key],
        'count' => $count,
        'href' => redirect("/friends.php?id=$get_id&nk=$network_key", null, 0),
        );
    $aff_count++;
  }


  $apps_data[$GLOBALS['APP_ID_NETWORK_FRIENDS']]['networks_with_friends'] = $friend_networks;
  $apps_data[$GLOBALS['APP_ID_NETWORK_FRIENDS']]['special_networks'] = $special_networks;
  $apps_data[$GLOBALS['APP_ID_NETWORK_FRIENDS']]['user_first_name'] = $first_name;

  $show_apps[$GLOBALS['APP_ID_NETWORK_FRIENDS']] = true;
}


/**
 * STATUS UPDATES
 */

$show_status = $my_profile;
$status = array();
$status['mine'] = $my_profile;

if (!$is_memorialized &&
    ($my_profile || $can_see['statusupdates'])) {
  // We fetch this differently due to 2 diff cache keys, for yourself you want
  // to get the full presence data with your custom history, but for someone
  // else we just want the small status info, no history
  if ($my_profile) {
    $status_data = mobile_get_presence_data($get_id);
    $one_week_ago = time() - 604800;
    if ($status_data['status_time'] < $one_week_ago) {
      $status_data['status'] = '';
    }
    $mobile_status = array('message' => $status_data['status'],
                           'time' => $status_data['status_time'],
                           'source' => $status_data['status_source']);
  } else {
    $mobile_status = mobile_get_status($get_id);
  }

  // Display it only if a message is present
  if ($mobile_status['message']) {
    $mobile_status['message'] = txt_set($mobile_status['message']);
    $status['info'] = $mobile_status;

    // Show Diff
    if ($diff_view &&
        array_key_exists('mobile_status', $old_fields_array) &&
        $old_fields_array['mobile_status']) {
      $status['show_diff'] = true;
    }

    $show_status = true;
  }
  $status['custom'] = $my_profile ? mobile_get_status_custom($get_id) : null;
  $status['editable'] = ($my_profile && !$user_is_guest);
}
tpl_set('status', $status);
tpl_set('show_status', $show_status);


/**
 * ONLINE PRESENCE
 */

// Clear fire if desired
if ($my_profile && $get_extinguish) {
  mobile_extinguish_fire($user);
  // Redirect so that extinguish doesn't show up in the link again, in case
  // the user wants to hit 'refresh' after this
  $uri = $_SERVER['REQUEST_URI'];
  $uri = preg_replace('/(\?|&)extinguish/', '', $uri);
  header('Location: '.$uri);
  my_exit();
}

// Check online status
$show_online = false;
$presence = array();
if ($can_see['online'] && !$is_memorialized) {
  $presence['online'] = $my_profile || presence_is_user_logged_in($get_id);
  $presence['fire'] = mobile_is_on_fire($get_id);
  if ($presence['fire']) {
    $presence['fired_by'] = mobile_get_fired_by($get_id);
    $presence['fired_by'] = render_name_no_network_with_profile_link($user, $presence['fired_by']);
  }
  $show_online = true;
}
tpl_set('presence', $presence);
tpl_set('show_online', $show_online);

print_time("profile.php login_info");

$networks_current = $profile['active_affiliations_data'];
tpl_set('networks', $networks_current);

print_time("profile.php friends at other schools");


//
// INFO
//

// get geography stuff
if ($profile['geography'])
txt_set('geo_name', geography_name($profile['geography']));

$current_school = get_current_school($get_id);
txt_set('current_school', $current_school);

$network_name = id_get_network_name($get_id);
txt_set('network_name', $network_name);

// get high school name
if ($profile['hs']) { // THIS IS FOR COLLEGE DEFINED HS
  // LN - no txt_set, make_ubersearch_link does this in the display layer
  $high_school = get_high_school($profile['hs']);
  if ($profile['hs2']) {
    $high_school2 = get_high_school($profile['hs2']);
  } else {
    $high_school2 = null;
  }
} else {
  $high_school = null;
  $high_school2 = null;
}


// PROCESSED PROFILE STUFF
if ($us_can_highlight && !$ss_term_in_name) {
  // Can't use the profile cache here because the profile displays
  // differently depending on your search
  $flag_no_profile_cache = 1;
} else {
  $flag_no_profile_cache = 0;
}

$flag_no_profile_cache = $flag_no_profile_cache || !IS_PRODUCTION_WEB;
$birthday_visibility = user_get_info_preferences_attr($get_id, 'birthday');


// This function renders a large chunk of the profile page, then saves the resulting
// html in memcache so it doesn't need to be recomputed each time.
$content_arr = profile_get_content_html($get_id, $profile, $diff_view, $old_fields_array,
                                        $birthday_visibility, $high_school, $high_school2,
                                        $flag_no_profile_cache);

// Make sure all keys are present
$content_default = profile_get_default_content_arr();
$content_arr = array_key_merge($content_default, $content_arr);

// Hide Relationship Sig Other if $user can't see Sig Other in Search
// get_relationship returns -1 for nobody relationships
if (!$content_arr['relationship_link'] ||
    ($rel_id = get_relationship($get_id)) <= 0 ||
    $user <= 0 ||
    !can_see($user, $rel_id, 'search')) {
  $content_arr['relationship_link'] = '';
}


//
// EDUCATION AND WORK
//
$work_history = user_get_work_history($get_id);
$apps_data[$GLOBALS['APP_ID_EDUWORK']]['work_history'] = $work_history;

$education = user_get_education($get_id);
$apps_data[$GLOBALS['APP_ID_EDUWORK']]['education'] = $education;

// TODO: break up the content_arr and can_see into the parts we need
$apps_data[$GLOBALS['APP_ID_EDUWORK']]['content_arr'] = $content_arr;
$apps_data[$GLOBALS['APP_ID_EDUWORK']]['can_see'] = $can_see;
$show_apps[$GLOBALS['APP_ID_EDUWORK']] = $can_see['professional'] || $can_see['education'];


//
// SEASONAL
//
$apps_data[$GLOBALS['APP_ID_SEASONAL']]['break_plans_season'] = get_site_variable('BREAK_PLANS_SEASON');
$apps_data[$GLOBALS['APP_ID_SEASONAL']]['content_arr'] = $content_arr;

$show_apps[$GLOBALS['APP_ID_SEASONAL']] = $can_see['seasonal'] && !$is_memorialized;


//
// GROUPS
//
$groups = array();
if (is_platform_app_installed_to_profile($GLOBALS['APP_ID_GROUPS'], $get_id)) {
  if ($can_see['groups'] && !$is_memorialized) {
    $groups = profile_get_groups_data($get_id, $can_see['groups']);
    if (!empty($groups)) {
    $show_apps[$GLOBALS['APP_ID_GROUPS']] = true;
    }
  }
}
$apps_data[$GLOBALS['APP_ID_GROUPS']]['groups'] = $groups;

//
//  CLASSIFIEDS
//
if (can_see_installed_app($GLOBALS['APP_ID_MARKET'], $get_id, $user)) {
  if (user_can_see_classifieds($user) && !$is_memorialized) {
    $classifieds_data = profile_get_classifieds_box_data($get_id);
    if (isset($classifieds_data['listings'])) {
      $classifieds_data['listings'] = profile_prepare_classifieds_box_data($classifieds_data['listings'], $user);
      $classifieds_data['count_total'] = classifieds_get_num_user_posts($get_id);
      $classifieds_data['count_shown'] = count($classifieds_data['listings']);
      $classifieds_data['href'] = redirect_str('/marketplace/', 'www');
      $apps_data[$GLOBALS['APP_ID_MARKET']] = $classifieds_data;
      $show_apps[$GLOBALS['APP_ID_MARKET']] = true;
    }
  }
}
print_time("profile.php marketplace");

//
// SAVED BOX
//

if (is_platform_app_installed_to_profile($GLOBALS['APP_ID_POSTED'], $get_id)) {
  $show_apps['posted'] = true;
  if ($can_see['saves'] && !$is_memorialized) {
    $saved_data = profile_get_share_data($user, $get_id, $diff_view, $old_fields_array);
    $apps_data[$GLOBALS['APP_ID_POSTED']]['saved'] = $saved_data['saved'];
    $apps_data[$GLOBALS['APP_ID_POSTED']]['ids'] = $saved_data['ids'];
    $apps_data[$GLOBALS['APP_ID_POSTED']]['count'] =  $saved_data['count'];

    if ($saved_data['saved']) {
      $show_apps[$GLOBALS['APP_ID_POSTED']] = true;
    }
    print_time("profile.php saved box");
  } else {
    $show_apps[$GLOBALS['APP_ID_POSTED']] = false;
  }
} else {
  $show_apps[$GLOBALS['APP_ID_POSTED']] = false;
}

//
// PHOTOS
//
$photos_arr = profile_get_photos_data($get_id, $user,
                                      isset($old_fields_array['updated_album']) ?
                                      $old_fields_array['updated_album'] :
                                      array());

if (!empty($photos_arr) && $can_see['albums']) {
  $show_apps[$GLOBALS['APP_ID_PHOTOS']] = true;
 }
$apps_data[$GLOBALS['APP_ID_PHOTOS']]['photos'] = $photos_arr;
tpl_set('photos', $photos_arr);
print_time('profile.php photos');

//
// NOTES
//
$notes_by_count = 0;
if (is_platform_app_installed_to_profile($GLOBALS['APP_ID_NOTES'], $get_id) &&
    $can_see['notes'] &&
    !$is_memorialized &&
    can_see_installed_app($GLOBALS['APP_ID_NOTES'], $get_id, $user)) {
  $show_apps[$GLOBALS['APP_ID_NOTES']] = true;
  if ($user && !$is_memorialized) {
    $notebook = profile_get_notes_data($get_id, $my_profile);
    $apps_data[$GLOBALS['APP_ID_NOTES']]['notebook'] = $notebook;
  }

  if ($can_see['notes']) {
    $notes_by_count = notebook_get_count($get_id);
    if ($my_profile) {
      $menu_options['can_see_notes_by_me'] = "notes.php";
    } else {
      $menu_options['can_see_notes_by'] = "notes.php?id=$get_id";
    }
  }
}
tpl_set('notes_by_count', $notes_by_count);
print_time("profile.php notes");


//
// VIDEO
//
$video = null;
$video_tagcount = null;
if (platform_can_see_app_profile_action($GLOBALS['APP_ID_VIDEO'], $get_id, $user) &&
    video_is_active()) {
  if ($my_profile || $can_see['videosofme'] || $is_unregistered_guest) {

    $videos_of_user_url = video_get_videos_of_user_url($get_id);
    $video_counts = video_get_user_counts($get_id);
    $video_tagcount = $video_counts['of'];

    if ($video_tagcount) {
      if ($my_profile) {
        $menu_options['can_browse_videos_me'] = $videos_of_user_url;
      } else {
        $menu_options['can_browse_videos'] = $videos_of_user_url;
      }
    }
  }
}
if (can_see_installed_app($GLOBALS['APP_ID_VIDEO'], $get_id, $user) &&
    video_is_active()) {
  $video = profile_get_video_data($get_id, $user);
  if ($video && $can_see['video']) {
    $show_apps[$GLOBALS['APP_ID_VIDEO']] = true;
  }
}

tpl_set('video_tagcount', $video_tagcount);
print_time('profile.php video');
$apps_data[$GLOBALS['APP_ID_VIDEO']] = txt_set($video);
tpl_set('menu_options', $menu_options);

//
// MOBILE UPLOADS
//
$mobile_uploads = null;
if (is_platform_app_installed_to_profile($GLOBALS['APP_ID_MOBILE'], $get_id) &&
    can_see_installed_app($GLOBALS['APP_ID_MOBILE'], $get_id, $user)) {
  $mobile_uploads = profile_get_mobile_uploads_data($user, $get_id);
  if (!empty($mobile_uploads)) {
    $show_apps[$GLOBALS['APP_ID_MOBILE']] = true;
  }
}
$apps_data[$GLOBALS['APP_ID_MOBILE']]['mobile'] = $mobile_uploads;

//
// COURSES
//
$courses = array();
if ($can_see['courses'] && !$is_memorialized) {
  $can_show_courses = user_has_courses($get_id);
  if ($can_show_courses) {
    $skip_cache = !IS_PRODUCTION_WEB || $NO_CACHE;
    $courses = profile_get_courses_html($get_id, $skip_cache);
    $show_apps[$GLOBALS['APP_ID_COURSES']] = true;
  } else {
    $show_apps[$GLOBALS['APP_ID_COURSES']] = false;
    $courses = array();
  }
} else {
  $courses = array();
  $show_apps[$GLOBALS['APP_ID_COURSES']] = false;
}

$apps_data[$GLOBALS['APP_ID_COURSES']] = $courses;

print_time("profile.php courses");


//
// WALL
//
// ----------------------------------------------------------------------------
if ($can_see['wall']) {
  $wall_config = array('can_see' => true);
  $wall = wall_prepare_profile_box($user, $get_id);
  if (rand(1, 100000) > get_site_variable('WALL_POST_OLDEST_ENTRY_THROTTLE')) {
    if (empty($wall['wall_posts'])) {
      $time = 0;
    } else {
      $time = $wall['wall_posts'][count($wall['wall_posts']) - 1]['time'];
    }
    $message = scribe_create_message('wall_survey', 'user: '.$time.' '.$wall['count']);
    scribe_add_messages(array($message));
  }
  $apps_data[$GLOBALS['APP_ID_WALL']]['wall_total'] = $wall['count'];
  $apps_data[$GLOBALS['APP_ID_WALL']]['wall'] = $wall['wall_posts'];
  $apps_data[$GLOBALS['APP_ID_WALL']]['birthday_visibility'] = $birthday_visibility;
  $apps_data[$GLOBALS['APP_ID_WALL']]['birthday_notification_days'] = wall_get_birthday_notification_days($user, $get_id);
  $apps_data[$GLOBALS['APP_ID_WALL']]['wall_show_valentines_day_ad'] = wall_get_show_valentines_day_ad($user, $get_id);
  $apps_data[$GLOBALS['APP_ID_WALL']]['first_name'] = $first_name;

  $show_apps[$GLOBALS['APP_ID_WALL']] = true;
}
print_time("profile.php wall");


//
// MINIFEED
//

$hide_minifeed = false;
if ($is_memorialized) {
  $hide_minifeed = true;
  $minifeed_stories = null;

} else if ($get_st) {
  if (!$get_n) {
    $get_n = 30;
  }
  $minifeed_stories = minifeed_prepare_stories($user, $get_id,
    minifeed_filter_stories($user, $get_id,
    dev_dbget_minifeed_stories_of_type($get_id, $get_st, $get_n), $get_n),
    $get_n);

} else {
  if (can_see($user, $get_id, 'feed')) {
    $minifeed_stories = minifeed_prepare_stories($user, $get_id,
      minifeed_filter_stories($user, $get_id,
      user_get_minifeed_stories($get_id)), 10);
  } else {
    $hide_minifeed = true;
  }
}

$minifeed_archive_href = 'minifeed.php?id='.$get_id;
tpl_set('hide_minifeed', $hide_minifeed);
tpl_set('minifeed_stories', $minifeed_stories);
tpl_set('minifeed_archive_href', $minifeed_archive_href);

print_time("profile.php minifeed");

//
// VIRTUAL GIFTS
//

$giftbox = profile_get_giftbox_data($user, $get_id);
$apps_data[$GLOBALS['APP_ID_GIFTBOX']]['giftbox'] = profile_get_giftbox_data($user, $get_id);
$apps_data[$GLOBALS['APP_ID_GIFTBOX']]['user_can_promote'] = $giftbox['user_can_promote'];
$show_apps[$GLOBALS['APP_ID_GIFTBOX']] = true;

print_time("profile.php giftbox");

tpl_set('first_name', $first_name);

if (user_is_alpha($user, 'recentlogins')) {
  $recent_logins = array();
  $ret = queryf($conn, 'SELECT `ip`, max(`time`) AS `last_login`, min(`time`) AS `first_login`, count(*) AS `count` FROM `log_login` WHERE `id` = %d GROUP BY `ip` ORDER BY `count` DESC', $get_id);
  if ($ret) {
    while ($row = mysql_fetch_assoc($ret)) {
      $recent_logins []= array_merge($row, ip_get_gps_info($row['ip']));
    }
  }
  tpl_set('recent_logins', $recent_logins);
}

// SET ALL SCREENNAMES
// Screennames
$screennames = array();
if (!$is_memorialized) {
  $screennames = user_get_screennames($get_id);
}

$apps_data[$GLOBALS['APP_ID_INFORMATION']]['screennames'] = $screennames;

// SET ALL EMAILS
// $hidden_by_karma refers to karma telling us not to show email addresses
// 16777337 is the Naval Academy - we don't show their email addresses

//TODO: removing extra emails from profile
$email_images = array();
if (!$hidden_by_karma && !$is_memorialized) {
  $profile_emails = user_get_profile_emails($get_id, $profile, $can_see);
  $highlight_e = ($diff_view && array_key_exists('email', $old_fields_array));
  foreach ($profile_emails as $e) {
    $email_images []= email_image($e, $hidden_by_karma, $get_id, $highlight_e);
  }
}

// SET TEMPLATE VALUES

tpl_set('user_is_guest', $user_is_guest);
tpl_set('is_memorialized', $is_memorialized);
tpl_set('email_images', $email_images);

tpl_set('old_fields_array', $old_fields_array);

$apps_data[$GLOBALS['APP_ID_INFORMATION']]['email_images'] = $email_images;
$apps_data[$GLOBALS['APP_ID_INFORMATION']]['content_arr'] = $content_arr;
$apps_data[$GLOBALS['APP_ID_INFORMATION']]['can_see'] = $can_see;
$show_apps[$GLOBALS['APP_ID_INFORMATION']] = !$is_memorialized && ($can_see['contact'] || $can_see['personal']);

tpl_set('content_arr', $content_arr);
tpl_set('can_see', $can_see);
tpl_set('show_layout_popup', $get_layout);

tpl_set('diff_view', $diff_view);
if ($diff_view) {
  //find out which sections to expand
  $diff_section_mask =
    get_profile_diff_section_mask($old_fields_array);

  extract(profile_diff_get_const());

  $diff_photos = $diff_section_mask & $PROFILE_DIFF_SECTIONS['PHOTOS'];
  $diff_video  = false; //$diff_section_mask & $PROFILE_DIFF_SECTIONS['VIDEO'];
  $diff_status = $diff_section_mask & $PROFILE_DIFF_SECTIONS['STATUS'];
  $diff_notes = $diff_section_mask & $PROFILE_DIFF_SECTIONS['NOTES'];
  $diff_posts = $diff_section_mask & $PROFILE_DIFF_SECTIONS['POSTS'];
  $diff_personal = $diff_section_mask & $PROFILE_DIFF_SECTIONS['INFORMATION'];
  $diff_seasonal = $diff_section_mask & $PROFILE_DIFF_SECTIONS['SEASONAL'];
  $diff_education = $diff_section_mask & $PROFILE_DIFF_SECTIONS['EDU_WORK'];
  tpl_set('show_picture_diff', array_key_exists("link", $old_fields_array));
  tpl_set('show_status_diff', array_key_exists("mobile_status", $old_fields_array) && $old_fields_array['mobile_status']);
} else {
  $diff_photos = null;
  $diff_status = null;
  $diff_notes = null;
  $diff_posts = null;
  $diff_personal = null;
  $diff_seasonal = null;
  $diff_education = null;
}

$moveable_fb_boxes = get_fb_profile_box_moveability($this_is_you);
tpl_set('moveable_fb_boxes', $moveable_fb_boxes);


// PROFILE BOX ORDERING
$default_order_boxes = get_default_order_boxes();

// Get installed apps markup
if (!$is_memorialized) {
  $profile_apps_and_profile_actions =
    profile_get_apps_and_profile_actions($user, $get_id);
  $profile_apps = $profile_apps_and_profile_actions['profile_apps'];
  $platform_profile_actions =
    $profile_apps_and_profile_actions['platform_profile_actions'];
} else {
  $profile_apps = array();
  $platform_profile_actions = array();
}

tpl_set('ordered_boxes', $profile_apps);
tpl_set('platform_profile_actions', $platform_profile_actions);


/*
 * APP SWITCHER
 */
$app_switcher_data = array();
if (!$is_memorialized) {
  $app_switcher_data = get_app_switcher_data($user, $get_id);
  foreach (array_keys($app_switcher_data['apps']) as $app_name) {
    switch ($app_name) {
      case 'notes':
        $app_id = $GLOBALS['APP_ID_NOTES'];
        break;
      case 'photos':
        $app_id = $GLOBALS['APP_ID_PHOTOS'];
        break;
      case 'marketplace':
        $app_id = $GLOBALS['APP_ID_MARKET'];
        break;
      case 'groups':
        $app_id = $GLOBALS['APP_ID_GROUPS'];
        break;
      case 'posted':
        $app_id = $GLOBALS['APP_ID_POSTED'];
        break;
      case 'video':
        $app_id = $GLOBALS['APP_ID_VIDEO'];
        break;
      default:
        $app_id = null;
        break;
    }
    if ($app_id && !can_see_installed_app($app_id, $get_id, $user)) {
      unset($app_switcher_data['apps'][$app_name]);
    }
  }
  if (count($app_switcher_data['apps']) <= 1) {
    // must have only 'profile'
    $app_switcher_data = null;
  }
}

tpl_set('app_switcher_data', $app_switcher_data);

$apps_flex = user_get_app_display($user);

tpl_set('aim_presence', screenname_aim_presence_enabled($user));
tpl_set('apps_flex', $apps_flex);
tpl_set('greatwall_user', is_greatwall_user($user));
tpl_set('megawall_is_active', megawall_is_active($user));

greatwall_record_action('profile view');

tpl_set('show_apps', $show_apps);
tpl_set('apps_data', $apps_data);

render_template($_SERVER['PHP_ROOT'].'/html/profile.phpt');

print_time('profile.php render template');