includes/functions_convert.php
author indvdum (gotoindvdum[at]gmail[dot]com)
Wed, 07 Mar 2012 16:41:10 +0400
changeset 0 ceef6d64c21d
permissions -rw-r--r--
Added phpBB-3.0.10
     1 <?php
     2 /**
     3 *
     4 * @package install
     5 * @version $Id$
     6 * @copyright (c) 2006 phpBB Group
     7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
     8 *
     9 */
    10 
    11 /**
    12 * @ignore
    13 */
    14 if (!defined('IN_PHPBB'))
    15 {
    16 	exit;
    17 }
    18 
    19 /**
    20 * Default avatar width/height
    21 * @ignore
    22 */
    23 define('DEFAULT_AVATAR_X', 80);
    24 define('DEFAULT_AVATAR_Y', 80);
    25 
    26 // Global functions - all functions can be used by convertors
    27 
    28 // SIMPLE FUNCTIONS
    29 
    30 /**
    31 * Return the preceding value
    32 */
    33 function dec($var)
    34 {
    35 	return --$var;
    36 }
    37 
    38 /**
    39 * Return the next value
    40 */
    41 function inc($var)
    42 {
    43 	return ++$var;
    44 }
    45 
    46 /**
    47 * Return whether the value is positive
    48 */
    49 function is_positive($n)
    50 {
    51 	return ($n > 0) ? 1 : 0;
    52 }
    53 
    54 /**
    55 * Boolean inverse of the value
    56 */
    57 function not($var)
    58 {
    59 	return ($var) ? 0 : 1;
    60 }
    61 
    62 /**
    63 * Convert a textual value to it's equivalent boolean value
    64 *
    65 * @param string $str String to convert (converts yes, on, y, 1 and true to boolean true)
    66 * @return boolean The equivalent value
    67 */
    68 function str_to_bool($str)
    69 {
    70 	$str = strtolower($str);
    71 	return ($str == 'yes' || $str == 'on' || $str == 'y' || $str == 'true' || $str == '1') ? true : false;
    72 }
    73 
    74 /**
    75 * Function to mimic php's empty() function (it is the same)
    76 */
    77 function is_empty($mixed)
    78 {
    79 	return empty($mixed);
    80 }
    81 
    82 /**
    83 * Convert the name of a user's primary group to the appropriate equivalent phpBB group id
    84 *
    85 * @param string $status The name of the group
    86 * @return int The group_id corresponding to the equivalent group
    87 */
    88 function str_to_primary_group($status)
    89 {
    90 	switch (ucfirst(strtolower($status)))
    91 	{
    92 		case 'Administrator':
    93 			return get_group_id('administrators');
    94 		break;
    95 
    96 		case 'Super moderator':
    97 		case 'Global moderator':
    98 		case 'Moderator':
    99 			return get_group_id('global_moderators');
   100 		break;
   101 
   102 		case 'Guest':
   103 		case 'Anonymous':
   104 			return get_group_id('guests');
   105 		break;
   106 
   107 		default:
   108 			return get_group_id('registered');
   109 		break;
   110 	}
   111 }
   112 
   113 /**
   114 * Convert a boolean into the appropriate phpBB constant indicating whether the item is locked
   115 */
   116 function is_item_locked($bool)
   117 {
   118 	return ($bool) ? ITEM_LOCKED : ITEM_UNLOCKED;
   119 }
   120 
   121 /**
   122 * Convert a value from days to seconds
   123 */
   124 function days_to_seconds($days)
   125 {
   126 	return ($days * 86400);
   127 }
   128 
   129 /**
   130 * Determine whether a user is anonymous and return the appropriate new user_id
   131 */
   132 function is_user_anonymous($user_id)
   133 {
   134 	return ($user_id > ANONYMOUS) ? $user_id : ANONYMOUS;
   135 }
   136 
   137 /**
   138 * Generate a key value based on existing values
   139 *
   140 * @param int $pad Amount to add to the maximum value
   141 * @return int Key value
   142 */
   143 function auto_id($pad = 0)
   144 {
   145 	global $auto_id, $convert_row;
   146 
   147 	if (!empty($convert_row['max_id']))
   148 	{
   149 		return $convert_row['max_id'] + $pad;
   150 	}
   151 
   152 	return $auto_id + $pad;
   153 }
   154 
   155 /**
   156 * Convert a boolean into the appropriate phpBB constant indicating whether the user is active
   157 */
   158 function set_user_type($user_active)
   159 {
   160 	return ($user_active) ? USER_NORMAL : USER_INACTIVE;
   161 }
   162 
   163 /**
   164 * Convert a value from minutes to hours
   165 */
   166 function minutes_to_hours($minutes)
   167 {
   168 	return ($minutes / 3600);
   169 }
   170 
   171 /**
   172 * Return the group_id for a given group name
   173 */
   174 function get_group_id($group_name)
   175 {
   176 	global $db, $group_mapping;
   177 
   178 	if (empty($group_mapping))
   179 	{
   180 		$sql = 'SELECT group_name, group_id
   181 			FROM ' . GROUPS_TABLE;
   182 		$result = $db->sql_query($sql);
   183 
   184 		$group_mapping = array();
   185 		while ($row = $db->sql_fetchrow($result))
   186 		{
   187 			$group_mapping[strtoupper($row['group_name'])] = (int) $row['group_id'];
   188 		}
   189 		$db->sql_freeresult($result);
   190 	}
   191 
   192 	if (!sizeof($group_mapping))
   193 	{
   194 		add_default_groups();
   195 		return get_group_id($group_name);
   196 	}
   197 
   198 	if (isset($group_mapping[strtoupper($group_name)]))
   199 	{
   200 		return $group_mapping[strtoupper($group_name)];
   201 	}
   202 
   203 	return $group_mapping['REGISTERED'];
   204 }
   205 
   206 /**
   207 * Generate the email hash stored in the users table
   208 *
   209 * Note: Deprecated, calls should directly go to phpbb_email_hash()
   210 */
   211 function gen_email_hash($email)
   212 {
   213 	return phpbb_email_hash($email);
   214 }
   215 
   216 /**
   217 * Convert a boolean into the appropriate phpBB constant indicating whether the topic is locked
   218 */
   219 function is_topic_locked($bool)
   220 {
   221 	return (!empty($bool)) ? ITEM_LOCKED : ITEM_UNLOCKED;
   222 }
   223 
   224 /**
   225 * Generate a bbcode_uid value
   226 */
   227 function make_uid($timestamp)
   228 {
   229 	static $last_timestamp, $last_uid;
   230 
   231 	if (empty($last_timestamp) || $timestamp != $last_timestamp)
   232 	{
   233 		$last_uid = substr(base_convert(unique_id(), 16, 36), 0, BBCODE_UID_LEN);
   234 	}
   235 	$last_timestamp = $timestamp;
   236 	return $last_uid;
   237 }
   238 
   239 
   240 /**
   241 * Validate a website address
   242 */
   243 function validate_website($url)
   244 {
   245 	if ($url === 'http://')
   246 	{
   247 		return '';
   248 	}
   249 	else if (!preg_match('#^[a-z0-9]+://#i', $url) && strlen($url) > 0)
   250 	{
   251 		return 'http://' . $url;
   252 	}
   253 	return $url;
   254 }
   255 
   256 /**
   257 * Convert nulls to zeros for fields which allowed a NULL value in the source but not the destination
   258 */
   259 function null_to_zero($value)
   260 {
   261 	return ($value === NULL) ? 0 : $value;
   262 }
   263 
   264 /**
   265 * Convert nulls to empty strings for fields which allowed a NULL value in the source but not the destination
   266 */
   267 function null_to_str($value)
   268 {
   269 	return ($value === NULL) ? '' : $value;
   270 }
   271 
   272 // EXTENDED FUNCTIONS
   273 
   274 /**
   275 * Get old config value
   276 */
   277 function get_config_value($config_name)
   278 {
   279 	static $convert_config;
   280 
   281 	if (!isset($convert_config))
   282 	{
   283 		$convert_config = get_config();
   284 	}
   285 
   286 	if (!isset($convert_config[$config_name]))
   287 	{
   288 		return false;
   289 	}
   290 
   291 	return (empty($convert_config[$config_name])) ? '' : $convert_config[$config_name];
   292 }
   293 
   294 /**
   295 * Convert an IP address from the hexadecimal notation to normal dotted-quad notation
   296 */
   297 function decode_ip($int_ip)
   298 {
   299 	if (!$int_ip)
   300 	{
   301 		return $int_ip;
   302 	}
   303 
   304 	$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
   305 
   306 	// Any mod changing the way ips are stored? Then we are not able to convert and enter the ip "as is" to not "destroy" anything...
   307 	if (sizeof($hexipbang) < 4)
   308 	{
   309 		return $int_ip;
   310 	}
   311 
   312 	return hexdec($hexipbang[0]) . '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
   313 }
   314 
   315 /**
   316 * Reverse the encoding of wild-carded bans
   317 */
   318 function decode_ban_ip($int_ip)
   319 {
   320 	return str_replace('255', '*', decode_ip($int_ip));
   321 }
   322 
   323 /**
   324 * Determine the MIME-type of a specified filename
   325 * This does not actually inspect the file, but simply uses the file extension
   326 */
   327 function mimetype($filename)
   328 {
   329 	if (!preg_match('/\.([a-z0-9]+)$/i', $filename, $m))
   330 	{
   331 		return 'application/octet-stream';
   332 	}
   333 
   334 	switch (strtolower($m[1]))
   335 	{
   336 		case 'zip':		return 'application/zip';
   337 		case 'jpeg':	return 'image/jpeg';
   338 		case 'jpg':		return 'image/jpeg';
   339 		case 'jpe':		return 'image/jpeg';
   340 		case 'png':		return 'image/png';
   341 		case 'gif':		return 'image/gif';
   342 		case 'htm':
   343 		case 'html':	return 'text/html';
   344 		case 'tif':		return 'image/tiff';
   345 		case 'tiff':	return 'image/tiff';
   346 		case 'ras':		return 'image/x-cmu-raster';
   347 		case 'pnm':		return 'image/x-portable-anymap';
   348 		case 'pbm':		return 'image/x-portable-bitmap';
   349 		case 'pgm':		return 'image/x-portable-graymap';
   350 		case 'ppm':		return 'image/x-portable-pixmap';
   351 		case 'rgb':		return 'image/x-rgb';
   352 		case 'xbm':		return 'image/x-xbitmap';
   353 		case 'xpm':		return 'image/x-xpixmap';
   354 		case 'xwd':		return 'image/x-xwindowdump';
   355 		case 'z':		return 'application/x-compress';
   356 		case 'gtar':	return 'application/x-gtar';
   357 		case 'tgz':		return 'application/x-gtar';
   358 		case 'gz':		return 'application/x-gzip';
   359 		case 'tar':		return 'application/x-tar';
   360 		case 'xls':		return 'application/excel';
   361 		case 'pdf':		return 'application/pdf';
   362 		case 'ppt':		return 'application/powerpoint';
   363 		case 'rm':		return 'application/vnd.rn-realmedia';
   364 		case 'wma':		return 'audio/x-ms-wma';
   365 		case 'swf':		return 'application/x-shockwave-flash';
   366 		case 'ief':		return 'image/ief';
   367 		case 'doc':
   368 		case 'dot':
   369 		case 'wrd':		return 'application/msword';
   370 		case 'ai':
   371 		case 'eps':
   372 		case 'ps':		return 'application/postscript';
   373 		case 'asc':
   374 		case 'txt':
   375 		case 'c':
   376 		case 'cc':
   377 		case 'h':
   378 		case 'hh':
   379 		case 'cpp':
   380 		case 'hpp':
   381 		case 'php':
   382 		case 'php3':	return 'text/plain';
   383 		default: 		return 'application/octet-stream';
   384 	}
   385 }
   386 
   387 /**
   388 * Obtain the dimensions of all remotely hosted avatars
   389 * This should only be called from execute_last
   390 * There can be significant network overhead if there are a large number of remote avatars
   391 * @todo Look at the option of allowing the user to decide whether this is called or to force the dimensions
   392 */
   393 function remote_avatar_dims()
   394 {
   395 	global $db;
   396 
   397 	$sql = 'SELECT user_id, user_avatar
   398 		FROM ' . USERS_TABLE . '
   399 		WHERE user_avatar_type = ' . AVATAR_REMOTE;
   400 	$result = $db->sql_query($sql);
   401 
   402 	$remote_avatars = array();
   403 	while ($row = $db->sql_fetchrow($result))
   404 	{
   405 		$remote_avatars[(int) $row['user_id']] = $row['user_avatar'];
   406 	}
   407 	$db->sql_freeresult($result);
   408 
   409 	foreach ($remote_avatars as $user_id => $avatar)
   410 	{
   411 		$width = (int) get_remote_avatar_dim($avatar, 0);
   412 		$height = (int) get_remote_avatar_dim($avatar, 1);
   413 
   414 		$sql = 'UPDATE ' . USERS_TABLE . '
   415 			SET user_avatar_width = ' . (int) $width . ', user_avatar_height = ' . (int) $height . '
   416 			WHERE user_id = ' . $user_id;
   417 		$db->sql_query($sql);
   418 	}
   419 }
   420 
   421 function import_avatar_gallery($gallery_name = '', $subdirs_as_galleries = false)
   422 {
   423 	global $config, $convert, $phpbb_root_path, $user;
   424 
   425 	$relative_path = empty($convert->convertor['source_path_absolute']);
   426 
   427 	if (empty($convert->convertor['avatar_gallery_path']))
   428 	{
   429 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GALLERY_PATH'], 'import_avatar_gallery()'), __LINE__, __FILE__);
   430 	}
   431 
   432 	$src_path = relative_base(path($convert->convertor['avatar_gallery_path'], $relative_path), $relative_path);
   433 
   434 	if (is_dir($src_path))
   435 	{
   436 		// Do not die on failure... safe mode restrictions may be in effect.
   437 		copy_dir($convert->convertor['avatar_gallery_path'], path($config['avatar_gallery_path']) . $gallery_name, !$subdirs_as_galleries, false, false, $relative_path);
   438 
   439 		// only doing 1 level deep. (ibf 1.x)
   440 		// notes: ibf has 2 tiers: directly in the avatar directory for base gallery (handled in the above statement), plus subdirs(handled below).
   441 		// recursive subdirs ignored. -- i don't know if other forums support recursive galleries. if they do, this following code could be upgraded to be recursive.
   442 		if ($subdirs_as_galleries)
   443 		{
   444 			$dirlist = array();
   445 			if ($handle = @opendir($src_path))
   446 			{
   447 				while ($entry = readdir($handle))
   448 				{
   449 					if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
   450 					{
   451 						continue;
   452 					}
   453 
   454 					if (is_dir($src_path . $entry))
   455 					{
   456 						$dirlist[] = $entry;
   457 					}
   458 				}
   459 				closedir($handle);
   460 			}
   461 			else if ($dir = @dir($src_path))
   462 			{
   463 				while ($entry = $dir->read())
   464 				{
   465 					if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
   466 					{
   467 						continue;
   468 					}
   469 
   470 					if (is_dir($src_path . $entry))
   471 					{
   472 						$dirlist[] = $entry;
   473 					}
   474 				}
   475 				$dir->close();
   476 			}
   477 
   478 			for ($i = 0; $i < sizeof($dirlist); ++$i)
   479 			{
   480 				$dir = $dirlist[$i];
   481 
   482 				// Do not die on failure... safe mode restrictions may be in effect.
   483 				copy_dir(path($convert->convertor['avatar_gallery_path'], $relative_path) . $dir, path($config['avatar_gallery_path']) . $dir, true, false, false, $relative_path);
   484 			}
   485 		}
   486 	}
   487 }
   488 
   489 function import_attachment_files($category_name = '')
   490 {
   491 	global $config, $convert, $phpbb_root_path, $db, $user;
   492 
   493 	$sql = 'SELECT config_value AS upload_path
   494 		FROM ' . CONFIG_TABLE . "
   495 		WHERE config_name = 'upload_path'";
   496 	$result = $db->sql_query($sql);
   497 	$config['upload_path'] = $db->sql_fetchfield('upload_path');
   498 	$db->sql_freeresult($result);
   499 
   500 	$relative_path = empty($convert->convertor['source_path_absolute']);
   501 
   502 	if (empty($convert->convertor['upload_path']))
   503 	{
   504 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_UPLOAD_DIR'], 'import_attachment_files()'), __LINE__, __FILE__);
   505 	}
   506 
   507 	if (is_dir(relative_base(path($convert->convertor['upload_path'], $relative_path), $relative_path)))
   508 	{
   509 		copy_dir($convert->convertor['upload_path'], path($config['upload_path']) . $category_name, true, false, true, $relative_path);
   510 	}
   511 }
   512 
   513 function attachment_forum_perms($forum_id)
   514 {
   515 	if (!is_array($forum_id))
   516 	{
   517 		$forum_id = array($forum_id);
   518 	}
   519 
   520 	return serialize($forum_id);
   521 }
   522 
   523 // base64todec function
   524 // -> from php manual?
   525 function base64_unpack($string)
   526 {
   527 	$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-';
   528 	$base = strlen($chars);
   529 
   530 	$length = strlen($string);
   531 	$number = 0;
   532 
   533 	for ($i = 1; $i <= $length; $i++)
   534 	{
   535 		$pos = $length - $i;
   536 		$operand = strpos($chars, substr($string, $pos, 1));
   537 		$exponent = pow($base, $i-1);
   538 		$dec_value = $operand * $exponent;
   539 		$number += $dec_value;
   540 	}
   541 
   542 	return $number;
   543 }
   544 
   545 function _import_check($config_var, $source, $use_target)
   546 {
   547 	global $convert, $config;
   548 
   549 	$result = array(
   550 		'orig_source'	=> $source,
   551 		'copied'		=> false,
   552 		'relative_path'	=> (empty($convert->convertor['source_path_absolute'])) ? true : false,
   553 	);
   554 
   555 	// copy file will prepend $phpBB_root_path
   556 	$target = $config[$config_var] . '/' . utf8_basename(($use_target === false) ? $source : $use_target);
   557 
   558 	if (!empty($convert->convertor[$config_var]) && strpos($source, $convert->convertor[$config_var]) !== 0)
   559 	{
   560 		$source = $convert->convertor[$config_var] . $source;
   561 	}
   562 
   563 	$result['source'] = $source;
   564 
   565 	if (file_exists(relative_base($source, $result['relative_path'], __LINE__, __FILE__)))
   566 	{
   567 		$result['copied'] = copy_file($source, $target, false, false, $result['relative_path']);
   568 	}
   569 
   570 	if ($result['copied'])
   571 	{
   572 		$result['target'] = utf8_basename($target);
   573 	}
   574 	else
   575 	{
   576 		$result['target'] = ($use_target !== false) ? $result['orig_source'] : utf8_basename($target);
   577 	}
   578 
   579 	return $result;
   580 }
   581 
   582 function import_attachment($source, $use_target = false)
   583 {
   584 	if (empty($source))
   585 	{
   586 		return '';
   587 	}
   588 
   589 	global $convert, $phpbb_root_path, $config, $user;
   590 
   591 	if (empty($convert->convertor['upload_path']))
   592 	{
   593 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_UPLOAD_DIR'], 'import_attachment()'), __LINE__, __FILE__);
   594 	}
   595 
   596 	$result = _import_check('upload_path', $source, $use_target);
   597 
   598 	if ($result['copied'])
   599 	{
   600 		// Thumbnails?
   601 		if (is_array($convert->convertor['thumbnails']))
   602 		{
   603 			$thumb_dir = $convert->convertor['thumbnails'][0];
   604 			$thumb_prefix = $convert->convertor['thumbnails'][1];
   605 			$thumb_source = $thumb_dir . $thumb_prefix . utf8_basename($result['source']);
   606 
   607 			if (strpos($thumb_source, $convert->convertor['upload_path']) !== 0)
   608 			{
   609 				$thumb_source = $convert->convertor['upload_path'] . $thumb_source;
   610 			}
   611 			$thumb_target = $config['upload_path'] . '/thumb_' . $result['target'];
   612 
   613 			if (file_exists(relative_base($thumb_source, $result['relative_path'], __LINE__, __FILE__)))
   614 			{
   615 				copy_file($thumb_source, $thumb_target, false, false, $result['relative_path']);
   616 			}
   617 		}
   618 	}
   619 
   620 	return $result['target'];
   621 }
   622 
   623 function import_rank($source, $use_target = false)
   624 {
   625 	if (empty($source))
   626 	{
   627 		return '';
   628 	}
   629 
   630 	global $convert, $phpbb_root_path, $config, $user;
   631 
   632 	if (!isset($convert->convertor['ranks_path']))
   633 	{
   634 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_RANKS_PATH'], 'import_rank()'), __LINE__, __FILE__);
   635 	}
   636 
   637 	$result = _import_check('ranks_path', $source, $use_target);
   638 	return $result['target'];
   639 }
   640 
   641 function import_smiley($source, $use_target = false)
   642 {
   643 	if (empty($source))
   644 	{
   645 		return '';
   646 	}
   647 
   648 	global $convert, $phpbb_root_path, $config, $user;
   649 
   650 	if (!isset($convert->convertor['smilies_path']))
   651 	{
   652 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_SMILIES_PATH'], 'import_smiley()'), __LINE__, __FILE__);
   653 	}
   654 
   655 	$result = _import_check('smilies_path', $source, $use_target);
   656 	return $result['target'];
   657 }
   658 
   659 /*
   660 */
   661 function import_avatar($source, $use_target = false, $user_id = false)
   662 {
   663 	if (empty($source) || preg_match('#^https?:#i', $source) || preg_match('#blank\.(gif|png)$#i', $source))
   664 	{
   665 		return;
   666 	}
   667 
   668 	global $convert, $phpbb_root_path, $config, $user;
   669 
   670 	if (!isset($convert->convertor['avatar_path']))
   671 	{
   672 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_AVATAR_PATH'], 'import_avatar()'), __LINE__, __FILE__);
   673 	}
   674 
   675 	if ($use_target === false && $user_id !== false)
   676 	{
   677 		$use_target = $config['avatar_salt'] . '_' . $user_id . '.' . substr(strrchr($source, '.'), 1);
   678 	}
   679 
   680 	$result = _import_check('avatar_path', $source, $use_target);
   681 
   682 	return ((!empty($user_id)) ? $user_id : $use_target) . '.' . substr(strrchr($source, '.'), 1);
   683 }
   684 
   685 /**
   686 * @todo all image dimension functions below (there are a *lot*) should get revisited and converted to one or two functions (no more needed, really).
   687 */
   688 
   689 /**
   690 * Calculate the size of the specified image
   691 * Called from the following functions for calculating the size of specific image types
   692 */
   693 function get_image_dim($source)
   694 {
   695 	if (empty($source))
   696 	{
   697 		return array(0, 0);
   698 	}
   699 
   700 	global $convert;
   701 
   702 	$relative_path = empty($convert->convertor['source_path_absolute']);
   703 
   704 	if (file_exists(relative_base($source, $relative_path)))
   705 	{
   706 		$image = relative_base($source, $relative_path);
   707 		return @getimagesize($image);
   708 	}
   709 
   710 	return false;
   711 }
   712 
   713 /**
   714 * Obtain the width of the specified smilie
   715 */
   716 function get_smiley_width($src)
   717 {
   718 	return get_smiley_dim($src, 0);
   719 }
   720 
   721 /**
   722 * Obtain the height of the specified smilie
   723 */
   724 function get_smiley_height($src)
   725 {
   726 	return get_smiley_dim($src, 1);
   727 }
   728 
   729 /**
   730 * Obtain the size of the specified smilie (using the cache if possible) and cache the value
   731 */
   732 function get_smiley_dim($source, $axis)
   733 {
   734 	if (empty($source))
   735 	{
   736 		return 15;
   737 	}
   738 
   739 	static $smiley_cache = array();
   740 
   741 	if (isset($smiley_cache[$source]))
   742 	{
   743 		return $smiley_cache[$source][$axis];
   744 	}
   745 
   746 	global $convert, $phpbb_root_path, $config, $user;
   747 
   748 	$orig_source = $source;
   749 
   750 	if (!isset($convert->convertor['smilies_path']))
   751 	{
   752 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_SMILIES_PATH'], 'get_smiley_dim()'), __LINE__, __FILE__);
   753 	}
   754 
   755 	if (!empty($convert->convertor['smilies_path']) && strpos($source, $convert->convertor['smilies_path']) !== 0)
   756 	{
   757 		$source = $convert->convertor['smilies_path'] . $source;
   758 	}
   759 
   760 	$smiley_cache[$orig_source] = get_image_dim($source);
   761 
   762 	if (empty($smiley_cache[$orig_source]) || empty($smiley_cache[$orig_source][0]) || empty($smiley_cache[$orig_source][1]))
   763 	{
   764 		$smiley_cache[$orig_source] = array(15, 15);
   765 		return 15;
   766 	}
   767 
   768 	return $smiley_cache[$orig_source][$axis];
   769 }
   770 
   771 /**
   772 * Obtain the width of the specified avatar
   773 */
   774 function get_avatar_width($src, $func = false, $arg1 = false, $arg2 = false)
   775 {
   776 	return get_avatar_dim($src, 0, $func, $arg1, $arg2);
   777 }
   778 
   779 /**
   780 * Obtain the height of the specified avatar
   781 */
   782 function get_avatar_height($src, $func = false, $arg1 = false, $arg2 = false)
   783 {
   784 	return get_avatar_dim($src, 1, $func, $arg1, $arg2);
   785 }
   786 
   787 /**
   788 */
   789 function get_avatar_dim($src, $axis, $func = false, $arg1 = false, $arg2 = false)
   790 {
   791 	$avatar_type = AVATAR_UPLOAD;
   792 
   793 	if ($func)
   794 	{
   795 		if ($arg1 || $arg2)
   796 		{
   797 			$ary = array($arg1);
   798 
   799 			if ($arg2)
   800 			{
   801 				$ary[] = $arg2;
   802 			}
   803 
   804 			$avatar_type = call_user_func_array($func, $ary);
   805 		}
   806 		else
   807 		{
   808 			$avatar_type = call_user_func($func);
   809 		}
   810 	}
   811 
   812 	switch ($avatar_type)
   813 	{
   814 		case AVATAR_UPLOAD:
   815 			return get_upload_avatar_dim($src, $axis);
   816 		break;
   817 
   818 		case AVATAR_GALLERY:
   819 			return get_gallery_avatar_dim($src, $axis);
   820 		break;
   821 
   822 		case AVATAR_REMOTE:
   823 			 // see notes on this functions usage and (hopefully) model $func to avoid this accordingly
   824 			return get_remote_avatar_dim($src, $axis);
   825 		break;
   826 
   827 		default:
   828 			$default_x = (defined('DEFAULT_AVATAR_X_CUSTOM')) ? DEFAULT_AVATAR_X_CUSTOM : DEFAULT_AVATAR_X;
   829 			$default_y = (defined('DEFAULT_AVATAR_Y_CUSTOM')) ? DEFAULT_AVATAR_Y_CUSTOM : DEFAULT_AVATAR_Y;
   830 
   831 			return $axis ? $default_y : $default_x;
   832 		break;
   833 	}
   834 }
   835 
   836 /**
   837 * Obtain the size of the specified uploaded avatar (using the cache if possible) and cache the value
   838 */
   839 function get_upload_avatar_dim($source, $axis)
   840 {
   841 	static $cachedims = false;
   842 	static $cachekey = false;
   843 
   844 	if (empty($source))
   845 	{
   846 		return 0;
   847 	}
   848 
   849 	if ($cachekey == $source)
   850 	{
   851 		return $cachedims[$axis];
   852 	}
   853 
   854 	$orig_source = $source;
   855 
   856 	if (substr($source, 0, 7) == 'upload:')
   857 	{
   858 		$source = substr($source, 7);
   859 	}
   860 
   861 	global $convert, $phpbb_root_path, $config, $user;
   862 
   863 	if (!isset($convert->convertor['avatar_path']))
   864 	{
   865 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_AVATAR_PATH'], 'get_upload_avatar_dim()'), __LINE__, __FILE__);
   866 	}
   867 
   868 	if (!empty($convert->convertor['avatar_path']) && strpos($source, $convert->convertor['avatar_path']) !== 0)
   869 	{
   870 		$source = path($convert->convertor['avatar_path'], empty($convert->convertor['source_path_absolute'])) . $source;
   871 	}
   872 
   873 	$cachedims = get_image_dim($source);
   874 
   875 	if (empty($cachedims) || empty($cachedims[0]) || empty($cachedims[1]))
   876 	{
   877 		$default_x = (defined('DEFAULT_AVATAR_X_CUSTOM')) ? DEFAULT_AVATAR_X_CUSTOM : DEFAULT_AVATAR_X;
   878 		$default_y = (defined('DEFAULT_AVATAR_Y_CUSTOM')) ? DEFAULT_AVATAR_Y_CUSTOM : DEFAULT_AVATAR_Y;
   879 
   880 		$cachedims = array($default_x, $default_y);
   881 	}
   882 
   883 	return $cachedims[$axis];
   884 }
   885 
   886 /**
   887 * Obtain the size of the specified gallery avatar (using the cache if possible) and cache the value
   888 */
   889 function get_gallery_avatar_dim($source, $axis)
   890 {
   891 	if (empty($source))
   892 	{
   893 		return 0;
   894 	}
   895 
   896 	static $avatar_cache = array();
   897 
   898 	if (isset($avatar_cache[$source]))
   899 	{
   900 		return $avatar_cache[$source][$axis];
   901 	}
   902 
   903 	global $convert, $phpbb_root_path, $config, $user;
   904 
   905 	$orig_source = $source;
   906 
   907 	if (!isset($convert->convertor['avatar_gallery_path']))
   908 	{
   909 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GALLERY_PATH'], 'get_gallery_avatar_dim()'), __LINE__, __FILE__);
   910 	}
   911 
   912 	if (!empty($convert->convertor['avatar_gallery_path']) && strpos($source, $convert->convertor['avatar_gallery_path']) !== 0)
   913 	{
   914 		$source = path($convert->convertor['avatar_gallery_path'], empty($convert->convertor['source_path_absolute'])) . $source;
   915 	}
   916 
   917 	$avatar_cache[$orig_source] = get_image_dim($source);
   918 
   919 	if (empty($avatar_cache[$orig_source]) || empty($avatar_cache[$orig_source][0]) || empty($avatar_cache[$orig_source][1]))
   920 	{
   921 		$default_x = (defined('DEFAULT_AVATAR_X_CUSTOM')) ? DEFAULT_AVATAR_X_CUSTOM : DEFAULT_AVATAR_X;
   922 		$default_y = (defined('DEFAULT_AVATAR_Y_CUSTOM')) ? DEFAULT_AVATAR_Y_CUSTOM : DEFAULT_AVATAR_Y;
   923 
   924 		$avatar_cache[$orig_source] = array($default_x, $default_y);
   925 	}
   926 
   927 	return $avatar_cache[$orig_source][$axis];
   928 }
   929 
   930 /**
   931 * Obtain the size of the specified remote avatar (using the cache if possible) and cache the value
   932 * Whilst it's unlikely that remote avatars will be duplicated, it is possible so caching seems the best option
   933 * This should only be called from a post processing step due to the possibility of network timeouts
   934 */
   935 function get_remote_avatar_dim($src, $axis)
   936 {
   937 	if (empty($src))
   938 	{
   939 		return 0;
   940 	}
   941 
   942 	static $remote_avatar_cache = array();
   943 
   944 	// an ugly hack: we assume that the dimensions of each remote avatar are accessed exactly twice (x and y)
   945 	if (isset($remote_avatar_cache[$src]))
   946 	{
   947 		$retval = $remote_avatar_cache[$src][$axis];
   948 		unset($remote_avatar_cache);
   949 		return $retval;
   950 	}
   951 
   952 	$url_info = @parse_url($src);
   953 	if (empty($url_info['host']))
   954 	{
   955 		return 0;
   956 	}
   957 	$host = $url_info['host'];
   958 	$port = (isset($url_info['port'])) ? $url_info['port'] : 0;
   959 	$protocol = (isset($url_info['scheme'])) ? $url_info['scheme'] : 'http';
   960 	if (empty($port))
   961 	{
   962 		switch(strtolower($protocol))
   963 		{
   964 			case 'ftp':
   965 				$port = 21;
   966 				break;
   967 
   968 			case 'https':
   969 				$port = 443;
   970 				break;
   971 
   972 			default:
   973 				$port = 80;
   974 		}
   975 	}
   976 
   977 	$timeout = @ini_get('default_socket_timeout');
   978 	@ini_set('default_socket_timeout', 2);
   979 
   980 	// We're just trying to reach the server to avoid timeouts
   981 	$fp = @fsockopen($host, $port, $errno, $errstr, 1);
   982 	if ($fp)
   983 	{
   984 		$remote_avatar_cache[$src] = @getimagesize($src);
   985 		fclose($fp);
   986 	}
   987 
   988 	$default_x 	= (defined('DEFAULT_AVATAR_X_CUSTOM')) ? DEFAULT_AVATAR_X_CUSTOM : DEFAULT_AVATAR_X;
   989 	$default_y 	= (defined('DEFAULT_AVATAR_Y_CUSTOM')) ? DEFAULT_AVATAR_Y_CUSTOM : DEFAULT_AVATAR_Y;
   990 	$default 	= array($default_x, $default_y);
   991 
   992 	if (empty($remote_avatar_cache[$src]) || empty($remote_avatar_cache[$src][0]) || empty($remote_avatar_cache[$src][1]))
   993 	{
   994 		$remote_avatar_cache[$src] = $default;
   995 	}
   996 	else
   997 	{
   998 		// We trust gallery and uploaded avatars to conform to the size settings; we might have to adjust here
   999 		if ($remote_avatar_cache[$src][0] > $default_x || $remote_avatar_cache[$src][1] > $default_y)
  1000 		{
  1001 			$bigger = ($remote_avatar_cache[$src][0] > $remote_avatar_cache[$src][1]) ? 0 : 1;
  1002 			$ratio = $default[$bigger] / $remote_avatar_cache[$src][$bigger];
  1003 			$remote_avatar_cache[$src][0] = (int)($remote_avatar_cache[$src][0] * $ratio);
  1004 			$remote_avatar_cache[$src][1] = (int)($remote_avatar_cache[$src][1] * $ratio);
  1005 		}
  1006 	}
  1007 
  1008 	@ini_set('default_socket_timeout', $timeout);
  1009 	return $remote_avatar_cache[$src][$axis];
  1010 }
  1011 
  1012 function set_user_options()
  1013 {
  1014 	global $convert_row;
  1015 
  1016 	// Key need to be set in row, else default value is chosen
  1017 	$keyoptions = array(
  1018 		'viewimg'		=> array('bit' => 0, 'default' => 1),
  1019 		'viewflash'		=> array('bit' => 1, 'default' => 1),
  1020 		'viewsmilies'	=> array('bit' => 2, 'default' => 1),
  1021 		'viewsigs'		=> array('bit' => 3, 'default' => 1),
  1022 		'viewavatars'	=> array('bit' => 4, 'default' => 1),
  1023 		'viewcensors'	=> array('bit' => 5, 'default' => 1),
  1024 		'attachsig'		=> array('bit' => 6, 'default' => 0),
  1025 		'bbcode'		=> array('bit' => 8, 'default' => 1),
  1026 		'smilies'		=> array('bit' => 9, 'default' => 1),
  1027 		'popuppm'		=> array('bit' => 10, 'default' => 0),
  1028 		'sig_bbcode'	=> array('bit' => 15, 'default' => 1),
  1029 		'sig_smilies'	=> array('bit' => 16, 'default' => 1),
  1030 		'sig_links'		=> array('bit' => 17, 'default' => 1),
  1031 	);
  1032 
  1033 	$option_field = 0;
  1034 
  1035 	foreach ($keyoptions as $key => $key_ary)
  1036 	{
  1037 		$value = (isset($convert_row[$key])) ? (int) $convert_row[$key] : $key_ary['default'];
  1038 
  1039 		if ($value && !($option_field & 1 << $key_ary['bit']))
  1040 		{
  1041 			$option_field += 1 << $key_ary['bit'];
  1042 		}
  1043 	}
  1044 
  1045 	return $option_field;
  1046 }
  1047 
  1048 /**
  1049 * Index messages on the fly as we convert them
  1050 * @todo naderman, can you check that this works with the new search plugins as it's use is currently disabled (and thus untested)
  1051 function search_indexing($message = '')
  1052 {
  1053 	global $fulltext_search, $convert_row;
  1054 
  1055 	if (!isset($convert_row['post_id']))
  1056 	{
  1057 		return;
  1058 	}
  1059 
  1060 	if (!$message)
  1061 	{
  1062 		if (!isset($convert_row['message']))
  1063 		{
  1064 			return;
  1065 		}
  1066 
  1067 		$message = $convert_row['message'];
  1068 	}
  1069 
  1070 	$title = (isset($convert_row['title'])) ? $convert_row['title'] : '';
  1071 
  1072 	$fulltext_search->index('post', $convert_row['post_id'], $message, $title, $convert_row['poster_id'], $convert_row['forum_id']);
  1073 }
  1074 */
  1075 
  1076 function make_unique_filename($filename)
  1077 {
  1078 	if (!strlen($filename))
  1079 	{
  1080 		$filename = md5(unique_id()) . '.dat';
  1081 	}
  1082 	else if ($filename[0] == '.')
  1083 	{
  1084 		$filename = md5(unique_id()) . $filename;
  1085 	}
  1086 	else if (preg_match('/\.([a-z]+)$/i', $filename, $m))
  1087 	{
  1088 		$filename = preg_replace('/\.([a-z]+)$/i', '_' . md5(unique_id()) . '.\1', $filename);
  1089 	}
  1090 	else
  1091 	{
  1092 		$filename .= '_' . md5(unique_id()) . '.dat';
  1093 	}
  1094 
  1095 	return $filename;
  1096 }
  1097 
  1098 function words_unique(&$words)
  1099 {
  1100 	reset($words);
  1101 	$return_array = array();
  1102 
  1103 	$word = current($words);
  1104 	do
  1105 	{
  1106 		$return_array[$word] = $word;
  1107 	}
  1108 	while ($word = next($words));
  1109 
  1110 	return $return_array;
  1111 }
  1112 
  1113 /**
  1114 * Adds a user to the specified group and optionally makes them a group leader
  1115 * This function does not create the group if it does not exist and so should only be called after the groups have been created
  1116 */
  1117 function add_user_group($group_id, $user_id, $group_leader=false)
  1118 {
  1119 	global $convert, $phpbb_root_path, $config, $user, $db;
  1120 
  1121 	$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  1122 		'group_id'		=> $group_id,
  1123 		'user_id'		=> $user_id,
  1124 		'group_leader'	=> ($group_leader) ? 1 : 0,
  1125 		'user_pending'	=> 0));
  1126 	$db->sql_query($sql);
  1127 }
  1128 
  1129 // STANDALONE FUNCTIONS
  1130 
  1131 /**
  1132 * Add users to the pre-defined "special" groups
  1133 *
  1134 * @param string $group The name of the special group to add to
  1135 * @param string $select_query An SQL query to retrieve the user(s) to add to the group
  1136 */
  1137 function user_group_auth($group, $select_query, $use_src_db)
  1138 {
  1139 	global $convert, $phpbb_root_path, $config, $user, $db, $src_db, $same_db;
  1140 
  1141 	if (!in_array($group, array('guests', 'registered', 'registered_coppa', 'global_moderators', 'administrators', 'bots')))
  1142 	{
  1143 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_WRONG_GROUP'], $group, 'user_group_auth()'), __LINE__, __FILE__, true);
  1144 		return;
  1145 	}
  1146 
  1147 	$sql = 'SELECT group_id
  1148 		FROM ' . GROUPS_TABLE . "
  1149 		WHERE group_name = '" . $db->sql_escape(strtoupper($group)) . "'";
  1150 	$result = $db->sql_query($sql);
  1151 	$group_id = (int) $db->sql_fetchfield('group_id');
  1152 	$db->sql_freeresult($result);
  1153 
  1154 	if (!$group_id)
  1155 	{
  1156 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GROUP'], $group, 'user_group_auth()'), __LINE__, __FILE__, true);
  1157 		return;
  1158 	}
  1159 
  1160 	if ($same_db || !$use_src_db)
  1161 	{
  1162 		$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' (user_id, group_id, user_pending)
  1163 			' . str_replace('{' . strtoupper($group) . '}', $group_id . ', 0', $select_query);
  1164 		$db->sql_query($sql);
  1165 	}
  1166 	else
  1167 	{
  1168 		$result = $src_db->sql_query(str_replace('{' . strtoupper($group) . '}', $group_id . ' ', $select_query));
  1169 		while ($row = $src_db->sql_fetchrow($result))
  1170 		{
  1171 			// this might become quite a lot of INSERTS unfortunately
  1172 			$sql = 'INSERT INTO ' . USER_GROUP_TABLE . " (user_id, group_id, user_pending)
  1173 				VALUES ({$row['user_id']}, $group_id, 0)";
  1174 			$db->sql_query($sql);
  1175 		}
  1176 		$src_db->sql_freeresult($result);
  1177 	}
  1178 }
  1179 
  1180 /**
  1181 * Retrieves configuration information from the source forum and caches it as an array
  1182 * Both database and file driven configuration formats can be handled
  1183 * (the type used is specified in $config_schema, see convert_phpbb20.php for more details)
  1184 */
  1185 function get_config()
  1186 {
  1187 	static $convert_config;
  1188 	global $user;
  1189 
  1190 	if (isset($convert_config))
  1191 	{
  1192 		return $convert_config;
  1193 	}
  1194 
  1195 	global $src_db, $same_db, $phpbb_root_path, $config;
  1196 	global $convert;
  1197 
  1198 	if ($convert->config_schema['table_format'] != 'file')
  1199 	{
  1200 		if ($convert->mysql_convert && $same_db)
  1201 		{
  1202 			$src_db->sql_query("SET NAMES 'binary'");
  1203 		}
  1204 
  1205 		$sql = 'SELECT * FROM ' . $convert->src_table_prefix . $convert->config_schema['table_name'];
  1206 		$result = $src_db->sql_query($sql);
  1207 		$row = $src_db->sql_fetchrow($result);
  1208 
  1209 		if (!$row)
  1210 		{
  1211 			$convert->p_master->error($user->lang['CONV_ERROR_GET_CONFIG'], __LINE__, __FILE__);
  1212 		}
  1213 	}
  1214 
  1215 	if (is_array($convert->config_schema['table_format']))
  1216 	{
  1217 		$convert_config = array();
  1218 		list($key, $val) = each($convert->config_schema['table_format']);
  1219 
  1220 		do
  1221 		{
  1222 			$convert_config[$row[$key]] = $row[$val];
  1223 		}
  1224 		while ($row = $src_db->sql_fetchrow($result));
  1225 		$src_db->sql_freeresult($result);
  1226 
  1227 		if ($convert->mysql_convert && $same_db)
  1228 		{
  1229 			$src_db->sql_query("SET NAMES 'utf8'");
  1230 		}
  1231 	}
  1232 	else if ($convert->config_schema['table_format'] == 'file')
  1233 	{
  1234 		$filename = $convert->options['forum_path'] . '/' . $convert->config_schema['filename'];
  1235 		if (!file_exists($filename))
  1236 		{
  1237 			$convert->p_master->error($user->lang['FILE_NOT_FOUND'] . ': ' . $filename, __LINE__, __FILE__);
  1238 		}
  1239 
  1240 		if (isset($convert->config_schema['array_name']))
  1241 		{
  1242 			unset($convert->config_schema['array_name']);
  1243 		}
  1244 
  1245 		$convert_config = extract_variables_from_file($filename);
  1246 		if (!empty($convert->config_schema['array_name']))
  1247 		{
  1248 			$convert_config = $convert_config[$convert->config_schema['array_name']];
  1249 		}
  1250 	}
  1251 	else
  1252 	{
  1253 		$convert_config = $row;
  1254 		if ($convert->mysql_convert && $same_db)
  1255 		{
  1256 			$src_db->sql_query("SET NAMES 'utf8'");
  1257 		}
  1258 	}
  1259 
  1260 	if (!sizeof($convert_config))
  1261 	{
  1262 		$convert->p_master->error($user->lang['CONV_ERROR_CONFIG_EMPTY'], __LINE__, __FILE__);
  1263 	}
  1264 
  1265 	return $convert_config;
  1266 }
  1267 
  1268 /**
  1269 * Transfers the relevant configuration information from the source forum
  1270 * The mapping of fields is specified in $config_schema, see convert_phpbb20.php for more details
  1271 */
  1272 function restore_config($schema)
  1273 {
  1274 	global $db, $config;
  1275 
  1276 	$convert_config = get_config();
  1277 
  1278 	foreach ($schema['settings'] as $config_name => $src)
  1279 	{
  1280 		if (preg_match('/(.*)\((.*)\)/', $src, $m))
  1281 		{
  1282 			$var = (empty($m[2]) || empty($convert_config[$m[2]])) ? "''" : "'" . addslashes($convert_config[$m[2]]) . "'";
  1283 			$exec = '$config_value = ' . $m[1] . '(' . $var . ');';
  1284 			eval($exec);
  1285 		}
  1286 		else
  1287 		{
  1288 			if ($schema['table_format'] != 'file' || empty($schema['array_name']))
  1289 			{
  1290 				$config_value = (isset($convert_config[$src])) ? $convert_config[$src] : '';
  1291 			}
  1292 			else if (!empty($schema['array_name']))
  1293 			{
  1294 				$src_ary = $schema['array_name'];
  1295 				$config_value = (isset($convert_config[$src_ary][$src])) ? $convert_config[$src_ary][$src] : '';
  1296 			}
  1297    		}
  1298 
  1299 		if ($config_value !== '')
  1300 		{
  1301 			// Most are...
  1302 			if (is_string($config_value))
  1303 			{
  1304 				$config_value = truncate_string(utf8_htmlspecialchars($config_value), 255, 255, false);
  1305 			}
  1306 
  1307 			set_config($config_name, $config_value);
  1308 		}
  1309 	}
  1310 }
  1311 
  1312 /**
  1313 * Update the count of PM's in custom folders for all users
  1314 */
  1315 function update_folder_pm_count()
  1316 {
  1317 	global $db, $convert, $user;
  1318 
  1319 	$sql = 'SELECT user_id, folder_id, COUNT(msg_id) as num_messages
  1320 		FROM ' . PRIVMSGS_TO_TABLE . '
  1321 		WHERE folder_id NOT IN (' . PRIVMSGS_NO_BOX . ', ' . PRIVMSGS_HOLD_BOX . ', ' . PRIVMSGS_INBOX . ', ' . PRIVMSGS_OUTBOX . ', ' . PRIVMSGS_SENTBOX . ')
  1322 		GROUP BY folder_id, user_id';
  1323 	$result = $db->sql_query($sql);
  1324 
  1325 	while ($row = $db->sql_fetchrow($result))
  1326 	{
  1327 		$db->sql_query('UPDATE ' . PRIVMSGS_FOLDER_TABLE . ' SET pm_count = ' . $row['num_messages'] . '
  1328 			WHERE user_id = ' . $row['user_id'] . ' AND folder_id = ' . $row['folder_id']);
  1329 	}
  1330 	$db->sql_freeresult($result);
  1331 }
  1332 
  1333 // Functions mainly used by the main convertor script
  1334 
  1335 function path($path, $path_relative = true)
  1336 {
  1337 	if ($path === false)
  1338 	{
  1339 		return '';
  1340 	}
  1341 
  1342 	if (substr($path, -1) != '/')
  1343 	{
  1344 		$path .= '/';
  1345 	}
  1346 
  1347 	if (!$path_relative)
  1348 	{
  1349 		return $path;
  1350 	}
  1351 
  1352 	if (substr($path, 0, 1) == '/')
  1353 	{
  1354 		$path = substr($path, 1);
  1355 	}
  1356 
  1357 	return $path;
  1358 }
  1359 
  1360 /**
  1361 * Extract the variables defined in a configuration file
  1362 * @todo As noted by Xore we need to look at this from a security perspective
  1363 */
  1364 function extract_variables_from_file($_filename)
  1365 {
  1366 	include($_filename);
  1367 
  1368 	$vars = get_defined_vars();
  1369 	unset($vars['_filename']);
  1370 
  1371 	return $vars;
  1372 }
  1373 
  1374 function get_path($src_path, $src_url, $test_file)
  1375 {
  1376 	global $config, $phpbb_root_path, $phpEx;
  1377 
  1378 	$board_config = get_config();
  1379 
  1380 	$test_file = preg_replace('/\.php$/i', ".$phpEx", $test_file);
  1381 	$src_path = path($src_path);
  1382 
  1383 	if (@file_exists($phpbb_root_path . $src_path . $test_file))
  1384 	{
  1385 		return $src_path;
  1386 	}
  1387 
  1388 	if (!empty($src_url) && !empty($board_config['server_name']))
  1389 	{
  1390 		if (!preg_match('#https?://([^/]+)(.*)#i', $src_url, $m))
  1391 		{
  1392 			return false;
  1393 		}
  1394 
  1395 		if ($m[1] != $board_config['server_name'])
  1396 		{
  1397 			return false;
  1398 		}
  1399 
  1400 		$url_parts = explode('/', $m[2]);
  1401 		if (substr($src_url, -1) != '/')
  1402 		{
  1403 			if (preg_match('/.*\.([a-z0-9]{3,4})$/i', $url_parts[sizeof($url_parts) - 1]))
  1404 			{
  1405 				$url_parts[sizeof($url_parts) - 1] = '';
  1406 			}
  1407 			else
  1408 			{
  1409 				$url_parts[] = '';
  1410 			}
  1411 		}
  1412 
  1413 		$script_path = $board_config['script_path'];
  1414 		if (substr($script_path, -1) == '/')
  1415 		{
  1416 			$script_path = substr($script_path, 0, -1);
  1417 		}
  1418 
  1419 		$path_array = array();
  1420 
  1421 		$phpbb_parts = explode('/', $script_path);
  1422 		for ($i = 0; $i < sizeof($url_parts); ++$i)
  1423 		{
  1424 			if ($i < sizeof($phpbb_parts[$i]) && $url_parts[$i] == $phpbb_parts[$i])
  1425 			{
  1426 				$path_array[] = $url_parts[$i];
  1427 				unset($url_parts[$i]);
  1428 			}
  1429 			else
  1430 			{
  1431 				$path = '';
  1432 				for ($j = $i; $j < sizeof($phpbb_parts); ++$j)
  1433 				{
  1434 					$path .= '../';
  1435 				}
  1436 				$path .= implode('/', $url_parts);
  1437 				break;
  1438 			}
  1439 		}
  1440 
  1441 		if (!empty($path))
  1442 		{
  1443 			if (@file_exists($phpbb_root_path . $path . $test_file))
  1444 			{
  1445 				return $path;
  1446 			}
  1447 		}
  1448 	}
  1449 
  1450 	return false;
  1451 }
  1452 
  1453 function compare_table($tables, $tablename, &$prefixes)
  1454 {
  1455 	for ($i = 0, $table_size = sizeof($tables); $i < $table_size; ++$i)
  1456 	{
  1457 		if (preg_match('/(.*)' . $tables[$i] . '$/', $tablename, $m))
  1458 		{
  1459 			if (empty($m[1]))
  1460 			{
  1461 				$m[1] = '*';
  1462 			}
  1463 
  1464 			if (isset($prefixes[$m[1]]))
  1465 			{
  1466 				$prefixes[$m[1]]++;
  1467 			}
  1468 			else
  1469 			{
  1470 				$prefixes[$m[1]] = 1;
  1471 			}
  1472 		}
  1473 	}
  1474 }
  1475 
  1476 /**
  1477 * Grant permissions to a specified user or group
  1478 *
  1479 * @param string $ug_type user|group|user_role|group_role
  1480 * @param mixed $forum_id forum ids (array|int|0) -> 0 == all forums
  1481 * @param mixed $ug_id [int] user_id|group_id : [string] usergroup name
  1482 * @param mixed $acl_list [string] acl entry : [array] acl entries : [string] role entry
  1483 * @param int $setting ACL_YES|ACL_NO|ACL_NEVER
  1484 */
  1485 function mass_auth($ug_type, $forum_id, $ug_id, $acl_list, $setting = ACL_NO)
  1486 {
  1487 	global $db, $convert, $user, $config;
  1488 	static $acl_option_ids, $group_ids;
  1489 
  1490 	if (($ug_type == 'group' || $ug_type == 'group_role') && is_string($ug_id))
  1491 	{
  1492 		if (!isset($group_ids[$ug_id]))
  1493 		{
  1494 			$sql = 'SELECT group_id
  1495 				FROM ' . GROUPS_TABLE . "
  1496 				WHERE group_name = '" . $db->sql_escape(strtoupper($ug_id)) . "'";
  1497 			$result = $db->sql_query_limit($sql, 1);
  1498 			$id = (int) $db->sql_fetchfield('group_id');
  1499 			$db->sql_freeresult($result);
  1500 
  1501 			if (!$id)
  1502 			{
  1503 				return;
  1504 			}
  1505 
  1506 			$group_ids[$ug_id] = $id;
  1507 		}
  1508 
  1509 		$ug_id = (int) $group_ids[$ug_id];
  1510 	}
  1511 
  1512 	$table = ($ug_type == 'user' || $ug_type == 'user_role') ? ACL_USERS_TABLE : ACL_GROUPS_TABLE;
  1513 	$id_field = ($ug_type == 'user' || $ug_type == 'user_role') ? 'user_id' : 'group_id';
  1514 
  1515 	// Role based permissions are the simplest to handle so check for them first
  1516 	if ($ug_type == 'user_role' || $ug_type == 'group_role')
  1517 	{
  1518 		if (is_numeric($forum_id))
  1519 		{
  1520 			$sql = 'SELECT role_id
  1521 				FROM ' . ACL_ROLES_TABLE . "
  1522 				WHERE role_name = 'ROLE_" . $db->sql_escape($acl_list) . "'";
  1523 			$result = $db->sql_query_limit($sql, 1);
  1524 			$row = $db->sql_fetchrow($result);
  1525 			$db->sql_freeresult($result);
  1526 
  1527 			// If we have no role id there is something wrong here
  1528 			if ($row)
  1529 			{
  1530 				$sql = "INSERT INTO $table ($id_field, forum_id, auth_role_id) VALUES ($ug_id, $forum_id, " . $row['role_id'] . ')';
  1531 				$db->sql_query($sql);
  1532 			}
  1533 		}
  1534 
  1535 		return;
  1536 	}
  1537 
  1538 	// Build correct parameters
  1539 	$auth = array();
  1540 
  1541 	if (!is_array($acl_list))
  1542 	{
  1543 		$auth = array($acl_list => $setting);
  1544 	}
  1545 	else
  1546 	{
  1547 		foreach ($acl_list as $auth_option)
  1548 		{
  1549 			$auth[$auth_option] = $setting;
  1550 		}
  1551 	}
  1552 	unset($acl_list);
  1553 
  1554 	if (!is_array($forum_id))
  1555 	{
  1556 		$forum_id = array($forum_id);
  1557 	}
  1558 
  1559 	// Set any flags as required
  1560 	foreach ($auth as $auth_option => $acl_setting)
  1561 	{
  1562 		$flag = substr($auth_option, 0, strpos($auth_option, '_') + 1);
  1563 		if (empty($auth[$flag]))
  1564 		{
  1565 			$auth[$flag] = $acl_setting;
  1566 		}
  1567 	}
  1568 
  1569 	if (!is_array($acl_option_ids) || empty($acl_option_ids))
  1570 	{
  1571 		$sql = 'SELECT auth_option_id, auth_option
  1572 			FROM ' . ACL_OPTIONS_TABLE;
  1573 		$result = $db->sql_query($sql);
  1574 
  1575 		while ($row = $db->sql_fetchrow($result))
  1576 		{
  1577 			$acl_option_ids[$row['auth_option']] = $row['auth_option_id'];
  1578 		}
  1579 		$db->sql_freeresult($result);
  1580 	}
  1581 
  1582 	$sql_forum = 'AND ' . $db->sql_in_set('a.forum_id', array_map('intval', $forum_id), false, true);
  1583 
  1584 	$sql = ($ug_type == 'user') ? 'SELECT o.auth_option_id, o.auth_option, a.forum_id, a.auth_setting FROM ' . ACL_USERS_TABLE . ' a, ' . ACL_OPTIONS_TABLE . " o WHERE a.auth_option_id = o.auth_option_id $sql_forum AND a.user_id = $ug_id" : 'SELECT o.auth_option_id, o.auth_option, a.forum_id, a.auth_setting FROM ' . ACL_GROUPS_TABLE . ' a, ' . ACL_OPTIONS_TABLE . " o WHERE a.auth_option_id = o.auth_option_id $sql_forum AND a.group_id = $ug_id";
  1585 	$result = $db->sql_query($sql);
  1586 
  1587 	$cur_auth = array();
  1588 	while ($row = $db->sql_fetchrow($result))
  1589 	{
  1590 		$cur_auth[$row['forum_id']][$row['auth_option_id']] = $row['auth_setting'];
  1591 	}
  1592 	$db->sql_freeresult($result);
  1593 
  1594 	$sql_ary = array();
  1595 	foreach ($forum_id as $forum)
  1596 	{
  1597 		foreach ($auth as $auth_option => $setting)
  1598 		{
  1599 			$auth_option_id = $acl_option_ids[$auth_option];
  1600 
  1601 			if (!$auth_option_id)
  1602 			{
  1603 				continue;
  1604 			}
  1605 
  1606 			switch ($setting)
  1607 			{
  1608 				case ACL_NO:
  1609 					if (isset($cur_auth[$forum][$auth_option_id]))
  1610 					{
  1611 						$sql_ary['delete'][] = "DELETE FROM $table
  1612 							WHERE forum_id = $forum
  1613 								AND auth_option_id = $auth_option_id
  1614 								AND $id_field = $ug_id";
  1615 					}
  1616 				break;
  1617 
  1618 				default:
  1619 					if (!isset($cur_auth[$forum][$auth_option_id]))
  1620 					{
  1621 						$sql_ary['insert'][] = "$ug_id, $forum, $auth_option_id, $setting";
  1622 					}
  1623 					else if ($cur_auth[$forum][$auth_option_id] != $setting)
  1624 					{
  1625 						$sql_ary['update'][] = "UPDATE " . $table . "
  1626 							SET auth_setting = $setting
  1627 							WHERE $id_field = $ug_id
  1628 								AND forum_id = $forum
  1629 								AND auth_option_id = $auth_option_id";
  1630 					}
  1631 			}
  1632 		}
  1633 	}
  1634 	unset($cur_auth);
  1635 
  1636 	$sql = '';
  1637 	foreach ($sql_ary as $sql_type => $sql_subary)
  1638 	{
  1639 		switch ($sql_type)
  1640 		{
  1641 			case 'insert':
  1642 				switch ($db->sql_layer)
  1643 				{
  1644 					case 'mysql':
  1645 					case 'mysql4':
  1646 						$sql = 'VALUES ' . implode(', ', preg_replace('#^(.*?)$#', '(\1)', $sql_subary));
  1647 					break;
  1648 
  1649 					case 'mssql':
  1650 					case 'sqlite':
  1651 					case 'mssqlnative':
  1652 						$sql = implode(' UNION ALL ', preg_replace('#^(.*?)$#', 'SELECT \1', $sql_subary));
  1653 					break;
  1654 
  1655 					default:
  1656 						foreach ($sql_subary as $sql)
  1657 						{
  1658 							$sql = "INSERT INTO $table ($id_field, forum_id, auth_option_id, auth_setting) VALUES ($sql)";
  1659 							$db->sql_query($sql);
  1660 							$sql = '';
  1661 						}
  1662 				}
  1663 
  1664 				if ($sql != '')
  1665 				{
  1666 					$sql = "INSERT INTO $table ($id_field, forum_id, auth_option_id, auth_setting) $sql";
  1667 					$db->sql_query($sql);
  1668 				}
  1669 			break;
  1670 
  1671 			case 'update':
  1672 			case 'delete':
  1673 				foreach ($sql_subary as $sql)
  1674 				{
  1675 					$db->sql_query($sql);
  1676 					$sql = '';
  1677 				}
  1678 			break;
  1679 		}
  1680 		unset($sql_ary[$sql_type]);
  1681 	}
  1682 	unset($sql_ary);
  1683 
  1684 }
  1685 
  1686 /**
  1687 * Update the count of unread private messages for all users
  1688 */
  1689 function update_unread_count()
  1690 {
  1691 	global $db;
  1692 
  1693 	$sql = 'SELECT user_id, COUNT(msg_id) as num_messages
  1694 		FROM ' . PRIVMSGS_TO_TABLE . '
  1695 		WHERE pm_unread = 1
  1696 			AND folder_id <> ' . PRIVMSGS_OUTBOX . '
  1697 		GROUP BY user_id';
  1698 	$result = $db->sql_query($sql);
  1699 
  1700 	while ($row = $db->sql_fetchrow($result))
  1701 	{
  1702 		$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_unread_privmsg = ' . $row['num_messages'] . '
  1703 			WHERE user_id = ' . $row['user_id']);
  1704 	}
  1705 	$db->sql_freeresult($result);
  1706 }
  1707 
  1708 /**
  1709 * Add any of the pre-defined "special" groups which are missing from the database
  1710 */
  1711 function add_default_groups()
  1712 {
  1713 	global $db;
  1714 
  1715 	$default_groups = array(
  1716 		'GUESTS'			=> array('', 0, 0),
  1717 		'REGISTERED'		=> array('', 0, 0),
  1718 		'REGISTERED_COPPA'	=> array('', 0, 0),
  1719 		'GLOBAL_MODERATORS'	=> array('00AA00', 1, 0),
  1720 		'ADMINISTRATORS'	=> array('AA0000', 1, 1),
  1721 		'BOTS'				=> array('9E8DA7', 0, 0),
  1722 		'NEWLY_REGISTERED'		=> array('', 0, 0),
  1723 	);
  1724 
  1725 	$sql = 'SELECT *
  1726 		FROM ' . GROUPS_TABLE . '
  1727 		WHERE ' . $db->sql_in_set('group_name', array_keys($default_groups));
  1728 	$result = $db->sql_query($sql);
  1729 
  1730 	while ($row = $db->sql_fetchrow($result))
  1731 	{
  1732 		unset($default_groups[strtoupper($row['group_name'])]);
  1733 	}
  1734 	$db->sql_freeresult($result);
  1735 
  1736 	$sql_ary = array();
  1737 
  1738 	foreach ($default_groups as $name => $data)
  1739 	{
  1740 		$sql_ary[] = array(
  1741 			'group_name'			=> (string) $name,
  1742 			'group_desc'			=> '',
  1743 			'group_desc_uid'		=> '',
  1744 			'group_desc_bitfield'	=> '',
  1745 			'group_type'			=> GROUP_SPECIAL,
  1746 			'group_colour'			=> (string) $data[0],
  1747 			'group_legend'			=> (int) $data[1],
  1748 			'group_founder_manage'	=> (int) $data[2]
  1749 		);
  1750 	}
  1751 
  1752 	if (sizeof($sql_ary))
  1753 	{
  1754 		$db->sql_multi_insert(GROUPS_TABLE, $sql_ary);
  1755 	}
  1756 }
  1757 
  1758 
  1759 /**
  1760 * Sync post count. We might need to do this in batches.
  1761 */
  1762 function sync_post_count($offset, $limit)
  1763 {
  1764 	global $db;
  1765 	$sql = 'SELECT COUNT(post_id) AS num_posts, poster_id
  1766 			FROM ' . POSTS_TABLE . '
  1767 			WHERE post_postcount = 1
  1768 				AND post_approved = 1
  1769 			GROUP BY poster_id
  1770 			ORDER BY poster_id';
  1771 	$result = $db->sql_query_limit($sql, $limit, $offset);
  1772 
  1773 	while ($row = $db->sql_fetchrow($result))
  1774 	{
  1775 		$db->sql_query('UPDATE ' . USERS_TABLE . " SET user_posts = {$row['num_posts']} WHERE user_id = {$row['poster_id']}");
  1776 	}
  1777 	$db->sql_freeresult($result);
  1778 }
  1779 
  1780 /**
  1781 * Add the search bots into the database
  1782 * This code should be used in execute_last if the source database did not have bots
  1783 * If you are converting bots this function should not be called
  1784 * @todo We might want to look at sharing the bot list between the install code and this code for consistancy
  1785 */
  1786 function add_bots()
  1787 {
  1788 	global $db, $convert, $user, $config, $phpbb_root_path, $phpEx;
  1789 
  1790 	$db->sql_query($convert->truncate_statement . BOTS_TABLE);
  1791 
  1792 	$sql = 'SELECT group_id FROM ' . GROUPS_TABLE . " WHERE group_name = 'BOTS'";
  1793 	$result = $db->sql_query($sql);
  1794 	$group_id = (int) $db->sql_fetchfield('group_id', false, $result);
  1795 	$db->sql_freeresult($result);
  1796 
  1797 	if (!$group_id)
  1798 	{
  1799 		add_default_groups();
  1800 
  1801 		$sql = 'SELECT group_id FROM ' . GROUPS_TABLE . " WHERE group_name = 'BOTS'";
  1802 		$result = $db->sql_query($sql);
  1803 		$group_id = (int) $db->sql_fetchfield('group_id', false, $result);
  1804 		$db->sql_freeresult($result);
  1805 
  1806 		if (!$group_id)
  1807 		{
  1808 			global $install;
  1809 			$install->error($user->lang['CONV_ERROR_INCONSISTENT_GROUPS'], __LINE__, __FILE__);
  1810 		}
  1811 	}
  1812 
  1813 	$bots = array(
  1814 		'AdsBot [Google]'			=> array('AdsBot-Google', ''),
  1815 		'Alexa [Bot]'				=> array('ia_archiver', ''),
  1816 		'Alta Vista [Bot]'			=> array('Scooter/', ''),
  1817 		'Ask Jeeves [Bot]'			=> array('Ask Jeeves', ''),
  1818 		'Baidu [Spider]'			=> array('Baiduspider+(', ''),
  1819 		'Bing [Bot]'				=> array('bingbot/', ''),
  1820 		'Exabot [Bot]'				=> array('Exabot/', ''),
  1821 		'FAST Enterprise [Crawler]'	=> array('FAST Enterprise Crawler', ''),
  1822 		'FAST WebCrawler [Crawler]'	=> array('FAST-WebCrawler/', ''),
  1823 		'Francis [Bot]'				=> array('http://www.neomo.de/', ''),
  1824 		'Gigabot [Bot]'				=> array('Gigabot/', ''),
  1825 		'Google Adsense [Bot]'		=> array('Mediapartners-Google', ''),
  1826 		'Google Desktop'			=> array('Google Desktop', ''),
  1827 		'Google Feedfetcher'		=> array('Feedfetcher-Google', ''),
  1828 		'Google [Bot]'				=> array('Googlebot', ''),
  1829 		'Heise IT-Markt [Crawler]'	=> array('heise-IT-Markt-Crawler', ''),
  1830 		'Heritrix [Crawler]'		=> array('heritrix/1.', ''),
  1831 		'IBM Research [Bot]'		=> array('ibm.com/cs/crawler', ''),
  1832 		'ICCrawler - ICjobs'		=> array('ICCrawler - ICjobs', ''),
  1833 		'ichiro [Crawler]'			=> array('ichiro/2', ''),
  1834 		'Majestic-12 [Bot]'			=> array('MJ12bot/', ''),
  1835 		'Metager [Bot]'				=> array('MetagerBot/', ''),
  1836 		'MSN NewsBlogs'				=> array('msnbot-NewsBlogs/', ''),
  1837 		'MSN [Bot]'					=> array('msnbot/', ''),
  1838 		'MSNbot Media'				=> array('msnbot-media/', ''),
  1839 		'NG-Search [Bot]'			=> array('NG-Search/', ''),
  1840 		'Nutch [Bot]'				=> array('http://lucene.apache.org/nutch/', ''),
  1841 		'Nutch/CVS [Bot]'			=> array('NutchCVS/', ''),
  1842 		'OmniExplorer [Bot]'		=> array('OmniExplorer_Bot/', ''),
  1843 		'Online link [Validator]'	=> array('online link validator', ''),
  1844 		'psbot [Picsearch]'			=> array('psbot/0', ''),
  1845 		'Seekport [Bot]'			=> array('Seekbot/', ''),
  1846 		'Sensis [Crawler]'			=> array('Sensis Web Crawler', ''),
  1847 		'SEO Crawler'				=> array('SEO search Crawler/', ''),
  1848 		'Seoma [Crawler]'			=> array('Seoma [SEO Crawler]', ''),
  1849 		'SEOSearch [Crawler]'		=> array('SEOsearch/', ''),
  1850 		'Snappy [Bot]'				=> array('Snappy/1.1 ( http://www.urltrends.com/ )', ''),
  1851 		'Steeler [Crawler]'			=> array('http://www.tkl.iis.u-tokyo.ac.jp/~crawler/', ''),
  1852 		'Synoo [Bot]'				=> array('SynooBot/', ''),
  1853 		'Telekom [Bot]'				=> array('crawleradmin.t-info@telekom.de', ''),
  1854 		'TurnitinBot [Bot]'			=> array('TurnitinBot/', ''),
  1855 		'Voyager [Bot]'				=> array('voyager/1.0', ''),
  1856 		'W3 [Sitesearch]'			=> array('W3 SiteSearch Crawler', ''),
  1857 		'W3C [Linkcheck]'			=> array('W3C-checklink/', ''),
  1858 		'W3C [Validator]'			=> array('W3C_*Validator', ''),
  1859 		'WiseNut [Bot]'				=> array('http://www.WISEnutbot.com', ''),
  1860 		'YaCy [Bot]'				=> array('yacybot', ''),
  1861 		'Yahoo MMCrawler [Bot]'		=> array('Yahoo-MMCrawler/', ''),
  1862 		'Yahoo Slurp [Bot]'			=> array('Yahoo! DE Slurp', ''),
  1863 		'Yahoo [Bot]'				=> array('Yahoo! Slurp', ''),
  1864 		'YahooSeeker [Bot]'			=> array('YahooSeeker/', ''),
  1865 	);
  1866 
  1867 	if (!function_exists('user_add'))
  1868 	{
  1869 		include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
  1870 	}
  1871 
  1872 	foreach ($bots as $bot_name => $bot_ary)
  1873 	{
  1874 		$user_row = array(
  1875 			'user_type'				=> USER_IGNORE,
  1876 			'group_id'				=> $group_id,
  1877 			'username'				=> $bot_name,
  1878 			'user_regdate'			=> time(),
  1879 			'user_password'			=> '',
  1880 			'user_colour'			=> '9E8DA7',
  1881 			'user_email'			=> '',
  1882 			'user_lang'				=> $config['default_lang'],
  1883 			'user_style'			=> 1,
  1884 			'user_timezone'			=> 0,
  1885 			'user_allow_massemail'	=> 0,
  1886 		);
  1887 
  1888 		$user_id = user_add($user_row);
  1889 
  1890 		if ($user_id)
  1891 		{
  1892 			$sql = 'INSERT INTO ' . BOTS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  1893 				'bot_active'	=> 1,
  1894 				'bot_name'		=> $bot_name,
  1895 				'user_id'		=> $user_id,
  1896 				'bot_agent'		=> $bot_ary[0],
  1897 				'bot_ip'		=> $bot_ary[1])
  1898 			);
  1899 			$db->sql_query($sql);
  1900 		}
  1901 	}
  1902 }
  1903 
  1904 /**
  1905 * Update any dynamic configuration variables after the conversion is finished
  1906 * @todo Confirm that this updates all relevant values since it has not necessarily been kept in sync with all changes
  1907 */
  1908 function update_dynamic_config()
  1909 {
  1910 	global $db, $config;
  1911 
  1912 	// Get latest username
  1913 	$sql = 'SELECT user_id, username, user_colour
  1914 		FROM ' . USERS_TABLE . '
  1915 		WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
  1916 
  1917 	if (!empty($config['increment_user_id']))
  1918 	{
  1919 		$sql .= ' AND user_id <> ' . $config['increment_user_id'];
  1920 	}
  1921 
  1922 	$sql .= ' ORDER BY user_id DESC';
  1923 
  1924 	$result = $db->sql_query_limit($sql, 1);
  1925 	$row = $db->sql_fetchrow($result);
  1926 	$db->sql_freeresult($result);
  1927 
  1928 	if ($row)
  1929 	{
  1930 		set_config('newest_user_id', $row['user_id'], true);
  1931 		set_config('newest_username', $row['username'], true);
  1932 		set_config('newest_user_colour', $row['user_colour'], true);
  1933 	}
  1934 
  1935 //	Also do not reset record online user/date. There will be old data or the fresh data from the schema.
  1936 //	set_config('record_online_users', 1, true);
  1937 //	set_config('record_online_date', time(), true);
  1938 
  1939 	$sql = 'SELECT COUNT(post_id) AS stat
  1940 		FROM ' . POSTS_TABLE . '
  1941 		WHERE post_approved = 1';
  1942 	$result = $db->sql_query($sql);
  1943 	$row = $db->sql_fetchrow($result);
  1944 	$db->sql_freeresult($result);
  1945 
  1946 	set_config('num_posts', (int) $row['stat'], true);
  1947 
  1948 	$sql = 'SELECT COUNT(topic_id) AS stat
  1949 		FROM ' . TOPICS_TABLE . '
  1950 		WHERE topic_approved = 1';
  1951 	$result = $db->sql_query($sql);
  1952 	$row = $db->sql_fetchrow($result);
  1953 	$db->sql_freeresult($result);
  1954 
  1955 	set_config('num_topics', (int) $row['stat'], true);
  1956 
  1957 	$sql = 'SELECT COUNT(user_id) AS stat
  1958 		FROM ' . USERS_TABLE . '
  1959 		WHERE user_type IN (' . USER_NORMAL . ',' . USER_FOUNDER . ')';
  1960 	$result = $db->sql_query($sql);
  1961 	$row = $db->sql_fetchrow($result);
  1962 	$db->sql_freeresult($result);
  1963 
  1964 	set_config('num_users', (int) $row['stat'], true);
  1965 
  1966 	$sql = 'SELECT COUNT(attach_id) as stat
  1967 		FROM ' . ATTACHMENTS_TABLE . '
  1968 		WHERE is_orphan = 0';
  1969 	$result = $db->sql_query($sql);
  1970 	set_config('num_files', (int) $db->sql_fetchfield('stat'), true);
  1971 	$db->sql_freeresult($result);
  1972 
  1973 	$sql = 'SELECT SUM(filesize) as stat
  1974 		FROM ' . ATTACHMENTS_TABLE . '
  1975 		WHERE is_orphan = 0';
  1976 	$result = $db->sql_query($sql);
  1977 	set_config('upload_dir_size', (float) $db->sql_fetchfield('stat'), true);
  1978 	$db->sql_freeresult($result);
  1979 
  1980 	/**
  1981 	* We do not resync users post counts - this can be done by the admin after conversion if wanted.
  1982 	$sql = 'SELECT COUNT(post_id) AS num_posts, poster_id
  1983 		FROM ' . POSTS_TABLE . '
  1984 		WHERE post_postcount = 1
  1985 		GROUP BY poster_id';
  1986 	$result = $db->sql_query($sql);
  1987 
  1988 	while ($row = $db->sql_fetchrow($result))
  1989 	{
  1990 		$db->sql_query('UPDATE ' . USERS_TABLE . " SET user_posts = {$row['num_posts']} WHERE user_id = {$row['poster_id']}");
  1991 	}
  1992 	$db->sql_freeresult($result);
  1993 	*/
  1994 }
  1995 
  1996 /**
  1997 * Updates topics_posted entries
  1998 */
  1999 function update_topics_posted()
  2000 {
  2001 	global $db, $config;
  2002 
  2003 	switch ($db->sql_layer)
  2004 	{
  2005 		case 'sqlite':
  2006 		case 'firebird':
  2007 			$db->sql_query('DELETE FROM ' . TOPICS_POSTED_TABLE);
  2008 		break;
  2009 
  2010 		default:
  2011 			$db->sql_query('TRUNCATE TABLE ' . TOPICS_POSTED_TABLE);
  2012 		break;
  2013 	}
  2014 
  2015 	// This can get really nasty... therefore we only do the last six months
  2016 	$get_from_time = time() - (6 * 4 * 7 * 24 * 60 * 60);
  2017 
  2018 	// Select forum ids, do not include categories
  2019 	$sql = 'SELECT forum_id
  2020 		FROM ' . FORUMS_TABLE . '
  2021 		WHERE forum_type <> ' . FORUM_CAT;
  2022 	$result = $db->sql_query($sql);
  2023 
  2024 	$forum_ids = array();
  2025 	while ($row = $db->sql_fetchrow($result))
  2026 	{
  2027 		$forum_ids[] = $row['forum_id'];
  2028 	}
  2029 	$db->sql_freeresult($result);
  2030 
  2031 	// Any global announcements? ;)
  2032 	$forum_ids[] = 0;
  2033 
  2034 	// Now go through the forums and get us some topics...
  2035 	foreach ($forum_ids as $forum_id)
  2036 	{
  2037 		$sql = 'SELECT p.poster_id, p.topic_id
  2038 			FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t
  2039 			WHERE t.forum_id = ' . $forum_id . '
  2040 				AND t.topic_moved_id = 0
  2041 				AND t.topic_last_post_time > ' . $get_from_time . '
  2042 				AND t.topic_id = p.topic_id
  2043 				AND p.poster_id <> ' . ANONYMOUS . '
  2044 			GROUP BY p.poster_id, p.topic_id';
  2045 		$result = $db->sql_query($sql);
  2046 
  2047 		$posted = array();
  2048 		while ($row = $db->sql_fetchrow($result))
  2049 		{
  2050 			$posted[$row['poster_id']][] = $row['topic_id'];
  2051 		}
  2052 		$db->sql_freeresult($result);
  2053 
  2054 		$sql_ary = array();
  2055 		foreach ($posted as $user_id => $topic_row)
  2056 		{
  2057 			foreach ($topic_row as $topic_id)
  2058 			{
  2059 				$sql_ary[] = array(
  2060 					'user_id'		=> (int) $user_id,
  2061 					'topic_id'		=> (int) $topic_id,
  2062 					'topic_posted'	=> 1,
  2063 				);
  2064 			}
  2065 		}
  2066 		unset($posted);
  2067 
  2068 		if (sizeof($sql_ary))
  2069 		{
  2070 			$db->sql_multi_insert(TOPICS_POSTED_TABLE, $sql_ary);
  2071 		}
  2072 	}
  2073 }
  2074 
  2075 /**
  2076 * Ensure that all users have a default group specified and update related information such as their colour
  2077 */
  2078 function fix_empty_primary_groups()
  2079 {
  2080 	global $db;
  2081 
  2082 	// Set group ids for users not already having it
  2083 	$sql = 'UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('registered') . '
  2084 		WHERE group_id = 0 AND user_type = ' . USER_INACTIVE;
  2085 	$db->sql_query($sql);
  2086 
  2087 	$sql = 'UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('registered') . '
  2088 		WHERE group_id = 0 AND user_type = ' . USER_NORMAL;
  2089 	$db->sql_query($sql);
  2090 
  2091 	$db->sql_query('UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('guests') . ' WHERE user_id = ' . ANONYMOUS);
  2092 
  2093 	$sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . ' WHERE group_id = ' . get_group_id('administrators');
  2094 	$result = $db->sql_query($sql);
  2095 
  2096 	$user_ids = array();
  2097 	while ($row = $db->sql_fetchrow($result))
  2098 	{
  2099 		$user_ids[] = $row['user_id'];
  2100 	}
  2101 	$db->sql_freeresult($result);
  2102 
  2103 	if (sizeof($user_ids))
  2104 	{
  2105 		$db->sql_query('UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('administrators') . '
  2106 			WHERE group_id = 0 AND ' . $db->sql_in_set('user_id', $user_ids));
  2107 	}
  2108 
  2109 	$sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . ' WHERE group_id = ' . get_group_id('global_moderators');
  2110 
  2111 	$user_ids = array();
  2112 	while ($row = $db->sql_fetchrow($result))
  2113 	{
  2114 		$user_ids[] = $row['user_id'];
  2115 	}
  2116 	$db->sql_freeresult($result);
  2117 
  2118 	if (sizeof($user_ids))
  2119 	{
  2120 		$db->sql_query('UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('global_moderators') . '
  2121 			WHERE group_id = 0 AND ' . $db->sql_in_set('user_id', $user_ids));
  2122 	}
  2123 
  2124 	// Set user colour
  2125 	$sql = 'SELECT group_id, group_colour FROM ' . GROUPS_TABLE . "
  2126 		WHERE group_colour <> ''";
  2127 	$result = $db->sql_query($sql);
  2128 
  2129 	while ($row = $db->sql_fetchrow($result))
  2130 	{
  2131 		$db->sql_query('UPDATE ' . USERS_TABLE . " SET user_colour = '{$row['group_colour']}' WHERE group_id = {$row['group_id']}");
  2132 	}
  2133 	$db->sql_freeresult($result);
  2134 }
  2135 
  2136 /**
  2137 * Cleanly remove invalid user entries after converting the users table...
  2138 */
  2139 function remove_invalid_users()
  2140 {
  2141 	global $convert, $db, $phpEx, $phpbb_root_path;
  2142 
  2143 	// username_clean is UNIQUE
  2144 	$sql = 'SELECT user_id
  2145 		FROM ' . USERS_TABLE . "
  2146 		WHERE username_clean = ''";
  2147 	$result = $db->sql_query($sql);
  2148 	$row = $db->sql_fetchrow($result);
  2149 	$db->sql_freeresult($result);
  2150 
  2151 	if ($row)
  2152 	{
  2153 		if (!function_exists('user_delete'))
  2154 		{
  2155 			include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
  2156 		}
  2157 
  2158 		user_delete('remove', $row['user_id']);
  2159 	}
  2160 }
  2161 
  2162 function convert_bbcode($message, $convert_size = true, $extended_bbcodes = false)
  2163 {
  2164 	static $orig, $repl, $origx, $replx, $str_from, $str_to;
  2165 
  2166 	if (empty($orig))
  2167 	{
  2168 		$orig = $repl = array();
  2169 
  2170 		$orig[] = '#\[(php|sql)\](.*?)\[/(php|sql)\]#is';
  2171 		$repl[] = '[code]\2[/code]';
  2172 
  2173 		$orig[] = '#\[font=[^\]]+\](.*?)\[/font\]#is';
  2174 		$repl[] = '\1';
  2175 
  2176 		$orig[] = '#\[align=[a-z]+\](.*?)\[/align\]#is';
  2177 		$repl[] = '\1';
  2178 
  2179 		$orig[] = '#\[/list=.*?\]#is';
  2180 		$repl[] = '[/list]';
  2181 
  2182 		$origx = array(
  2183 			'#\[glow[^\]]+\](.*?)\[/glow\]#is',
  2184 			'#\[shadow[^\]]+\](.*?)\[/shadow\]#is',
  2185 			'#\[flash[^\]]+\](.*?)\[/flash\]#is'
  2186 		);
  2187 
  2188 		$replx = array(
  2189 			'\1',
  2190 			'\1',
  2191 			'[url=\1]Flash[/url]'
  2192 		);
  2193 
  2194 		$str_from = array(
  2195 			'[ftp]',	'[/ftp]',
  2196 			'[ftp=',	'[/ftp]',
  2197 			'[pre]',	'[/pre]',
  2198 			'[table]',	'[/table]',
  2199 			'[td]',		'[/td]',
  2200 			'[tr]',		'[/tr]',
  2201 			'[s]',		'[/s]',
  2202 			'[left]',	'[/left]',
  2203 			'[right]',	'[/right]',
  2204 			'[center]',	'[/center]',
  2205 			'[sub]',	'[/sub]',
  2206 			'[sup]',	'[/sup]',
  2207 			'[tt]',		'[/tt]',
  2208 			'[move]',	'[/move]',
  2209 			'[hr]'
  2210 		);
  2211 
  2212 		$str_to = array(
  2213 			'[url]',	'[/url]',
  2214 			'[url=',	'[/url]',
  2215 			'[code]',	'[/code]',
  2216 			"\n",		'',
  2217 			'',			'',
  2218 			"\n",		'',
  2219 			'',			'',
  2220 			'',			'',
  2221 			'',			'',
  2222 			'',			'',
  2223 			'',			'',
  2224 			'',			'',
  2225 			'',			'',
  2226 			'',			'',
  2227 			"\n\n"
  2228 		);
  2229 
  2230 		for ($i = 0; $i < sizeof($str_from); ++$i)
  2231 		{
  2232 			$origx[] = '#\\' . str_replace(']', '\\]', $str_from[$i]) . '#is';
  2233 			$replx[] = $str_to[$i];
  2234 		}
  2235 	}
  2236 
  2237 	if (preg_match_all('#\[email=([^\]]+)\](.*?)\[/email\]#i', $message, $m))
  2238 	{
  2239 		for ($i = 0; $i < sizeof($m[1]); ++$i)
  2240 		{
  2241 			if ($m[1][$i] == $m[2][$i])
  2242 			{
  2243 				$message = str_replace($m[0][$i], '[email]' . $m[1][$i] . '[/email]', $message);
  2244 			}
  2245 			else
  2246 			{
  2247 				$message = str_replace($m[0][$i], $m[2][$i] . ' ([email]' . $m[1][$i] . '[/email])', $message);
  2248 			}
  2249 		}
  2250 	}
  2251 
  2252 	if ($convert_size && preg_match('#\[size=[0-9]+\].*?\[/size\]#i', $message))
  2253 	{
  2254 		$size = array(9, 9, 12, 15, 18, 24, 29, 29, 29, 29);
  2255 		$message = preg_replace('#\[size=([0-9]+)\](.*?)\[/size\]#i', '[size=\1]\2[/size]', $message);
  2256 		$message = preg_replace('#\[size=[0-9]{2,}\](.*?)\[/size\]#i', '[size=29]\1[/size]', $message);
  2257 
  2258 		for ($i = sizeof($size); $i; )
  2259 		{
  2260 			$i--;
  2261 			$message = str_replace('[size=' . $i . ']', '[size=' . $size[$i] . ']', $message);
  2262 		}
  2263 	}
  2264 
  2265 	if ($extended_bbcodes)
  2266 	{
  2267 		$message = preg_replace($origx, $replx, $message);
  2268 	}
  2269 
  2270 	$message = preg_replace($orig, $repl, $message);
  2271 	return $message;
  2272 }
  2273 
  2274 
  2275 function copy_file($src, $trg, $overwrite = false, $die_on_failure = true, $source_relative_path = true)
  2276 {
  2277 	global $convert, $phpbb_root_path, $config, $user, $db;
  2278 
  2279 	if (substr($trg, -1) == '/')
  2280 	{
  2281 		$trg .= utf8_basename($src);
  2282 	}
  2283 	$src_path = relative_base($src, $source_relative_path, __LINE__, __FILE__);
  2284 	$trg_path = $trg;
  2285 
  2286 	if (!$overwrite && @file_exists($trg_path))
  2287 	{
  2288 		return true;
  2289 	}
  2290 
  2291 	if (!@file_exists($src_path))
  2292 	{
  2293 		return;
  2294 	}
  2295 
  2296 	$path = $phpbb_root_path;
  2297 	$parts = explode('/', $trg);
  2298 	unset($parts[sizeof($parts) - 1]);
  2299 
  2300 	for ($i = 0; $i < sizeof($parts); ++$i)
  2301 	{
  2302 		$path .= $parts[$i] . '/';
  2303 
  2304 		if (!is_dir($path))
  2305 		{
  2306 			@mkdir($path, 0777);
  2307 		}
  2308 	}
  2309 
  2310 	if (!phpbb_is_writable($path))
  2311 	{
  2312 		@chmod($path, 0777);
  2313 	}
  2314 
  2315 	if (!@copy($src_path, $phpbb_root_path . $trg_path))
  2316 	{
  2317 		$convert->p_master->error(sprintf($user->lang['COULD_NOT_COPY'], $src_path, $phpbb_root_path . $trg_path), __LINE__, __FILE__, !$die_on_failure);
  2318 		return;
  2319 	}
  2320 
  2321 	if ($perm = @fileperms($src_path))
  2322 	{
  2323 		@chmod($phpbb_root_path . $trg_path, $perm);
  2324 	}
  2325 
  2326 	return true;
  2327 }
  2328 
  2329 function copy_dir($src, $trg, $copy_subdirs = true, $overwrite = false, $die_on_failure = true, $source_relative_path = true)
  2330 {
  2331 	global $convert, $phpbb_root_path, $config, $user, $db;
  2332 
  2333 	$dirlist = $filelist = $bad_dirs = array();
  2334 	$src = path($src, $source_relative_path);
  2335 	$trg = path($trg);
  2336 	$src_path = relative_base($src, $source_relative_path, __LINE__, __FILE__);
  2337 	$trg_path = $phpbb_root_path . $trg;
  2338 
  2339 	if (!is_dir($trg_path))
  2340 	{
  2341 		@mkdir($trg_path, 0777);
  2342 		@chmod($trg_path, 0777);
  2343 	}
  2344 
  2345 	if (!phpbb_is_writable($trg_path))
  2346 	{
  2347 		$bad_dirs[] = path($config['script_path']) . $trg;
  2348 	}
  2349 
  2350 	if ($handle = @opendir($src_path))
  2351 	{
  2352 		while ($entry = readdir($handle))
  2353 		{
  2354 			if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
  2355 			{
  2356 				continue;
  2357 			}
  2358 
  2359 			if (is_dir($src_path . $entry))
  2360 			{
  2361 				$dirlist[] = $entry;
  2362 			}
  2363 			else
  2364 			{
  2365 				$filelist[] = $entry;
  2366 			}
  2367 		}
  2368 		closedir($handle);
  2369 	}
  2370 	else if ($dir = @dir($src_path))
  2371 	{
  2372 		while ($entry = $dir->read())
  2373 		{
  2374 			if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
  2375 			{
  2376 				continue;
  2377 			}
  2378 
  2379 			if (is_dir($src_path . $entry))
  2380 			{
  2381 				$dirlist[] = $entry;
  2382 			}
  2383 			else
  2384 			{
  2385 				$filelist[] = $entry;
  2386 			}
  2387 		}
  2388 		$dir->close();
  2389 	}
  2390 	else
  2391 	{
  2392 		$convert->p_master->error(sprintf($user->lang['CONV_ERROR_COULD_NOT_READ'], relative_base($src, $source_relative_path)), __LINE__, __FILE__);
  2393 	}
  2394 
  2395 	if ($copy_subdirs)
  2396 	{
  2397 		for ($i = 0; $i < sizeof($dirlist); ++$i)
  2398 		{
  2399 			$dir = $dirlist[$i];
  2400 
  2401 			if ($dir == 'CVS')
  2402 			{
  2403 				continue;
  2404 			}
  2405 
  2406 			if (!is_dir($trg_path . $dir))
  2407 			{
  2408 				@mkdir($trg_path . $dir, 0777);
  2409 				@chmod($trg_path . $dir, 0777);
  2410 			}
  2411 
  2412 			if (!phpbb_is_writable($trg_path . $dir))
  2413 			{
  2414 				$bad_dirs[] = $trg . $dir;
  2415 				$bad_dirs[] = $trg_path . $dir;
  2416 			}
  2417 
  2418 			if (!sizeof($bad_dirs))
  2419 			{
  2420 				copy_dir($src . $dir, $trg . $dir, true, $overwrite, $die_on_failure, $source_relative_path);
  2421 			}
  2422 		}
  2423 	}
  2424 
  2425 	if (sizeof($bad_dirs))
  2426 	{
  2427 		$str = (sizeof($bad_dirs) == 1) ? $user->lang['MAKE_FOLDER_WRITABLE'] : $user->lang['MAKE_FOLDERS_WRITABLE'];
  2428 		sort($bad_dirs);
  2429 		$convert->p_master->error(sprintf($str, implode('<br />', $bad_dirs)), __LINE__, __FILE__);
  2430 	}
  2431 
  2432 	for ($i = 0; $i < sizeof($filelist); ++$i)
  2433 	{
  2434 		copy_file($src . $filelist[$i], $trg . $filelist[$i], $overwrite, $die_on_failure, $source_relative_path);
  2435 	}
  2436 }
  2437 
  2438 function relative_base($path, $is_relative = true, $line = false, $file = false)
  2439 {
  2440 	global $convert, $phpbb_root_path, $config, $user, $db;
  2441 
  2442 	if (!$is_relative)
  2443 	{
  2444 		return $path;
  2445 	}
  2446 
  2447 	if (empty($convert->options['forum_path']) && $is_relative)
  2448 	{
  2449 		$line = $line ? $line : __LINE__;
  2450 		$file = $file ? $file : __FILE__;
  2451 
  2452 		$convert->p_master->error($user->lang['CONV_ERROR_NO_FORUM_PATH'], $line, $file);
  2453 	}
  2454 
  2455 	return $convert->options['forum_path'] . '/' . $path;
  2456 }
  2457 
  2458 function get_smiley_display()
  2459 {
  2460 	static $smiley_count = 0;
  2461 	$smiley_count++;
  2462 	return ($smiley_count < 50) ? 1 : 0;
  2463 }
  2464 
  2465 
  2466 function fill_dateformat($user_dateformat)
  2467 {
  2468 	global $config;
  2469 
  2470 	return ((empty($user_dateformat)) ? $config['default_dateformat'] : $user_dateformat);
  2471 }
  2472 
  2473 
  2474 
  2475 ?>