PageRenderTime 54ms CodeModel.GetById 2ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/simple-forum/install/sf-upgrade-support.php

https://bitbucket.org/openfarmtech/weblog-content
PHP | 1594 lines | 1428 code | 94 blank | 72 comment | 134 complexity | 261072bd71a9f68f614061758a7ee163 MD5 | raw file
   1<?php
   2/*
   3Simple:Press
   4Install & Upgrade Support Routines
   5$LastChangedDate: 2010-05-13 19:54:56 -0700 (Thu, 13 May 2010) $
   6$Rev: 4018 $
   7*/
   8
   9if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) {
  10	die('Access Denied');
  11}
  12
  13include_once(SF_PLUGIN_DIR.'/library/sf-common-functions.php');
  14
  15# ==========================================
  16#
  17# GLOBAL UPDATE/INSTALL ROUTINES
  18#
  19# ==========================================
  20
  21
  22# Called from V4.1 onwards to log uodates.
  23function sf_log_event($release, $version, $build)
  24{
  25	global $wpdb, $current_user;
  26
  27	$now = current_time('mysql');
  28
  29	$sql = "
  30		INSERT INTO ".SFLOG." (user_id, install_date, release_type, version, build)
  31		VALUES (
  32		".$current_user->ID.",
  33		'".$now."',
  34		'".$release."',
  35		'".$version."',
  36		".$build.");";
  37	$wpdb->query($sql);
  38
  39	sf_update_option('sfversion', $version);
  40	sf_update_option('sfbuild', $build);
  41
  42	return;
  43}
  44
  45# Upgrade Database wrapper
  46function sf_upgrade_database($table_name, $column_name, $create_ddl)
  47{
  48	global $wpdb;
  49
  50
  51	foreach ($wpdb->get_col("DESC $table_name", 0) as $column )
  52	{
  53		if ($column == $column_name)
  54		{
  55			return true;
  56		}
  57    }
  58	# didn't find it try to create it.
  59    $q = $wpdb->query($create_ddl);
  60
  61	# we cannot directly tell that whether this succeeded!
  62	foreach ($wpdb->get_col("DESC $table_name", 0) as $column )
  63	{
  64		if ($column == $column_name)
  65		{
  66			return true;
  67		}
  68	}
  69	die(sprintf(__("DATABASE ERROR: Unable to ALTER the %s to create new column %s", "sforum"), $table_name, $column));
  70}
  71
  72function sf_charset()
  73{
  74	global $wpdb;
  75
  76	$charset='';
  77
  78	if ( ! empty($wpdb->charset) )
  79	{
  80		$charset = "DEFAULT CHARSET $wpdb->charset";
  81	} else {
  82		$charset = "DEFAULT CHARSET utf8";
  83	}
  84
  85	return $charset;
  86}
  87
  88# ==========================================
  89#
  90# VERSION SPECIFIC UPDATE/INSTALL ROUTINES
  91#
  92# ==========================================
  93
  94# Called by 1.6 to clear up previous deletion orphans
  95function sf_check_data_integrity()
  96{
  97	global $wpdb;
  98
  99	$topiclist = array();
 100	$postlist = array();
 101
 102	# to be run against a 1.5 install to clean up orphaned posts
 103	# Step 1: Loop through topics in case forum is gone and remove
 104	$topics = $wpdb->get_results("SELECT topic_id, forum_id FROM ".SFTOPICS);
 105	if($topics)
 106	{
 107		foreach($topics as $topic)
 108		{
 109			$test=$wpdb->get_col("SELECT forum_id FROM ".SFFORUMS." WHERE forum_id=".$topic->forum_id);
 110			if(!$test)
 111			{
 112				$topiclist[]=$topic->topic_id;
 113			}
 114		}
 115		if($topiclist)
 116		{
 117			foreach($topiclist as $topic)
 118			{
 119				$wpdb->query("DELETE FROM ".SFTOPICS." WHERE topic_id=".$topic);
 120			}
 121		}
 122	}
 123
 124	# Step 2: Loop through posts in case topic is gone and remove
 125	$posts = $wpdb->get_results("SELECT post_id, topic_id FROM ".SFPOSTS);
 126	if($posts)
 127	{
 128		foreach($posts as $post)
 129		{
 130			$test=$wpdb->get_col("SELECT topic_id FROM ".SFTOPICS." WHERE topic_id=".$post->topic_id);
 131			if(!$test)
 132			{
 133				$postlist[]=$post->post_id;
 134			}
 135		}
 136		if($postlist)
 137		{
 138			foreach($postlist as $post)
 139			{
 140				$wpdb->query("DELETE FROM ".SFPOSTS." WHERE post_id=".$post);
 141			}
 142		}
 143	}
 144	return;
 145}
 146
 147# Called by 1.7 to re-route subscriptions from usermeta to topics
 148function sf_rebuild_subscriptions()
 149{
 150	global $wpdb;
 151
 152	# Build a list of users with subscribe set
 153	$users = $wpdb->get_col("SELECT user_id FROM ".SFUSERMETA." WHERE meta_key='".$wpdb->prefix."sfsubscribe'");
 154	if($users)
 155	{
 156		# clear out the old sfsubcribe values ready for the new
 157		$wpdb->query("DELETE FROM ".SFUSERMETA." WHERE meta_key='".$wpdb->prefix."sfsubscribe'");
 158
 159		foreach($users as $user)
 160		{
 161			# now build the list of topics into which each user has posted
 162			$topics = $wpdb->get_col("SELECT DISTINCT topic_id FROM ".SFPOSTS." WHERE user_id=".$user);
 163			if($topics)
 164			{
 165				foreach($topics as $topic)
 166				{
 167					sf_save_subscription($topic, $user, false);
 168				}
 169			}
 170		}
 171	}
 172	return;
 173}
 174
 175# Called by 2.0 to clean up the topic subs lists where duplicates have crept in
 176function sf_clean_topic_subs()
 177{
 178	global $wpdb;
 179
 180	# build list of topics with subscriptions
 181	$topics = $wpdb->get_results("SELECT topic_id, topic_subs FROM ".SFTOPICS." WHERE topic_subs IS NOT NULL;");
 182	if(!$topics) return;
 183
 184	foreach($topics as $topic)
 185	{
 186		$nvalues = array();
 187		$cvalues = explode('@', $topic->topic_subs);
 188		$nvalues[0] = $cvalues[0];
 189		foreach($cvalues as $cvalue)
 190		{
 191			$notfound = true;
 192			foreach($nvalues as $nvalue)
 193			{
 194				if($nvalue == $cvalue) $notfound = false;
 195			}
 196			if($notfound) $nvalues[]=$cvalue;
 197		}
 198		$nvaluelist = implode('@', $nvalues);
 199		$wpdb->query("UPDATE ".SFTOPICS." SET topic_subs='".$nvaluelist."' WHERE topic_id=".$topic->topic_id);
 200	}
 201	return;
 202}
 203
 204function sf_relocate_avatars()
 205{
 206	global $wpdb;
 207
 208	$basepath='/';
 209	if (is_multisite()) $basepath = '/blogs.dir/' . $wpdb->blogid .'/files/';
 210
 211	$success = 0;
 212	$newpath = SF_STORE_DIR . $basepath . 'forum-avatars';
 213	$oldpath = SF_PLUGIN_DIR . '/styles/avatars';
 214
 215	# check if new folder does not exist - which it shouldn't!
 216	if(!is_dir($newpath))
 217	{
 218		if(!is_writable(SF_STORE_DIR) || !($dir = @mkdir($newpath, 0777)))
 219		{
 220			$success = 1;
 221			return $success;
 222		}
 223		if (!is_writable($newpath))
 224		{
 225			$success = 2;
 226			return $success;
 227		}
 228		if(is_dir($newpath))
 229		{
 230			$avlist = opendir($oldpath);
 231			while (false !== ($file = readdir($avlist)))
 232			{
 233				if (is_file($oldpath.'/'.$file) && $file != "." && $file != "..")
 234				{
 235					if(!file_exists($newpath.'/'.$file))
 236					{
 237						if(@copy($oldpath.'/'.$file, $newpath.'/'.$file) == false)
 238						{
 239							$success = 3;
 240							break;
 241						}
 242					}
 243				}
 244			}
 245			closedir($avlist);
 246		}
 247	}
 248	return $success;
 249}
 250
 251# Called by 2.1 to correct old timestamp in usermeta (sflast)
 252function sf_correct_sflast()
 253{
 254	global $wpdb;
 255
 256	$sql = "UPDATE ".SFUSERMETA." SET meta_value=now() WHERE meta_key = '".$wpdb->prefix."sflast' AND meta_value < DATE_SUB(CURDATE(), INTERVAL 1 YEAR);";
 257	$wpdb->query($sql);
 258	return;
 259}
 260
 261# Called by 2.1 Patch 2 to pre-create last visited date for all existing users who don't have one - Corrects the zero problem
 262function sf_precreate_sflast()
 263{
 264	global $wpdb;
 265
 266	$users = $wpdb->get_results("SELECT ID FROM ".SFUSERS);
 267	if($users)
 268	{
 269		foreach($users as $user)
 270		{
 271			$check = $wpdb->get_var("SELECT umeta_id FROM ".SFUSERMETA." WHERE meta_key='".$wpdb->prefix."sflast' AND user_id=".$user->ID);
 272			if(!$check)
 273			{
 274				sf_set_last_visited($user->ID);
 275			}
 276		}
 277	}
 278	return;
 279}
 280
 281# Called by 3.0 to create forum and topic slugs
 282function sf_create_slugs()
 283{
 284	global $wpdb;
 285
 286	# forums
 287	$records=$wpdb->get_results("SELECT forum_id, forum_name, forum_slug FROM ".SFFORUMS);
 288	if($records)
 289	{
 290		foreach($records as $record)
 291		{
 292			$title = sf_create_slug($record->forum_name, 'forum');
 293			if(empty($title))
 294			{
 295				$title = 'forum-'.$record->forum_id;
 296			}
 297			$wpdb->query("UPDATE ".SFFORUMS." SET forum_slug='".$title."' WHERE forum_id=".$record->forum_id);
 298		}
 299	}
 300
 301	# topics
 302	$records=$wpdb->get_results("SELECT topic_id, topic_name, topic_slug FROM ".SFTOPICS);
 303	if($records)
 304	{
 305		foreach($records as $record)
 306		{
 307			$title = sf_create_slug($record->topic_name, 'topic');
 308			if(empty($title))
 309			{
 310				$title = 'topic-'.$record->topic_id;
 311			}
 312			$wpdb->query("UPDATE ".SFTOPICS." SET topic_slug='".$title."' WHERE topic_id=".$record->topic_id);
 313		}
 314	}
 315	return;
 316}
 317
 318# Called by 3 to ensure all users have a display name set
 319function sf_check_all_display_names()
 320{
 321	global $wpdb;
 322
 323	$users = $wpdb->get_results("SELECT ID, user_login, display_name FROM ".SFUSERS." WHERE display_name=''");
 324	if($users)
 325	{
 326		foreach($users as $user)
 327		{
 328			$wpdb->query("UPDATE ".SFUSERS." SET display_name='".$user->login_name."' WHERE ID=".$user->ID);
 329		}
 330	}
 331	return;
 332}
 333
 334# Called by 3.0 to set up all users into default usergroups
 335# And then set all 3 usergroups to all forums by default
 336function sf_setup_usergroup_data($membergroup, $moderatorgroup, $upgrade, $keys)
 337{
 338	global $wpdb, $current_user;
 339
 340	# if upgrade check if any moderators
 341	$modusers = '';
 342	if ($upgrade) $modusers = get_option('sfmodusers');
 343	if (!empty($modusers))
 344	{
 345		$modusers = explode(';', get_option('sfmodusers'));
 346	}
 347
 348	# get the list of users and do the stuff
 349	$userlist = $wpdb->get_results("SELECT ID FROM ".SFUSERS." ORDER BY display_name ASC;");
 350	if($userlist)
 351	{
 352		foreach($userlist as $user)
 353		{
 354			# check it's not the admin
 355			if($user->ID != $current_user->ID)
 356			{
 357				$target = $membergroup;
 358				# is user a moderator?
 359				if(!empty($modusers))
 360				{
 361					if(in_array($user->ID, $modusers)) $target = $moderatorgroup;
 362				}
 363				$memberships = get_user_meta($user->ID, 'sfusergroup', true);
 364				$memberships[] = $target;
 365				update_user_meta($user->ID, 'sfusergroup', $memberships);
 366			}
 367		}
 368	}
 369
 370	# Now to assign all 3 default usergroups to all forums
 371	if(($keys) && ($upgrade))
 372	{
 373		$forums = $wpdb->get_results("SELECT forum_id FROM ".SFFORUMS.";");
 374		if($forums)
 375		{
 376			foreach($forums as $forum)
 377			{
 378				for($x=0; $x<count($keys); $x++)
 379				{
 380					$group = $keys[$x]['usergroup'];
 381					$perm  = $keys[$x]['permission'];
 382
 383					$sql ="INSERT INTO ".SFPERMISSIONS." (forum_id, usergroup_id, permission_role) ";
 384					$sql.="VALUES (".$forum->forum_id.", ".$group.", ".$perm.");";
 385					$wpdb->query($sql);
 386				}
 387			}
 388		}
 389	}
 390	return;
 391}
 392
 393# called by 3.1 (?) to build new last post columns, topic post count and post index
 394function sf_build_lastposts()
 395{
 396	global $wpdb;
 397
 398	$forums = sf_get_forums_all(true);
 399	if($forums)
 400	{
 401		foreach($forums as $forum)
 402		{
 403			sf_build_forum_index($forum->forum_id);
 404		}
 405	}
 406
 407	$topics = sf_get_topics_all(true);
 408	if($topics)
 409	{
 410		foreach($topics as $topic)
 411		{
 412			sf_build_post_index($topic->topic_id, $topic->topic_slug);
 413		}
 414	}
 415	return;
 416}
 417
 418# called by 3.1 upgrade to build members table
 419# should also now work correctly for individual network sites
 420# sends $editor_column as install and upgrade have different column names (don't ask!)
 421function sf_build_members_table($editor_column, $type, $subphase=0)
 422{
 423	global $wpdb, $current_user;
 424
 425	# get limits for installs
 426	if ($subphase != 0)
 427	{
 428		$limit = " LIMIT 250 OFFSET ".(($subphase - 1) * 250);
 429	}
 430
 431	# select all users
 432	$sql =
 433		"SELECT ID, display_name, user_login FROM ".SFUSERMETA."
 434		 RIGHT JOIN ".SFUSERMETA." ON ".SFUSERMETA.".ID = ".SFUSERMETA.".user_id
 435		 WHERE meta_key = '".$wpdb->prefix."capabilities'
 436		 ORDER BY ID".$limit;
 437	$members = $wpdb->get_results($sql);
 438
 439	if($members)
 440	{
 441		# grab the user groups so we can ensure the users settings are coprrect and groups exist
 442		$ugs = $wpdb->get_col("SELECT usergroup_id FROM ".SFUSERGROUPS);
 443		foreach($members as $member)
 444		{
 445			# Check ID exists and is not zero
 446			if(is_numeric($member->ID) && $member->ID > 0)
 447			{
 448				$usergroups = array();
 449				$usergroups = get_user_meta($member->ID, 'sfusergroup', true);
 450
 451				# user group handling - check groups exist
 452				$newgrouplist=array();
 453				if($usergroups)
 454				{
 455					foreach($usergroups as $group)
 456					{
 457						if(in_array($group, $ugs))
 458						{
 459							$newgrouplist[] = (string) $group;
 460						}
 461					}
 462				} else {
 463					$newgrouplist[] = (string) get_option('sfdefgroup');
 464				}
 465				$usergroups = serialize($newgrouplist);
 466
 467				# admins dont get user groups
 468				# forum admin not set up yet for installs
 469				if ($type == 'upgrade')
 470				{
 471					if (sf_is_forum_admin($member->ID)) $usergroups = '';
 472				} else {
 473					if ($current_user->ID == $member->ID) $usergroups = '';
 474				}
 475
 476				# remaining data items
 477				$display_name = sf_filter_name_save($member->display_name);
 478				if(empty($display_name))
 479				{
 480					$display_name = sf_filter_name_save($member->user_login);
 481				}
 482				$display_name = sf_filter_name_save($display_name);
 483
 484				$buddies = array();
 485				$avatar     = esc_sql(get_user_meta($member->ID, 'sfavatar', true));
 486				$signature  = esc_sql(get_user_meta($member->ID, 'signature', true));
 487				$sigimage   = esc_sql(get_user_meta($member->ID, 'sigimage', true));
 488				$posts      = get_user_meta($member->ID, 'sfposts', true);
 489				$lastvisit  = get_user_meta($member->ID, 'sflast', true);
 490				$subscribe  = get_user_meta($member->ID, 'sfsubscribe', true);
 491				$buddies    = get_user_meta($member->ID, 'sfbuddies', true);
 492				$pm         = sf_get_user_pm_status($member->ID, $newgrouplist);
 493				$moderator	= sf_get_user_mod_status($member->ID, $newgrouplist);
 494
 495				$signature = sf_filter_text_save(trim($signature));
 496				$sigimage = sf_filter_title_save(trim($sigimage));
 497
 498				$buddies    = serialize($buddies);
 499				if(!$posts) $posts = '0';
 500
 501				$editor_setting = get_user_meta($member->ID, 'sfuse_quicktags', true);
 502				if(empty($editor_setting))
 503				{
 504					if($editor_column == 'quicktags') $editor_setting = 0;
 505					if($editor_column == 'editor') $editor_setting = 1;
 506				}
 507
 508				if ($type == 'upgrade')
 509				{
 510					$sql ="INSERT INTO ".SFMEMBERS." (user_id, display_name, pm, moderator, {$editor_column}, usergroups, avatar, signature, sigimage, posts, lastvisit, subscribe, buddies) ";
 511					$sql.="VALUES ({$member->ID}, '{$display_name}', {$pm}, {$moderator}, {$editor_setting}, '{$usergroups}', '{$avatar}', '{$signature}', '{$sigimage}', {$posts}, '{$lastvisit}', '{$subscribe}', '{$buddies}');";
 512				} else {
 513					$sql ="INSERT INTO ".SFMEMBERS." (user_id, display_name, pm, moderator, avatar, signature, sigimage, posts, lastvisit, subscribe, buddies, newposts, checktime, admin, watches, posts_rated, admin_options) ";
 514					$sql.="VALUES ({$member->ID}, '{$display_name}', {$pm}, {$moderator}, '{$avatar}', '{$signature}', '{$sigimage}', {$posts}, now(), '{$subscribe}', '{$buddies}', '', now(), 0, '', '', '');";
 515
 516					$memberships = unserialize($usergroups);
 517					if ($memberships)   # will be empty for admin
 518					{
 519						foreach ($memberships as $membership)
 520						{
 521							sfc_add_membership($membership, $member->ID);
 522						}
 523					}
 524
 525					$useroptions = array();
 526					$useroptions['pmemail'] = true;
 527					$useroptions['editor'] = $editor_setting;
 528					sf_update_member_item($member->ID, 'user_options', $useroptions);
 529				}
 530				$wpdb->query($sql);
 531
 532				# now remove the old userfmeta entries for the current member
 533				$optionlist = array("sfavatar", "sfposts", "sfsubscribe", "sflast", "sfnewposts", "sfchecktime", "sfbuddies", "sfusergroup", "signature", "sigimage", "sfuse_quicktags");
 534				foreach($optionlist as $option)
 535				{
 536					$wpdb->query("DELETE FROM ".$wpdb->prefix."usermeta WHERE meta_key='".$option."' AND user_id=".$member->ID.";");
 537				}
 538			}
 539		}
 540	}
 541	return;
 542}
 543
 544# support function
 545function sf_get_user_pm_status($user_id, $usergroups)
 546{
 547	global $wpdb, $current_user;
 548
 549	if ($current_user->ID == $user_id) return '1';  # if user id is current user then its admin
 550	if (empty($usergroups)) return '0';
 551
 552	foreach ($usergroups as $usergroup)
 553	{
 554		$rids = $wpdb->get_results("SELECT permission_role FROM ".SFPERMISSIONS." WHERE usergroup_id='".$usergroup."'");
 555		foreach ($rids as $rid) {
 556			$role_actions = $wpdb->get_var("SELECT role_actions FROM ".SFROLES." WHERE role_id='".$rid->permission_role."'");
 557			$actions = maybe_unserialize($role_actions);
 558			if ($actions['Can use private messaging'] == 1)
 559			{
 560				return '1';
 561			}
 562		}
 563	}
 564	return '0';
 565}
 566
 567# support function
 568function sf_get_user_mod_status($user_id, $usergroups)
 569{
 570	global $wpdb, $current_user;
 571
 572	if (empty($usergroups)) return '0';
 573
 574	foreach ($usergroups as $usergroup)
 575	{
 576		$mod = $wpdb->get_var("SELECT usergroup_is_moderator FROM ".SFUSERGROUPS." WHERE usergroup_id = ".$usergroup);
 577		if($mod) return '1';
 578	}
 579	return '0';
 580}
 581
 582# support function for adding new role.  use first two params for fixed value.  third param will override second
 583function sf_upgrade_add_new_role($newaction, $perm, $limit_access=false, $mods_only=false, $no_access=false)
 584{
 585	global $wpdb;
 586
 587	$roles = $wpdb->get_results("SELECT * FROM ".SFROLES." ORDER BY role_id");
 588	if ($roles)
 589	{
 590		foreach ($roles as $role)
 591		{
 592			if ($no_access)
 593			{
 594				$perm = 1;
 595				if ($role->role_name == 'No Access')
 596				{
 597					$perm = 0;
 598				}
 599			}
 600			if ($limit_access)
 601			{
 602				$perm = 1;
 603				if ($role->role_name == 'No Access' || $role->role_name == 'Read Only Access')
 604				{
 605					$perm = 0;
 606				}
 607			}
 608			if ($mods_only)
 609			{
 610				$perm = 0;
 611				if ($role->role_name == 'Moderators')
 612				{
 613					$perm = 1;
 614				}
 615			}
 616			$actions = unserialize($role->role_actions);
 617			$actions[$newaction] = $perm;
 618			$actions = maybe_serialize($actions);
 619			$sql = "UPDATE ".SFROLES." SET ";
 620			$sql.= 'role_name="'.$role->role_name.'", ';
 621			$sql.= 'role_desc="'.$role->role_desc.'", ';
 622			$sql.= 'role_actions="'.esc_sql($actions).'" ';
 623			$sql.= "WHERE role_id=".$role->role_id.";";
 624			$wpdb->query($sql);
 625		}
 626	}
 627}
 628
 629# support function for modifying an existing role name
 630function array_change_key_name($orig, $new, &$array)
 631{
 632    if ( isset( $array[$orig] ) )
 633    {
 634        $array[$new] = $array[$orig];
 635        unset( $array[$orig] );
 636    }
 637    return $array;
 638}
 639
 640# support function for modifying an existing role name
 641function sf_modify_rolename($oldrole, $newrole)
 642{
 643	global $wpdb;
 644
 645	$roles = $wpdb->get_results("SELECT * FROM ".SFROLES." ORDER BY role_id");
 646	if ($roles)
 647	{
 648		foreach ($roles as $role)
 649		{
 650			$actions = unserialize($role->role_actions);
 651			$new_actions = array_change_key_name($oldrole, $newrole, $actions);
 652			$actions = maybe_serialize($new_actions);
 653			$sql = "UPDATE ".SFROLES." SET ";
 654			$sql.= 'role_name="'.$role->role_name.'", ';
 655			$sql.= 'role_desc="'.$role->role_desc.'", ';
 656			$sql.= 'role_actions="'.esc_sql($actions).'" ';
 657			$sql.= "WHERE role_id=".$role->role_id.";";
 658			$wpdb->query($sql);
 659		}
 660	}
 661}
 662
 663# function to set up default group permissions
 664function sf_group_def_perms()
 665{
 666	global $wpdb;
 667
 668	# grab the "default" permissions if they exist
 669	$noaccess = $wpdb->get_var("SELECT role_id FROM ".SFROLES." WHERE role_name='No Access'");
 670	if (!$noaccess) $noaccess = -1;
 671	$readonly = $wpdb->get_var("SELECT role_id FROM ".SFROLES." WHERE role_name='Read Only Access'");
 672	if (!$readonly) $readonly = -1;
 673	$standard = $wpdb->get_var("SELECT role_id FROM ".SFROLES." WHERE role_name='Standard Access'");
 674	if (!$standard) $standard = -1;
 675	$moderator = $wpdb->get_var("SELECT role_id FROM ".SFROLES." WHERE role_name='Moderator Access'");
 676	if (!$moderator) $moderator = -1;
 677
 678	$usergroups = $wpdb->get_results("SELECT * FROM ".SFUSERGROUPS);
 679	$groups = $wpdb->get_results("SELECT group_id FROM ".SFGROUPS);
 680	if ($groups && $usergroups)
 681	{
 682		foreach ($groups as $group)
 683		{
 684			foreach ($usergroups as $usergroup)
 685			{
 686				if ($usergroup->usergroup_name == 'Guests')
 687				{
 688					$rid = $readonly;
 689				} else if ($usergroup->usergroup_name == 'Members')
 690				{
 691					$rid = $standard;
 692				} else if ($usergroup->usergroup_name == 'Moderators')
 693				{
 694					$rid = $moderator;
 695				} else {
 696					$rid = $noaccess;
 697				}
 698				$wpdb->query("
 699					INSERT INTO ".SFDEFPERMISSIONS."
 700					(group_id, usergroup_id, permission_role)
 701					VALUES
 702					($group->group_id, $usergroup->usergroup_id, $rid)");
 703			}
 704		}
 705	}
 706}
 707
 708# ====== 4.0.0 ==================================================================================================
 709
 710# Called by 4.0 to create new forum-smileys folder and content
 711function sf_relocate_smileys()
 712{
 713	global $wpdb;
 714
 715	$basepath='/';
 716	if (is_multisite()) $basepath = '/blogs.dir/' . $wpdb->blogid .'/files/';
 717
 718	$success = 0;
 719	$newpath = SF_STORE_DIR . $basepath . 'forum-smileys';
 720	$oldpath = SF_PLUGIN_DIR . '/styles/smileys';
 721
 722	# check if new folder does not exist - which it shouldn't!
 723	if(!is_dir($newpath))
 724	{
 725		if(!is_writable(SF_STORE_DIR) || !($dir = @mkdir($newpath, 0777)))
 726		{
 727			$success = 1;
 728			return $success;
 729		}
 730		if (!is_writable($newpath))
 731		{
 732			$success = 2;
 733			return $success;
 734		}
 735		if(is_dir($newpath))
 736		{
 737			$avlist = opendir($oldpath);
 738			while (false !== ($file = readdir($avlist)))
 739			{
 740				if (is_file($oldpath.'/'.$file) && $file != "." && $file != "..")
 741				{
 742					if(!file_exists($newpath.'/'.$file))
 743					{
 744						if(@copy($oldpath.'/'.$file, $newpath.'/'.$file) == false)
 745						{
 746							$success = 3;
 747							break;
 748						}
 749					}
 750				}
 751			}
 752			closedir($avlist);
 753		}
 754	}
 755	return $success;
 756}
 757
 758# Called by 4.0 to build smiley array
 759function sf_build_base_smileys()
 760{
 761	$smileys = array(
 762	"Confused" => 	array (	0 => "sf-confused.gif",		1 => ":???:",),
 763	"Cool" =>		array (	0 => "sf-cool.gif",			1 => ":cool:"),
 764	"Cry" =>		array (	0 => "sf-cry.gif",			1 => ":cry:",),
 765	"Embarassed" =>	array (	0 => "sf-embarassed.gif",	1 => ":oops:",),
 766	"Frown" =>		array (	0 => "sf-frown.gif",		1 => ":frown:",),
 767	"Kiss" =>		array (	0 => "sf-kiss.gif",			1 => ":kiss:",),
 768	"Laugh" =>		array (	0 => "sf-laugh.gif",		1 => ":lol:",),
 769	"Smile" =>		array (	0 => "sf-smile.gif",		1 => ":smile:",),
 770	"Surprised" =>	array (	0 => "sf-surprised.gif",	1 => ":eek:",),
 771	"Wink" =>		array (	0 => "sf-wink.gif",			1 => ":wink:",),
 772	"Yell" =>		array (	0 => "sf-yell.gif",			1 => ":yell:",)
 773	);
 774
 775	sf_add_sfmeta('smileys', 'smileys', serialize($smileys));
 776
 777	return;
 778}
 779
 780# Called by 4.0 to add tinymce editor toolbar/plugin arrays
 781function sf_build_tinymce_toolbar_arrays()
 782{
 783	$tbar_buttons=array('bold','italic','underline','|','bullist','numlist','|','blockquote','outdent','indent','|','link','unlink','|','undo','redo','forecolor','charmap','|','image');
 784	$tbar_buttons_add=array('media','|','spoiler','ddcode','|','emotions','|','pastetext','pasteword','|','selectall','preview','code','|','spellchecker');
 785	$tbar_plugins=array('inlinepopups','safari','media','preview','emotions','spoiler','ddcode','spellchecker','paste');
 786
 787	$tinymce_toolbar = array();
 788	$tinymce_toolbar['tbar_buttons'] = $tbar_buttons;
 789	$tinymce_toolbar['tbar_buttons_add'] = $tbar_buttons_add;
 790	$tinymce_toolbar['tbar_plugins'] = $tbar_plugins;
 791
 792	sf_add_sfmeta('tinymce_toolbar', 'default', serialize($tinymce_toolbar));
 793	sf_add_sfmeta('tinymce_toolbar', 'user', serialize($tinymce_toolbar));
 794
 795	return;
 796}
 797
 798# Called by 4.0 and install to build memberships table
 799function sf_build_memberships_table()
 800{
 801	global $wpdb;
 802
 803	$users = $wpdb->get_results("SELECT user_id, usergroups FROM ".SFMEMBERS);
 804	if ($users)
 805	{
 806		foreach ($users as $user)
 807		{
 808			$memberships = maybe_unserialize($user->usergroups);
 809			if ($memberships)
 810			{
 811				for ($x=0; $x<count($memberships); $x++)
 812				{
 813					$sql ="INSERT INTO ".SFMEMBERSHIPS." (user_id, usergroup_id) ";
 814					$sql.="VALUES ('".$user->user_id."', '".$memberships[$x]."');";
 815					$wpdb->query($sql);
 816				}
 817			}
 818		}
 819	}
 820}
 821
 822# Called by 4.0 to create pm message slugs
 823function sf_create_message_slugs()
 824{
 825	global $wpdb;
 826
 827	# remove all single quotes
 828	$messages = $wpdb->get_results("SELECT message_id, title FROM ".SFMESSAGES);
 829	if($messages)
 830	{
 831		foreach($messages as $message)
 832		{
 833			$title = $message->title;
 834			$title = str_replace ("'", "", $title);
 835			$wpdb->query("UPDATE ".SFMESSAGES." SET title = '".$title."' WHERE message_id=".$message->message_id);
 836		}
 837	}
 838
 839	# perform slug creation
 840	$found = true;
 841	while($found)
 842	{
 843		$message = sf_grab_slugless_messages();
 844		if($message)
 845		{
 846			$slug = sf_create_slug($message->title, 'pm');
 847			# if not created force change of title
 848			if($slug)
 849			{
 850				$wpdb->query("UPDATE ".SFMESSAGES." SET message_slug = '".$slug."' WHERE title='".$message->title."';");
 851			} else {
 852				$wpdb->query("UPDATE ".SFMESSAGES." SET title = 'Untitled' WHERE message_id = ".$message->message_id);
 853			}
 854		} else {
 855			$found = false;
 856		}
 857	}
 858
 859	return;
 860}
 861
 862function sf_grab_slugless_messages()
 863{
 864	global $wpdb;
 865
 866	return $wpdb->get_row("SELECT * FROM ".SFMESSAGES." WHERE message_slug='' LIMIT 1;");
 867}
 868
 869# ====== 4.0.1 ==================================================================================================
 870
 871# Called by 4.0.1 to add blockquote to tinymce toolbar
 872function sf_update_tmtoolbar_blockquote()
 873{
 874	$tbrow = array();
 875	$tbrow[0]='default';
 876	$tbrow[1]='user';
 877	foreach($tbrow as $tb)
 878	{
 879		$tbmeta = sf_get_sfmeta('tinymce_toolbar', $tb);
 880		$buttons = unserialize($tbmeta[0]['meta_value']);
 881		$newbuttons = array();
 882
 883		$found = false;
 884
 885		# double check not already there...
 886		foreach($buttons['tbar_buttons'] as $button)
 887		{
 888			if($button == 'blockquote') $found=true;
 889		}
 890
 891		if(!$found)
 892		{
 893			foreach($buttons['tbar_buttons'] as $button)
 894			{
 895				if($button == 'outdent')
 896				{
 897					$newbuttons[]='blockquote';
 898				}
 899				$newbuttons[]=$button;
 900			}
 901			$buttons['tbar_buttons']=$newbuttons;
 902			sf_update_sfmeta('tinymce_toolbar', $tb, serialize($buttons), $tbmeta[0]['meta_id']);
 903		}
 904	}
 905	return;
 906}
 907
 908# ====== 4.0.2 ==================================================================================================
 909
 910function sf_update_membership_cleanup()
 911{
 912	global $wpdb;
 913
 914	#remove any duplicate memberships
 915	$memberships = $wpdb->get_results("SELECT * FROM ".SFMEMBERSHIPS);
 916	if ($memberships)
 917	{
 918		$test = array();
 919		foreach ($memberships as $membership)
 920		{
 921			if ($test[$membership->usergroup_id][$membership->user_id] == 1)
 922			{
 923				$wpdb->query("DELETE FROM ".SFMEMBERSHIPS." WHERE membership_id=".$membership->membership_id);
 924			} else {
 925				$test[$membership->usergroup_id][$membership->user_id] = 1;
 926			}
 927		}
 928	}
 929}
 930
 931
 932
 933# ====== 4.1 ==================================================================================================
 934
 935# Called by 4.1 to create and populate the user options table with the old editor column
 936function sf_create_user_options()
 937{
 938	global $wpdb;
 939
 940	$users = $wpdb->get_results("SELECT user_id, editor FROM ".SFMEMBERS." ORDER BY user_id");
 941	if ($users)
 942	{
 943		foreach ($users as $user)
 944		{
 945			# get user options if they exist
 946			$useroptions = sf_get_member_item($user->user_id, 'user_options');
 947			# move editor column to new users options column
 948			if(empty($user->editor) ? $editor=1 : $editor=$user->editor);
 949			$useroptions['editor'] = $editor;
 950			sf_update_member_item($user->user_id, 'user_options', $useroptions);
 951		}
 952	}
 953
 954	return;
 955}
 956
 957# Called by 4.1 to populate sfmeta for default usergroups
 958function sf_create_usergroup_meta($members)
 959{
 960	global $wp_roles;
 961
 962	$roles = array_keys($wp_roles->role_names);
 963	if ($roles)
 964	{
 965		foreach ($roles as $role)
 966		{
 967			sf_add_sfmeta('default usergroup', $role, $members); # initally set each role to members usergroup
 968		}
 969	}
 970}
 971
 972# Called by 4.1 to create new count and info fields
 973function sf_build_41_counts()
 974{
 975	global $wpdb;
 976
 977	# start with post count in forums
 978	$forums = $wpdb->get_results("SELECT forum_id FROM ".SFFORUMS);
 979	if($forums)
 980	{
 981		foreach($forums as $forum)
 982		{
 983			$posts = $wpdb->get_var("SELECT COUNT(post_id) FROM ".SFPOSTS." WHERE forum_id=".$forum->forum_id);
 984			$wpdb->query("UPDATE ".SFFORUMS." SET post_count = ".$posts." WHERE  forum_id=".$forum->forum_id);
 985		}
 986	}
 987}
 988
 989# Called by 4.1 to change topic subscriptions and watches, and post ratings to be stored in serialized arrays
 990function sf_serialize_subs_watches_ratings()
 991{
 992	global $wpdb;
 993
 994	# do sftopics table watches and subscriptions
 995	$topics = $wpdb->get_results("SELECT topic_id, topic_subs, topic_watches FROM ".SFTOPICS." WHERE topic_subs is not null OR topic_watches is not null");
 996	if ($topics)
 997	{
 998		foreach ($topics as $topic)
 999		{
1000			# make sure they arent already serialized, ie maybe ugprade already run once?
1001			if ($topic->topic_subs && !is_serialized($topic->topic_subs))
1002			{
1003				$subs = explode('@', $topic->topic_subs);
1004				$subs = serialize($subs);
1005				$wpdb->query("UPDATE ".SFTOPICS." SET topic_subs = '".$subs."' WHERE  topic_id=".$topic->topic_id);
1006			}
1007
1008			if ($topic->topic_watches && !is_serialized($topic->topic_watches))
1009			{
1010				$watches = explode('@', $topic->topic_watches);
1011				$watches = serialize($watches);
1012				$wpdb->query("UPDATE ".SFTOPICS." SET topic_watches = '".$watches."' WHERE  topic_id=".$topic->topic_id);
1013			}
1014		}
1015	}
1016
1017	# do members table watches and subscriptions
1018	$members = $wpdb->get_results("SELECT user_id, subscribe, watches FROM ".SFMEMBERS." WHERE subscribe is not null OR watches is not null");
1019	if ($members)
1020	{
1021		foreach ($members as $member)
1022		{
1023			if ($member->subscribe && !is_serialized($member->subscribe))
1024			{
1025				$subs = explode('@', $member->subscribe);
1026				$subs = serialize($subs);
1027				$wpdb->query("UPDATE ".SFMEMBERS." SET subscribe = '".$subs."' WHERE  user_id=".$member->user_id);
1028			}
1029
1030			if ($member->watches && !is_serialized($member->watches))
1031			{
1032				$watches = explode('@', $member->watches);
1033				$watches = serialize($watches);
1034				$wpdb->query("UPDATE ".SFMEMBERS." SET watches = '".$watches."' WHERE  user_id=".$member->user_id);
1035			}
1036		}
1037	}
1038
1039	# do members table post ratings
1040	$members = $wpdb->get_results("SELECT user_id, posts_rated FROM ".SFMEMBERS." WHERE posts_rated is not null");
1041	if ($members)
1042	{
1043		foreach ($members as $member)
1044		{
1045			if ($member->posts_rated && !is_serialized($member->posts_rated))
1046			{
1047				$ratings = explode('@', $member->posts_rated);
1048				$ratings = serialize($ratings);
1049				$wpdb->query("UPDATE ".SFMEMBERS." SET posts_rated = '".$ratings."' WHERE  user_id=".$member->user_id);
1050			}
1051		}
1052	}
1053}
1054
1055# Called by 4.1.0 to add spoiler to tinymce toolbar
1056function sf_update_tmtoolbar_spoiler()
1057{
1058	$tbrow = array();
1059	$tbrow[0]='default';
1060	$tbrow[1]='user';
1061	foreach($tbrow as $tb)
1062	{
1063		$tbmeta = sf_get_sfmeta('tinymce_toolbar', $tb);
1064		$buttons = unserialize($tbmeta[0]['meta_value']);
1065		$newbuttons = array();
1066
1067		$found = false;
1068
1069		# double check not already there...
1070		foreach($buttons['tbar_buttons_add'] as $button)
1071		{
1072			if($button == 'spoiler') $notfound=true;
1073		}
1074
1075		if(!$found)
1076		{
1077			foreach($buttons['tbar_buttons_add'] as $button)
1078			{
1079				if($button == 'ddcode')
1080				{
1081					$newbuttons[]='spoiler';
1082				}
1083				$newbuttons[]=$button;
1084			}
1085			$buttons['tbar_buttons_add']=$newbuttons;
1086
1087			$buttons['tbar_plugins'][]='spoiler';
1088
1089			sf_update_sfmeta('tinymce_toolbar', $tb, serialize($buttons), $tbmeta[0]['meta_id']);
1090		}
1091	}
1092	return;
1093}
1094
1095# Called by 4.1.0 to add SPF Manage Toolbox & Configuration caps to all admins with Options caps
1096function sf_update_admin_toolbox()
1097{
1098	global $wpdb;
1099
1100	$admins = $wpdb->get_col("SELECT user_id FROM ".SFMEMBERS." WHERE admin = 1");
1101	$metakey = $wpdb->prefix.'capabilities';
1102	if($admins)
1103	{
1104		foreach($admins as $admin)
1105		{
1106			$caps = get_user_meta($admin, $metakey, true);
1107			if($caps['SPF Manage Options'] == 1)
1108			{
1109				$caps['SPF Manage Toolbox'] = 1;
1110				$caps['SPF Manage Configuration'] = 1;
1111			} else {
1112				$caps['SPF Manage Toolbox'] = 0;
1113				$caps['SPF Manage Configuration'] = 0;
1114			}
1115			update_user_meta($admin, $metakey, $caps);
1116		}
1117	}
1118	return;
1119}
1120
1121# Called by 4.1.0 to clean up and serialise icon text
1122function sf_upgrade_icontext()
1123{
1124	$icons = get_option('sfshowicon');
1125	$list = explode('@', $icons);
1126
1127	$newicons = array();
1128	foreach($list as $i)
1129	{
1130		$temp=explode(';', $i);
1131		if($temp[0] != 'Moderation Queue' && $temp[0] != 'Close New Post List')
1132		{
1133			$newicons[$temp[0]] = $temp[1];
1134		}
1135	}
1136	update_option('sfshowicon', $newicons);
1137	return;
1138}
1139
1140# Called by 4.1.0 to clean up and serialise avatar options
1141function sf_upgrade_avatar_options()
1142{
1143	# if avatar options already serialized, bail since must have already been done
1144	if (is_serialized(get_option('sfavatars'))) return;
1145
1146	# convert avatar options
1147	$sfoptions = array();
1148	$sfoptions['sfshowavatars'] = get_option('sfshowavatars');
1149	$sfoptions['sfavataruploads'] = get_option('sfavataruploads');
1150	$sfoptions['sfgmaxrating'] = get_option('sfgmaxrating');
1151	$sfoptions['sfavatarsize'] = get_option('sfavatarsize');
1152
1153	$wpavatar = get_option('sfwpavatar');
1154	$gravatar = get_option('sfgravatar');
1155	if ($wpavatar)
1156	{
1157		$sfoptions['sfavatarpriority'] = array(1, 0, 2, 3);  # wp, gravatar, upload, spf
1158	} else if ($gravatar) {
1159		$sfoptions['sfavatarpriority'] = array(0, 2, 3, 1);  # gravatar, upload, spf, wp
1160	} else {
1161		$sfoptions['sfavatarpriority'] = array(2, 3, 0, 1);  # upload, spf, gravatar, wp
1162	}
1163
1164	# add the new serialized options
1165	add_option('sfavatars', $sfoptions);
1166
1167	return;
1168}
1169
1170# Called by 4.1.0 to serialise custom field data
1171function sf_update_custom_fields()
1172{
1173	$cfields = sf_get_sfmeta('custom_field');
1174	if ($cfields && !is_serialized($cfields))
1175	{
1176		foreach ($cfields as $info)
1177		{
1178			$field = array();
1179			$fields['type'] = $info['meta_value'];
1180
1181			$cfname = sf_create_slug($info['meta_key'], 'custom');
1182			$cfname = preg_replace('|[^a-z0-9_]|i', '', $cfname);
1183
1184			sf_update_sfmeta('custom_field', $cfname, serialize($fields), $info['meta_id']);
1185		}
1186	}
1187	return;
1188}
1189
1190# Called by 4.1.0 to convert exiting user custom field data
1191function sf_convert_custom_profile_fields()
1192{
1193	global $wpdb;
1194
1195	# see if any custom fields that need converting
1196	$cfields = sf_get_sfmeta('custom_field');
1197	if ($cfields && !is_serialized($cfields))
1198	{
1199		foreach ($cfields as $x => $cfield)
1200		{
1201			$sql = "SELECT user_id, meta_value FROM ".SFUSERMETA." WHERE meta_key='sfcustomfield".$x."'";
1202			$usermetas = $wpdb->get_results($sql);
1203			if ($usermetas)
1204			{
1205				foreach ($usermetas as $usermeta)
1206				{
1207					# delete old usermeta
1208					delete_user_meta($usermeta->user_id, 'sfcustomfield'.$x);
1209
1210					# replace the usermeta
1211					update_user_meta($usermeta->user_id, $cfield['meta_key'], $usermeta->meta_value);
1212				}
1213			}
1214		}
1215	}
1216	return;
1217}
1218
1219function sf_upgrade_members_pm()
1220{
1221	global $wpdb;
1222
1223	$users = $wpdb->get_results("SELECT user_id, user_options FROM ".SFMEMBERS);
1224	foreach ($users as $user)
1225	{
1226		$useroptions = unserialize($user->user_options);
1227		$useroptions['pmemail'] = 1;
1228		$useroptions = serialize($useroptions);
1229		$wpdb->query("UPDATE ".SFMEMBERS." SET user_options='".$useroptions."' WHERE user_id=".$user->user_id);
1230	}
1231}
1232
1233function sf_modify_admin_cap($curcap, $newcap)
1234{
1235	global $wpdb;
1236
1237	$admins = $wpdb->get_results("SELECT user_id FROM ".SFMEMBERS." WHERE admin=1");
1238	foreach ($admins as $admin)
1239	{
1240		$user = new WP_User($admin->user_id);
1241		if ($user->has_cap($curcap))
1242		{
1243			$user->remove_cap($curcap);
1244			$user->add_cap($newcap);
1245		}
1246	}
1247}
1248
1249function sf_move_options()
1250{
1251	global $wpdb;
1252
1253	$sql = "
1254		CREATE TABLE IF NOT EXISTS ".SFOPTIONS." (
1255		option_id bigint(20) unsigned NOT NULL auto_increment,
1256		option_name varchar(64) NOT NULL default '',
1257		option_value longtext NOT NULL,
1258		PRIMARY KEY (option_name),
1259		KEY option_id (option_id)
1260		) ENGINE=MyISAM ".sf_charset().";";
1261	$wpdb->query($sql);
1262
1263	$optionlist = array(
1264		'sfversion',
1265		'sfbuild',
1266		'sfpage',
1267		'sfslug',
1268		'sfsmilies',
1269		'sfuninstall',
1270		'sfdates',
1271		'sftimes',
1272		'sfshowavatars',
1273		'sfshowicon',
1274		'sfavatarsize',
1275		'sfavatars',
1276		'sfpermalink',
1277		'sfextprofile',
1278		'sfrsscount',
1279		'sfrsswords',
1280		'sfgravatar',
1281		'sfuseannounce',
1282		'sfannouncecount',
1283		'sfannouncehead',
1284		'sfannounceauto',
1285		'sfannouncetime',
1286		'sfannouncetext',
1287		'sfannouncelist',
1288		'sflockdown',
1289		'sfimgenlarge',
1290		'sfthumbsize',
1291		'sfmail',
1292		'sfnewusermail',
1293		'sfbadwords',
1294		'sfreplacementwords',
1295		'sfpm',
1296		'sfcustom',
1297		'sfeditormsg',
1298		'sfpostmsg',
1299		'sfcheck',
1300		'sfstyle',
1301		'sflogin',
1302		'sfadminsettings',
1303		'sfauto',
1304		'sfpmemail',
1305		'sfpmmax',
1306		'sfpostpaging',
1307		'sfeditor',
1308		'sfsmileys',
1309		'sfpostratings',
1310		'sfavataruploads',
1311		'sfprivatemessaging',
1312		'sfseo',
1313		'sfsigimagesize',
1314		'sfmemberlistperms',
1315		'sfgmaxrating',
1316		'sfcbexclusions',
1317		'sfshowmemberlist',
1318		'sfpostlinking',
1319		'sfwpavatar',
1320		'sfcheckformember',
1321		'sfsupport',
1322		'sfcontrols',
1323		'sfmetatags',
1324		'sfacolours',
1325		'sfallRSSurl',
1326		'sfautoupdate',
1327		'sfblockadmin',
1328		'sfconfig',
1329		'sfdisplay',
1330		'sffilters',
1331		'sfsinglemembership',
1332		'sfguests',
1333		'sfprofile',
1334		'sfuploads',
1335		'sfStartUpgrade',
1336		'sfforceupgrade',
1337		'sfzone'
1338	);
1339
1340	foreach( $optionlist as $option)
1341	{
1342		$sfopt = sf_opcheck(get_option($option));
1343		sf_add_option($option, $sfopt);
1344		delete_option($option);
1345	}
1346
1347	return;
1348}
1349
1350function sf_generate_member_feedkeys()
1351{
1352    global $wpdb;
1353
1354    $members = $wpdb->get_results("SELECT user_id FROM ".SFMEMBERS);
1355    foreach ($members as $member)
1356    {
1357        # generate a pseudo-random UUID according to RFC 4122
1358        $key = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
1359                    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
1360                    mt_rand( 0, 0x0fff ) | 0x4000,
1361                    mt_rand( 0, 0x3fff ) | 0x8000,
1362                    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
1363        $wpdb->query("UPDATE ".SFMEMBERS." SET feedkey = '".$key."' WHERE user_id=".$member->user_id);
1364    }
1365
1366    return;
1367}
1368
1369# 4.2 - Upgrade postmeta records to new blog linking table
1370function sf_upgrade_bloglinks_table()
1371{
1372	global $wpdb;
1373
1374	$links = $wpdb->get_results("SELECT post_id, meta_value FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'forumlink'");
1375	if($links)
1376	{
1377		foreach($links as $link)
1378		{
1379			$key=explode('@', $link->meta_value);
1380			if((isset($key[0]) && !empty($key[0])) && (isset($key[1]) && !empty($key[1])))
1381			{
1382				$postid=$link->post_id;
1383				$forumid=$key[0];
1384				$topicid=$key[1];
1385				$sql="INSERT INTO ".SFLINKS." (post_id, forum_id, topic_id) VALUES (".$postid.", ".$forumid.", '".$topicid."');";
1386				$wpdb->query($sql);
1387			}
1388		}
1389		$wpdb->query("DELETE FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'forumlink'");
1390	}
1391	return;
1392}
1393
1394# 4.2 - new members table building for installs
1395function sf_install_members_table($subphase)
1396{
1397	global $wpdb, $current_user;
1398
1399	# get limits for installs
1400	if ($subphase != 0)
1401	{
1402		$limit = " LIMIT 250 OFFSET ".(($subphase - 1) * 250);
1403	}
1404
1405	# select all users
1406	$sql = "SELECT ID FROM ".$wpdb->prefix."users".$limit;
1407	$members = $wpdb->get_results($sql);
1408
1409	if ($members)
1410	{
1411		foreach($members as $member)
1412		{
1413			# Check ID exists and is not zero
1414			if(is_numeric($member->ID) && $member->ID > 0)
1415			{
1416                sf_create_member_data($member->ID);
1417
1418                # for the admin installer, remove any usergroup membership added by create member function
1419				if ($current_user->ID == $member->ID)
1420                {
1421                    $wpdb->query("DELETE FROM ".$wpdb->prefix."sfmemberships WHERE user_id=".$member->ID);
1422        			sf_update_member_item($member->ID, 'pm', 1);
1423                }
1424			}
1425		}
1426	}
1427	return;
1428}
1429
1430# 4.2 - add additional admin colors
1431function sf_update_admin_colors()
1432{
1433	global $wpdb;
1434
1435   	# get admins that have custom colors
1436	$sql = "SELECT user_id FROM ".SFUSERMETA." WHERE meta_key='sfadmincolours'";
1437	$admins = $wpdb->get_results($sql);
1438    if ($admins)
1439    {
1440        foreach ($admins as $admin)
1441        {
1442            $sfacolors = sf_opcheck(get_user_meta($admin->user_id, 'sfadmincolours', true));
1443        	$sfacolors['submitbg'] = '27537A';
1444        	$sfacolors['submitbgt'] = 'FFFFFF';
1445           	update_user_meta($admin->user_id, 'sfadmincolours', $sfacolors);
1446        }
1447    }
1448}
1449
1450# 4.2 - move admin color options to admin options
1451function sf_move_admin_colors()
1452{
1453	global $wpdb;
1454
1455   	# get admins that have custom colors
1456	$sql = "SELECT user_id FROM ".SFUSERMETA." WHERE meta_key='sfadmincolours'";
1457	$admins = $wpdb->get_results($sql);
1458    if ($admins)
1459    {
1460        foreach ($admins as $admin)
1461        {
1462            # get current admin options
1463            $curdminoptions = sf_get_member_list($admin->user_id, 'admin_options');
1464            $newadminoptions = $curdminoptions['admin_options'];
1465
1466            # add in custom colors
1467        	$newadminoptions['colors'] = sf_opcheck(get_user_meta($admin->user_id, 'sfadmincolours', true));
1468            if (!$newadminoptions['colors']) $newadminoptions['colors'] = sf_get_option('sfacolours');
1469
1470            # save new admin options with colors
1471        	sf_update_member_item($admin->user_id, 'admin_options', $newadminoptions);
1472
1473            # delete old usermeta colors
1474           	delete_user_meta($admin->user_id, 'sfadmincolours');
1475        }
1476    }
1477}
1478
1479# 4.3 - move sig images into sig field and clean up
1480function sf_convert_sig_images()
1481{
1482	global $wpdb;
1483
1484    # remove the permission
1485	$roles = $wpdb->get_results("SELECT * FROM ".SFROLES." ORDER BY role_id");
1486	if ($roles)
1487	{
1488		foreach ($roles as $role)
1489		{
1490			$actions = unserialize($role->role_actions);
1491			unset($actions['Can use images in signatures']);
1492			$actions = maybe_serialize($actions);
1493			$sql = "UPDATE ".SFROLES." SET ";
1494			$sql.= 'role_name="'.$role->role_name.'", ';
1495			$sql.= 'role_desc="'.$role->role_desc.'", ';
1496			$sql.= 'role_actions="'.esc_sql($actions).'" ';
1497			$sql.= "WHERE role_id=".$role->role_id.";";
1498			$wpdb->query($sql);
1499		}
1500	}
1501
1502    # convert sig images to beginning of sig
1503    $sigs = $wpdb->get_results("SELECT user_id, signature, sigimage FROM ".SFMEMBERS." WHERE sigimage != '' AND sigimage != 'NULL'");
1504    if ($sigs)
1505    {
1506        foreach ($sigs as $sig)
1507        {
1508            $newsig = '<img src="'.$sig->sigimage.'" />'.addslashes($sig->signature);
1509            $wpdb->query("UPDATE ".SFMEMBERS." SET signature = '".$newsig."' WHERE user_id=".$sig->user_id);
1510        }
1511    }
1512
1513    # now remove sigimage column and clean up any usermeta stuff left over
1514	$wpdb->query("ALTER TABLE ".SFMEMBERS." DROP sigimage;");
1515	$wpdb->query("DELETE FROM ".SFUSERMETA." WHERE meta_key = 'signature' OR meta_key = 'sigimage'");
1516}
1517
1518# 4.3 - conver block admin levels to accessed roles
1519function sf_convert_block_admin()
1520{
1521	global $wp_roles;
1522
1523    # init allowed roles
1524    $sfblock['blockroles'] = array();
1525
1526    # find the min level for admin access
1527	$sfblock = sf_get_option('sfblockadmin');
1528    if ($sfblock && !empty($sfblock['blockrole']))
1529    {
1530        $minrole = get_role($sfblock['blockrole']);
1531        $minlevel = 0;
1532        foreach(array_keys($minrole->capabilities) as $cap)
1533        {
1534            preg_match('/^level_(10|[0-9])$/i', $cap, $matches);
1535            if ($matches[1] > $minlevel) $minlevel = $matches[1];
1536        }
1537
1538        # need to find level of each wp role
1539        $roles = array_keys($wp_roles->role_names);
1540        if ($roles)
1541        {
1542            foreach ($roles as $role)
1543            {
1544                $roleobj = $wp_roles->get_role($role);
1545                $rolelevel = 0;
1546                foreach(array_keys($roleobj->capabilities) as $cap)
1547                {
1548                    preg_match('/^level_(10|[0-9])$/i', $cap, $matches);
1549                    if ($matches[1] > $rolelevel) $rolelevel = $matches[1];
1550                }
1551
1552                # does the role current have access?
1553                 if ($rolelevel >= $minlevel)
1554                 {
1555                    $sfblock['blockroles'][$role] = 1;
1556                 } else {
1557                    $sfblock['blockroles'][$role] = 0;
1558                 }
1559            }
1560        }
1561
1562        # remove the old blockrole setting
1563        unset($sfblock['blockrole']);
1564    }
1565
1566    # always allow admin
1567    $sfblock['blockroles']['administrator'] = true;
1568
1569    # save new blockrole access list
1570	sf_update_option('sfblockadmin', $sfblock);
1571}
1572
1573# 4.3 - add user id to new user list
1574function sf_upgrade_new_user_list()
1575{
1576	global $wpdb;
1577
1578	$sfcontrols = sf_get_option('sfcontrols');
1579    if ($sfcontrols['newuserlist'])
1580    {
1581        $newlist = array();
1582        foreach ($sfcontrols['newuserlist'] as $index => $user)
1583        {
1584            $newlist[$index]['id'] = sf_get_user_id($user);
1585            $newlist[$index]['name'] = $user;
1586        }
1587        $sfcontrols['newuserlist'] = $newlist;
1588
1589        # save update new user list
1590        sf_update_option('sfcontrols', $sfcontrols);
1591    }
1592}
1593
1594?>