6 * @copyright (c) 2006 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
20 * Default avatar width/height
23 define('DEFAULT_AVATAR_X', 80);
24 define('DEFAULT_AVATAR_Y', 80);
26 // Global functions - all functions can be used by convertors
31 * Return the preceding value
39 * Return the next value
47 * Return whether the value is positive
49 function is_positive($n)
51 return ($n > 0) ? 1 : 0;
55 * Boolean inverse of the value
59 return ($var) ? 0 : 1;
63 * Convert a textual value to it's equivalent boolean value
65 * @param string $str String to convert (converts yes, on, y, 1 and true to boolean true)
66 * @return boolean The equivalent value
68 function str_to_bool($str)
70 $str = strtolower($str);
71 return ($str == 'yes' || $str == 'on' || $str == 'y' || $str == 'true' || $str == '1') ? true : false;
75 * Function to mimic php's empty() function (it is the same)
77 function is_empty($mixed)
83 * Convert the name of a user's primary group to the appropriate equivalent phpBB group id
85 * @param string $status The name of the group
86 * @return int The group_id corresponding to the equivalent group
88 function str_to_primary_group($status)
90 switch (ucfirst(strtolower($status)))
93 return get_group_id('administrators');
96 case 'Super moderator':
97 case 'Global moderator':
99 return get_group_id('global_moderators');
104 return get_group_id('guests');
108 return get_group_id('registered');
114 * Convert a boolean into the appropriate phpBB constant indicating whether the item is locked
116 function is_item_locked($bool)
118 return ($bool) ? ITEM_LOCKED : ITEM_UNLOCKED;
122 * Convert a value from days to seconds
124 function days_to_seconds($days)
126 return ($days * 86400);
130 * Determine whether a user is anonymous and return the appropriate new user_id
132 function is_user_anonymous($user_id)
134 return ($user_id > ANONYMOUS) ? $user_id : ANONYMOUS;
138 * Generate a key value based on existing values
140 * @param int $pad Amount to add to the maximum value
141 * @return int Key value
143 function auto_id($pad = 0)
145 global $auto_id, $convert_row;
147 if (!empty($convert_row['max_id']))
149 return $convert_row['max_id'] + $pad;
152 return $auto_id + $pad;
156 * Convert a boolean into the appropriate phpBB constant indicating whether the user is active
158 function set_user_type($user_active)
160 return ($user_active) ? USER_NORMAL : USER_INACTIVE;
164 * Convert a value from minutes to hours
166 function minutes_to_hours($minutes)
168 return ($minutes / 3600);
172 * Return the group_id for a given group name
174 function get_group_id($group_name)
176 global $db, $group_mapping;
178 if (empty($group_mapping))
180 $sql = 'SELECT group_name, group_id
181 FROM ' . GROUPS_TABLE;
182 $result = $db->sql_query($sql);
184 $group_mapping = array();
185 while ($row = $db->sql_fetchrow($result))
187 $group_mapping[strtoupper($row['group_name'])] = (int) $row['group_id'];
189 $db->sql_freeresult($result);
192 if (!sizeof($group_mapping))
194 add_default_groups();
195 return get_group_id($group_name);
198 if (isset($group_mapping[strtoupper($group_name)]))
200 return $group_mapping[strtoupper($group_name)];
203 return $group_mapping['REGISTERED'];
207 * Generate the email hash stored in the users table
209 * Note: Deprecated, calls should directly go to phpbb_email_hash()
211 function gen_email_hash($email)
213 return phpbb_email_hash($email);
217 * Convert a boolean into the appropriate phpBB constant indicating whether the topic is locked
219 function is_topic_locked($bool)
221 return (!empty($bool)) ? ITEM_LOCKED : ITEM_UNLOCKED;
225 * Generate a bbcode_uid value
227 function make_uid($timestamp)
229 static $last_timestamp, $last_uid;
231 if (empty($last_timestamp) || $timestamp != $last_timestamp)
233 $last_uid = substr(base_convert(unique_id(), 16, 36), 0, BBCODE_UID_LEN);
235 $last_timestamp = $timestamp;
241 * Validate a website address
243 function validate_website($url)
245 if ($url === 'http://')
249 else if (!preg_match('#^[a-z0-9]+://#i', $url) && strlen($url) > 0)
251 return 'http://' . $url;
257 * Convert nulls to zeros for fields which allowed a NULL value in the source but not the destination
259 function null_to_zero($value)
261 return ($value === NULL) ? 0 : $value;
265 * Convert nulls to empty strings for fields which allowed a NULL value in the source but not the destination
267 function null_to_str($value)
269 return ($value === NULL) ? '' : $value;
272 // EXTENDED FUNCTIONS
275 * Get old config value
277 function get_config_value($config_name)
279 static $convert_config;
281 if (!isset($convert_config))
283 $convert_config = get_config();
286 if (!isset($convert_config[$config_name]))
291 return (empty($convert_config[$config_name])) ? '' : $convert_config[$config_name];
295 * Convert an IP address from the hexadecimal notation to normal dotted-quad notation
297 function decode_ip($int_ip)
304 $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
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)
312 return hexdec($hexipbang[0]) . '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
316 * Reverse the encoding of wild-carded bans
318 function decode_ban_ip($int_ip)
320 return str_replace('255', '*', decode_ip($int_ip));
324 * Determine the MIME-type of a specified filename
325 * This does not actually inspect the file, but simply uses the file extension
327 function mimetype($filename)
329 if (!preg_match('/\.([a-z0-9]+)$/i', $filename, $m))
331 return 'application/octet-stream';
334 switch (strtolower($m[1]))
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';
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';
369 case 'wrd': return 'application/msword';
372 case 'ps': return 'application/postscript';
382 case 'php3': return 'text/plain';
383 default: return 'application/octet-stream';
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
393 function remote_avatar_dims()
397 $sql = 'SELECT user_id, user_avatar
398 FROM ' . USERS_TABLE . '
399 WHERE user_avatar_type = ' . AVATAR_REMOTE;
400 $result = $db->sql_query($sql);
402 $remote_avatars = array();
403 while ($row = $db->sql_fetchrow($result))
405 $remote_avatars[(int) $row['user_id']] = $row['user_avatar'];
407 $db->sql_freeresult($result);
409 foreach ($remote_avatars as $user_id => $avatar)
411 $width = (int) get_remote_avatar_dim($avatar, 0);
412 $height = (int) get_remote_avatar_dim($avatar, 1);
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);
421 function import_avatar_gallery($gallery_name = '', $subdirs_as_galleries = false)
423 global $config, $convert, $phpbb_root_path, $user;
425 $relative_path = empty($convert->convertor['source_path_absolute']);
427 if (empty($convert->convertor['avatar_gallery_path']))
429 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GALLERY_PATH'], 'import_avatar_gallery()'), __LINE__, __FILE__);
432 $src_path = relative_base(path($convert->convertor['avatar_gallery_path'], $relative_path), $relative_path);
434 if (is_dir($src_path))
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);
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)
445 if ($handle = @opendir($src_path))
447 while ($entry = readdir($handle))
449 if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
454 if (is_dir($src_path . $entry))
461 else if ($dir = @dir($src_path))
463 while ($entry = $dir->read())
465 if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
470 if (is_dir($src_path . $entry))
478 for ($i = 0; $i < sizeof($dirlist); ++$i)
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);
489 function import_attachment_files($category_name = '')
491 global $config, $convert, $phpbb_root_path, $db, $user;
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);
500 $relative_path = empty($convert->convertor['source_path_absolute']);
502 if (empty($convert->convertor['upload_path']))
504 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_UPLOAD_DIR'], 'import_attachment_files()'), __LINE__, __FILE__);
507 if (is_dir(relative_base(path($convert->convertor['upload_path'], $relative_path), $relative_path)))
509 copy_dir($convert->convertor['upload_path'], path($config['upload_path']) . $category_name, true, false, true, $relative_path);
513 function attachment_forum_perms($forum_id)
515 if (!is_array($forum_id))
517 $forum_id = array($forum_id);
520 return serialize($forum_id);
523 // base64todec function
524 // -> from php manual?
525 function base64_unpack($string)
527 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-';
528 $base = strlen($chars);
530 $length = strlen($string);
533 for ($i = 1; $i <= $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;
545 function _import_check($config_var, $source, $use_target)
547 global $convert, $config;
550 'orig_source' => $source,
552 'relative_path' => (empty($convert->convertor['source_path_absolute'])) ? true : false,
555 // copy file will prepend $phpBB_root_path
556 $target = $config[$config_var] . '/' . utf8_basename(($use_target === false) ? $source : $use_target);
558 if (!empty($convert->convertor[$config_var]) && strpos($source, $convert->convertor[$config_var]) !== 0)
560 $source = $convert->convertor[$config_var] . $source;
563 $result['source'] = $source;
565 if (file_exists(relative_base($source, $result['relative_path'], __LINE__, __FILE__)))
567 $result['copied'] = copy_file($source, $target, false, false, $result['relative_path']);
570 if ($result['copied'])
572 $result['target'] = utf8_basename($target);
576 $result['target'] = ($use_target !== false) ? $result['orig_source'] : utf8_basename($target);
582 function import_attachment($source, $use_target = false)
589 global $convert, $phpbb_root_path, $config, $user;
591 if (empty($convert->convertor['upload_path']))
593 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_UPLOAD_DIR'], 'import_attachment()'), __LINE__, __FILE__);
596 $result = _import_check('upload_path', $source, $use_target);
598 if ($result['copied'])
601 if (is_array($convert->convertor['thumbnails']))
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']);
607 if (strpos($thumb_source, $convert->convertor['upload_path']) !== 0)
609 $thumb_source = $convert->convertor['upload_path'] . $thumb_source;
611 $thumb_target = $config['upload_path'] . '/thumb_' . $result['target'];
613 if (file_exists(relative_base($thumb_source, $result['relative_path'], __LINE__, __FILE__)))
615 copy_file($thumb_source, $thumb_target, false, false, $result['relative_path']);
620 return $result['target'];
623 function import_rank($source, $use_target = false)
630 global $convert, $phpbb_root_path, $config, $user;
632 if (!isset($convert->convertor['ranks_path']))
634 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_RANKS_PATH'], 'import_rank()'), __LINE__, __FILE__);
637 $result = _import_check('ranks_path', $source, $use_target);
638 return $result['target'];
641 function import_smiley($source, $use_target = false)
648 global $convert, $phpbb_root_path, $config, $user;
650 if (!isset($convert->convertor['smilies_path']))
652 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_SMILIES_PATH'], 'import_smiley()'), __LINE__, __FILE__);
655 $result = _import_check('smilies_path', $source, $use_target);
656 return $result['target'];
661 function import_avatar($source, $use_target = false, $user_id = false)
663 if (empty($source) || preg_match('#^https?:#i', $source) || preg_match('#blank\.(gif|png)$#i', $source))
668 global $convert, $phpbb_root_path, $config, $user;
670 if (!isset($convert->convertor['avatar_path']))
672 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_AVATAR_PATH'], 'import_avatar()'), __LINE__, __FILE__);
675 if ($use_target === false && $user_id !== false)
677 $use_target = $config['avatar_salt'] . '_' . $user_id . '.' . substr(strrchr($source, '.'), 1);
680 $result = _import_check('avatar_path', $source, $use_target);
682 return ((!empty($user_id)) ? $user_id : $use_target) . '.' . substr(strrchr($source, '.'), 1);
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).
690 * Calculate the size of the specified image
691 * Called from the following functions for calculating the size of specific image types
693 function get_image_dim($source)
702 $relative_path = empty($convert->convertor['source_path_absolute']);
704 if (file_exists(relative_base($source, $relative_path)))
706 $image = relative_base($source, $relative_path);
707 return @getimagesize($image);
714 * Obtain the width of the specified smilie
716 function get_smiley_width($src)
718 return get_smiley_dim($src, 0);
722 * Obtain the height of the specified smilie
724 function get_smiley_height($src)
726 return get_smiley_dim($src, 1);
730 * Obtain the size of the specified smilie (using the cache if possible) and cache the value
732 function get_smiley_dim($source, $axis)
739 static $smiley_cache = array();
741 if (isset($smiley_cache[$source]))
743 return $smiley_cache[$source][$axis];
746 global $convert, $phpbb_root_path, $config, $user;
748 $orig_source = $source;
750 if (!isset($convert->convertor['smilies_path']))
752 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_SMILIES_PATH'], 'get_smiley_dim()'), __LINE__, __FILE__);
755 if (!empty($convert->convertor['smilies_path']) && strpos($source, $convert->convertor['smilies_path']) !== 0)
757 $source = $convert->convertor['smilies_path'] . $source;
760 $smiley_cache[$orig_source] = get_image_dim($source);
762 if (empty($smiley_cache[$orig_source]) || empty($smiley_cache[$orig_source][0]) || empty($smiley_cache[$orig_source][1]))
764 $smiley_cache[$orig_source] = array(15, 15);
768 return $smiley_cache[$orig_source][$axis];
772 * Obtain the width of the specified avatar
774 function get_avatar_width($src, $func = false, $arg1 = false, $arg2 = false)
776 return get_avatar_dim($src, 0, $func, $arg1, $arg2);
780 * Obtain the height of the specified avatar
782 function get_avatar_height($src, $func = false, $arg1 = false, $arg2 = false)
784 return get_avatar_dim($src, 1, $func, $arg1, $arg2);
789 function get_avatar_dim($src, $axis, $func = false, $arg1 = false, $arg2 = false)
791 $avatar_type = AVATAR_UPLOAD;
804 $avatar_type = call_user_func_array($func, $ary);
808 $avatar_type = call_user_func($func);
812 switch ($avatar_type)
815 return get_upload_avatar_dim($src, $axis);
819 return get_gallery_avatar_dim($src, $axis);
823 // see notes on this functions usage and (hopefully) model $func to avoid this accordingly
824 return get_remote_avatar_dim($src, $axis);
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;
831 return $axis ? $default_y : $default_x;
837 * Obtain the size of the specified uploaded avatar (using the cache if possible) and cache the value
839 function get_upload_avatar_dim($source, $axis)
841 static $cachedims = false;
842 static $cachekey = false;
849 if ($cachekey == $source)
851 return $cachedims[$axis];
854 $orig_source = $source;
856 if (substr($source, 0, 7) == 'upload:')
858 $source = substr($source, 7);
861 global $convert, $phpbb_root_path, $config, $user;
863 if (!isset($convert->convertor['avatar_path']))
865 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_AVATAR_PATH'], 'get_upload_avatar_dim()'), __LINE__, __FILE__);
868 if (!empty($convert->convertor['avatar_path']) && strpos($source, $convert->convertor['avatar_path']) !== 0)
870 $source = path($convert->convertor['avatar_path'], empty($convert->convertor['source_path_absolute'])) . $source;
873 $cachedims = get_image_dim($source);
875 if (empty($cachedims) || empty($cachedims[0]) || empty($cachedims[1]))
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;
880 $cachedims = array($default_x, $default_y);
883 return $cachedims[$axis];
887 * Obtain the size of the specified gallery avatar (using the cache if possible) and cache the value
889 function get_gallery_avatar_dim($source, $axis)
896 static $avatar_cache = array();
898 if (isset($avatar_cache[$source]))
900 return $avatar_cache[$source][$axis];
903 global $convert, $phpbb_root_path, $config, $user;
905 $orig_source = $source;
907 if (!isset($convert->convertor['avatar_gallery_path']))
909 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GALLERY_PATH'], 'get_gallery_avatar_dim()'), __LINE__, __FILE__);
912 if (!empty($convert->convertor['avatar_gallery_path']) && strpos($source, $convert->convertor['avatar_gallery_path']) !== 0)
914 $source = path($convert->convertor['avatar_gallery_path'], empty($convert->convertor['source_path_absolute'])) . $source;
917 $avatar_cache[$orig_source] = get_image_dim($source);
919 if (empty($avatar_cache[$orig_source]) || empty($avatar_cache[$orig_source][0]) || empty($avatar_cache[$orig_source][1]))
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;
924 $avatar_cache[$orig_source] = array($default_x, $default_y);
927 return $avatar_cache[$orig_source][$axis];
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
935 function get_remote_avatar_dim($src, $axis)
942 static $remote_avatar_cache = array();
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]))
947 $retval = $remote_avatar_cache[$src][$axis];
948 unset($remote_avatar_cache);
952 $url_info = @parse_url($src);
953 if (empty($url_info['host']))
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';
962 switch(strtolower($protocol))
977 $timeout = @ini_get('default_socket_timeout');
978 @ini_set('default_socket_timeout', 2);
980 // We're just trying to reach the server to avoid timeouts
981 $fp = @fsockopen($host, $port, $errno, $errstr, 1);
984 $remote_avatar_cache[$src] = @getimagesize($src);
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);
992 if (empty($remote_avatar_cache[$src]) || empty($remote_avatar_cache[$src][0]) || empty($remote_avatar_cache[$src][1]))
994 $remote_avatar_cache[$src] = $default;
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)
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);
1008 @ini_set('default_socket_timeout', $timeout);
1009 return $remote_avatar_cache[$src][$axis];
1012 function set_user_options()
1014 global $convert_row;
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),
1035 foreach ($keyoptions as $key => $key_ary)
1037 $value = (isset($convert_row[$key])) ? (int) $convert_row[$key] : $key_ary['default'];
1039 if ($value && !($option_field & 1 << $key_ary['bit']))
1041 $option_field += 1 << $key_ary['bit'];
1045 return $option_field;
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 = '')
1053 global $fulltext_search, $convert_row;
1055 if (!isset($convert_row['post_id']))
1062 if (!isset($convert_row['message']))
1067 $message = $convert_row['message'];
1070 $title = (isset($convert_row['title'])) ? $convert_row['title'] : '';
1072 $fulltext_search->index('post', $convert_row['post_id'], $message, $title, $convert_row['poster_id'], $convert_row['forum_id']);
1076 function make_unique_filename($filename)
1078 if (!strlen($filename))
1080 $filename = md5(unique_id()) . '.dat';
1082 else if ($filename[0] == '.')
1084 $filename = md5(unique_id()) . $filename;
1086 else if (preg_match('/\.([a-z]+)$/i', $filename, $m))
1088 $filename = preg_replace('/\.([a-z]+)$/i', '_' . md5(unique_id()) . '.\1', $filename);
1092 $filename .= '_' . md5(unique_id()) . '.dat';
1098 function words_unique(&$words)
1101 $return_array = array();
1103 $word = current($words);
1106 $return_array[$word] = $word;
1108 while ($word = next($words));
1110 return $return_array;
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
1117 function add_user_group($group_id, $user_id, $group_leader=false)
1119 global $convert, $phpbb_root_path, $config, $user, $db;
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);
1129 // STANDALONE FUNCTIONS
1132 * Add users to the pre-defined "special" groups
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
1137 function user_group_auth($group, $select_query, $use_src_db)
1139 global $convert, $phpbb_root_path, $config, $user, $db, $src_db, $same_db;
1141 if (!in_array($group, array('guests', 'registered', 'registered_coppa', 'global_moderators', 'administrators', 'bots')))
1143 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_WRONG_GROUP'], $group, 'user_group_auth()'), __LINE__, __FILE__, true);
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);
1156 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GROUP'], $group, 'user_group_auth()'), __LINE__, __FILE__, true);
1160 if ($same_db || !$use_src_db)
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);
1168 $result = $src_db->sql_query(str_replace('{' . strtoupper($group) . '}', $group_id . ' ', $select_query));
1169 while ($row = $src_db->sql_fetchrow($result))
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);
1176 $src_db->sql_freeresult($result);
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)
1185 function get_config()
1187 static $convert_config;
1190 if (isset($convert_config))
1192 return $convert_config;
1195 global $src_db, $same_db, $phpbb_root_path, $config;
1198 if ($convert->config_schema['table_format'] != 'file')
1200 if ($convert->mysql_convert && $same_db)
1202 $src_db->sql_query("SET NAMES 'binary'");
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);
1211 $convert->p_master->error($user->lang['CONV_ERROR_GET_CONFIG'], __LINE__, __FILE__);
1215 if (is_array($convert->config_schema['table_format']))
1217 $convert_config = array();
1218 list($key, $val) = each($convert->config_schema['table_format']);
1222 $convert_config[$row[$key]] = $row[$val];
1224 while ($row = $src_db->sql_fetchrow($result));
1225 $src_db->sql_freeresult($result);
1227 if ($convert->mysql_convert && $same_db)
1229 $src_db->sql_query("SET NAMES 'utf8'");
1232 else if ($convert->config_schema['table_format'] == 'file')
1234 $filename = $convert->options['forum_path'] . '/' . $convert->config_schema['filename'];
1235 if (!file_exists($filename))
1237 $convert->p_master->error($user->lang['FILE_NOT_FOUND'] . ': ' . $filename, __LINE__, __FILE__);
1240 if (isset($convert->config_schema['array_name']))
1242 unset($convert->config_schema['array_name']);
1245 $convert_config = extract_variables_from_file($filename);
1246 if (!empty($convert->config_schema['array_name']))
1248 $convert_config = $convert_config[$convert->config_schema['array_name']];
1253 $convert_config = $row;
1254 if ($convert->mysql_convert && $same_db)
1256 $src_db->sql_query("SET NAMES 'utf8'");
1260 if (!sizeof($convert_config))
1262 $convert->p_master->error($user->lang['CONV_ERROR_CONFIG_EMPTY'], __LINE__, __FILE__);
1265 return $convert_config;
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
1272 function restore_config($schema)
1274 global $db, $config;
1276 $convert_config = get_config();
1278 foreach ($schema['settings'] as $config_name => $src)
1280 if (preg_match('/(.*)\((.*)\)/', $src, $m))
1282 $var = (empty($m[2]) || empty($convert_config[$m[2]])) ? "''" : "'" . addslashes($convert_config[$m[2]]) . "'";
1283 $exec = '$config_value = ' . $m[1] . '(' . $var . ');';
1288 if ($schema['table_format'] != 'file' || empty($schema['array_name']))
1290 $config_value = (isset($convert_config[$src])) ? $convert_config[$src] : '';
1292 else if (!empty($schema['array_name']))
1294 $src_ary = $schema['array_name'];
1295 $config_value = (isset($convert_config[$src_ary][$src])) ? $convert_config[$src_ary][$src] : '';
1299 if ($config_value !== '')
1302 if (is_string($config_value))
1304 $config_value = truncate_string(utf8_htmlspecialchars($config_value), 255, 255, false);
1307 set_config($config_name, $config_value);
1313 * Update the count of PM's in custom folders for all users
1315 function update_folder_pm_count()
1317 global $db, $convert, $user;
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);
1325 while ($row = $db->sql_fetchrow($result))
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']);
1330 $db->sql_freeresult($result);
1333 // Functions mainly used by the main convertor script
1335 function path($path, $path_relative = true)
1337 if ($path === false)
1342 if (substr($path, -1) != '/')
1347 if (!$path_relative)
1352 if (substr($path, 0, 1) == '/')
1354 $path = substr($path, 1);
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
1364 function extract_variables_from_file($_filename)
1366 include($_filename);
1368 $vars = get_defined_vars();
1369 unset($vars['_filename']);
1374 function get_path($src_path, $src_url, $test_file)
1376 global $config, $phpbb_root_path, $phpEx;
1378 $board_config = get_config();
1380 $test_file = preg_replace('/\.php$/i', ".$phpEx", $test_file);
1381 $src_path = path($src_path);
1383 if (@file_exists($phpbb_root_path . $src_path . $test_file))
1388 if (!empty($src_url) && !empty($board_config['server_name']))
1390 if (!preg_match('#https?://([^/]+)(.*)#i', $src_url, $m))
1395 if ($m[1] != $board_config['server_name'])
1400 $url_parts = explode('/', $m[2]);
1401 if (substr($src_url, -1) != '/')
1403 if (preg_match('/.*\.([a-z0-9]{3,4})$/i', $url_parts[sizeof($url_parts) - 1]))
1405 $url_parts[sizeof($url_parts) - 1] = '';
1413 $script_path = $board_config['script_path'];
1414 if (substr($script_path, -1) == '/')
1416 $script_path = substr($script_path, 0, -1);
1419 $path_array = array();
1421 $phpbb_parts = explode('/', $script_path);
1422 for ($i = 0; $i < sizeof($url_parts); ++$i)
1424 if ($i < sizeof($phpbb_parts[$i]) && $url_parts[$i] == $phpbb_parts[$i])
1426 $path_array[] = $url_parts[$i];
1427 unset($url_parts[$i]);
1432 for ($j = $i; $j < sizeof($phpbb_parts); ++$j)
1436 $path .= implode('/', $url_parts);
1443 if (@file_exists($phpbb_root_path . $path . $test_file))
1453 function compare_table($tables, $tablename, &$prefixes)
1455 for ($i = 0, $table_size = sizeof($tables); $i < $table_size; ++$i)
1457 if (preg_match('/(.*)' . $tables[$i] . '$/', $tablename, $m))
1464 if (isset($prefixes[$m[1]]))
1470 $prefixes[$m[1]] = 1;
1477 * Grant permissions to a specified user or group
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
1485 function mass_auth($ug_type, $forum_id, $ug_id, $acl_list, $setting = ACL_NO)
1487 global $db, $convert, $user, $config;
1488 static $acl_option_ids, $group_ids;
1490 if (($ug_type == 'group' || $ug_type == 'group_role') && is_string($ug_id))
1492 if (!isset($group_ids[$ug_id]))
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);
1506 $group_ids[$ug_id] = $id;
1509 $ug_id = (int) $group_ids[$ug_id];
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';
1515 // Role based permissions are the simplest to handle so check for them first
1516 if ($ug_type == 'user_role' || $ug_type == 'group_role')
1518 if (is_numeric($forum_id))
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);
1527 // If we have no role id there is something wrong here
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);
1538 // Build correct parameters
1541 if (!is_array($acl_list))
1543 $auth = array($acl_list => $setting);
1547 foreach ($acl_list as $auth_option)
1549 $auth[$auth_option] = $setting;
1554 if (!is_array($forum_id))
1556 $forum_id = array($forum_id);
1559 // Set any flags as required
1560 foreach ($auth as $auth_option => $acl_setting)
1562 $flag = substr($auth_option, 0, strpos($auth_option, '_') + 1);
1563 if (empty($auth[$flag]))
1565 $auth[$flag] = $acl_setting;
1569 if (!is_array($acl_option_ids) || empty($acl_option_ids))
1571 $sql = 'SELECT auth_option_id, auth_option
1572 FROM ' . ACL_OPTIONS_TABLE;
1573 $result = $db->sql_query($sql);
1575 while ($row = $db->sql_fetchrow($result))
1577 $acl_option_ids[$row['auth_option']] = $row['auth_option_id'];
1579 $db->sql_freeresult($result);
1582 $sql_forum = 'AND ' . $db->sql_in_set('a.forum_id', array_map('intval', $forum_id), false, true);
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);
1587 $cur_auth = array();
1588 while ($row = $db->sql_fetchrow($result))
1590 $cur_auth[$row['forum_id']][$row['auth_option_id']] = $row['auth_setting'];
1592 $db->sql_freeresult($result);
1595 foreach ($forum_id as $forum)
1597 foreach ($auth as $auth_option => $setting)
1599 $auth_option_id = $acl_option_ids[$auth_option];
1601 if (!$auth_option_id)
1609 if (isset($cur_auth[$forum][$auth_option_id]))
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";
1619 if (!isset($cur_auth[$forum][$auth_option_id]))
1621 $sql_ary['insert'][] = "$ug_id, $forum, $auth_option_id, $setting";
1623 else if ($cur_auth[$forum][$auth_option_id] != $setting)
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";
1637 foreach ($sql_ary as $sql_type => $sql_subary)
1642 switch ($db->sql_layer)
1646 $sql = 'VALUES ' . implode(', ', preg_replace('#^(.*?)$#', '(\1)', $sql_subary));
1652 $sql = implode(' UNION ALL ', preg_replace('#^(.*?)$#', 'SELECT \1', $sql_subary));
1656 foreach ($sql_subary as $sql)
1658 $sql = "INSERT INTO $table ($id_field, forum_id, auth_option_id, auth_setting) VALUES ($sql)";
1659 $db->sql_query($sql);
1666 $sql = "INSERT INTO $table ($id_field, forum_id, auth_option_id, auth_setting) $sql";
1667 $db->sql_query($sql);
1673 foreach ($sql_subary as $sql)
1675 $db->sql_query($sql);
1680 unset($sql_ary[$sql_type]);
1687 * Update the count of unread private messages for all users
1689 function update_unread_count()
1693 $sql = 'SELECT user_id, COUNT(msg_id) as num_messages
1694 FROM ' . PRIVMSGS_TO_TABLE . '
1696 AND folder_id <> ' . PRIVMSGS_OUTBOX . '
1698 $result = $db->sql_query($sql);
1700 while ($row = $db->sql_fetchrow($result))
1702 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_unread_privmsg = ' . $row['num_messages'] . '
1703 WHERE user_id = ' . $row['user_id']);
1705 $db->sql_freeresult($result);
1709 * Add any of the pre-defined "special" groups which are missing from the database
1711 function add_default_groups()
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),
1726 FROM ' . GROUPS_TABLE . '
1727 WHERE ' . $db->sql_in_set('group_name', array_keys($default_groups));
1728 $result = $db->sql_query($sql);
1730 while ($row = $db->sql_fetchrow($result))
1732 unset($default_groups[strtoupper($row['group_name'])]);
1734 $db->sql_freeresult($result);
1738 foreach ($default_groups as $name => $data)
1741 'group_name' => (string) $name,
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]
1752 if (sizeof($sql_ary))
1754 $db->sql_multi_insert(GROUPS_TABLE, $sql_ary);
1760 * Sync post count. We might need to do this in batches.
1762 function sync_post_count($offset, $limit)
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
1770 ORDER BY poster_id';
1771 $result = $db->sql_query_limit($sql, $limit, $offset);
1773 while ($row = $db->sql_fetchrow($result))
1775 $db->sql_query('UPDATE ' . USERS_TABLE . " SET user_posts = {$row['num_posts']} WHERE user_id = {$row['poster_id']}");
1777 $db->sql_freeresult($result);
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
1788 global $db, $convert, $user, $config, $phpbb_root_path, $phpEx;
1790 $db->sql_query($convert->truncate_statement . BOTS_TABLE);
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);
1799 add_default_groups();
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);
1809 $install->error($user->lang['CONV_ERROR_INCONSISTENT_GROUPS'], __LINE__, __FILE__);
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/', ''),
1867 if (!function_exists('user_add'))
1869 include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
1872 foreach ($bots as $bot_name => $bot_ary)
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',
1882 'user_lang' => $config['default_lang'],
1884 'user_timezone' => 0,
1885 'user_allow_massemail' => 0,
1888 $user_id = user_add($user_row);
1892 $sql = 'INSERT INTO ' . BOTS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
1894 'bot_name' => $bot_name,
1895 'user_id' => $user_id,
1896 'bot_agent' => $bot_ary[0],
1897 'bot_ip' => $bot_ary[1])
1899 $db->sql_query($sql);
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
1908 function update_dynamic_config()
1910 global $db, $config;
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 . ')';
1917 if (!empty($config['increment_user_id']))
1919 $sql .= ' AND user_id <> ' . $config['increment_user_id'];
1922 $sql .= ' ORDER BY user_id DESC';
1924 $result = $db->sql_query_limit($sql, 1);
1925 $row = $db->sql_fetchrow($result);
1926 $db->sql_freeresult($result);
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);
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);
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);
1946 set_config('num_posts', (int) $row['stat'], true);
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);
1955 set_config('num_topics', (int) $row['stat'], true);
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);
1964 set_config('num_users', (int) $row['stat'], true);
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);
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);
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);
1988 while ($row = $db->sql_fetchrow($result))
1990 $db->sql_query('UPDATE ' . USERS_TABLE . " SET user_posts = {$row['num_posts']} WHERE user_id = {$row['poster_id']}");
1992 $db->sql_freeresult($result);
1997 * Updates topics_posted entries
1999 function update_topics_posted()
2001 global $db, $config;
2003 switch ($db->sql_layer)
2007 $db->sql_query('DELETE FROM ' . TOPICS_POSTED_TABLE);
2011 $db->sql_query('TRUNCATE TABLE ' . TOPICS_POSTED_TABLE);
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);
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);
2024 $forum_ids = array();
2025 while ($row = $db->sql_fetchrow($result))
2027 $forum_ids[] = $row['forum_id'];
2029 $db->sql_freeresult($result);
2031 // Any global announcements? ;)
2034 // Now go through the forums and get us some topics...
2035 foreach ($forum_ids as $forum_id)
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);
2048 while ($row = $db->sql_fetchrow($result))
2050 $posted[$row['poster_id']][] = $row['topic_id'];
2052 $db->sql_freeresult($result);
2055 foreach ($posted as $user_id => $topic_row)
2057 foreach ($topic_row as $topic_id)
2060 'user_id' => (int) $user_id,
2061 'topic_id' => (int) $topic_id,
2062 'topic_posted' => 1,
2068 if (sizeof($sql_ary))
2070 $db->sql_multi_insert(TOPICS_POSTED_TABLE, $sql_ary);
2076 * Ensure that all users have a default group specified and update related information such as their colour
2078 function fix_empty_primary_groups()
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);
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);
2091 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET group_id = ' . get_group_id('guests') . ' WHERE user_id = ' . ANONYMOUS);
2093 $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . ' WHERE group_id = ' . get_group_id('administrators');
2094 $result = $db->sql_query($sql);
2096 $user_ids = array();
2097 while ($row = $db->sql_fetchrow($result))
2099 $user_ids[] = $row['user_id'];
2101 $db->sql_freeresult($result);
2103 if (sizeof($user_ids))
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));
2109 $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . ' WHERE group_id = ' . get_group_id('global_moderators');
2111 $user_ids = array();
2112 while ($row = $db->sql_fetchrow($result))
2114 $user_ids[] = $row['user_id'];
2116 $db->sql_freeresult($result);
2118 if (sizeof($user_ids))
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));
2125 $sql = 'SELECT group_id, group_colour FROM ' . GROUPS_TABLE . "
2126 WHERE group_colour <> ''";
2127 $result = $db->sql_query($sql);
2129 while ($row = $db->sql_fetchrow($result))
2131 $db->sql_query('UPDATE ' . USERS_TABLE . " SET user_colour = '{$row['group_colour']}' WHERE group_id = {$row['group_id']}");
2133 $db->sql_freeresult($result);
2137 * Cleanly remove invalid user entries after converting the users table...
2139 function remove_invalid_users()
2141 global $convert, $db, $phpEx, $phpbb_root_path;
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);
2153 if (!function_exists('user_delete'))
2155 include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
2158 user_delete('remove', $row['user_id']);
2162 function convert_bbcode($message, $convert_size = true, $extended_bbcodes = false)
2164 static $orig, $repl, $origx, $replx, $str_from, $str_to;
2168 $orig = $repl = array();
2170 $orig[] = '#\[(php|sql)\](.*?)\[/(php|sql)\]#is';
2171 $repl[] = '[code]\2[/code]';
2173 $orig[] = '#\[font=[^\]]+\](.*?)\[/font\]#is';
2176 $orig[] = '#\[align=[a-z]+\](.*?)\[/align\]#is';
2179 $orig[] = '#\[/list=.*?\]#is';
2180 $repl[] = '[/list]';
2183 '#\[glow[^\]]+\](.*?)\[/glow\]#is',
2184 '#\[shadow[^\]]+\](.*?)\[/shadow\]#is',
2185 '#\[flash[^\]]+\](.*?)\[/flash\]#is'
2191 '[url=\1]Flash[/url]'
2198 '[table]', '[/table]',
2202 '[left]', '[/left]',
2203 '[right]', '[/right]',
2204 '[center]', '[/center]',
2208 '[move]', '[/move]',
2215 '[code]', '[/code]',
2230 for ($i = 0; $i < sizeof($str_from); ++$i)
2232 $origx[] = '#\\' . str_replace(']', '\\]', $str_from[$i]) . '#is';
2233 $replx[] = $str_to[$i];
2237 if (preg_match_all('#\[email=([^\]]+)\](.*?)\[/email\]#i', $message, $m))
2239 for ($i = 0; $i < sizeof($m[1]); ++$i)
2241 if ($m[1][$i] == $m[2][$i])
2243 $message = str_replace($m[0][$i], '[email]' . $m[1][$i] . '[/email]', $message);
2247 $message = str_replace($m[0][$i], $m[2][$i] . ' ([email]' . $m[1][$i] . '[/email])', $message);
2252 if ($convert_size && preg_match('#\[size=[0-9]+\].*?\[/size\]#i', $message))
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);
2258 for ($i = sizeof($size); $i; )
2261 $message = str_replace('[size=' . $i . ']', '[size=' . $size[$i] . ']', $message);
2265 if ($extended_bbcodes)
2267 $message = preg_replace($origx, $replx, $message);
2270 $message = preg_replace($orig, $repl, $message);
2275 function copy_file($src, $trg, $overwrite = false, $die_on_failure = true, $source_relative_path = true)
2277 global $convert, $phpbb_root_path, $config, $user, $db;
2279 if (substr($trg, -1) == '/')
2281 $trg .= utf8_basename($src);
2283 $src_path = relative_base($src, $source_relative_path, __LINE__, __FILE__);
2286 if (!$overwrite && @file_exists($trg_path))
2291 if (!@file_exists($src_path))
2296 $path = $phpbb_root_path;
2297 $parts = explode('/', $trg);
2298 unset($parts[sizeof($parts) - 1]);
2300 for ($i = 0; $i < sizeof($parts); ++$i)
2302 $path .= $parts[$i] . '/';
2306 @mkdir($path, 0777);
2310 if (!phpbb_is_writable($path))
2312 @chmod($path, 0777);
2315 if (!@copy($src_path, $phpbb_root_path . $trg_path))
2317 $convert->p_master->error(sprintf($user->lang['COULD_NOT_COPY'], $src_path, $phpbb_root_path . $trg_path), __LINE__, __FILE__, !$die_on_failure);
2321 if ($perm = @fileperms($src_path))
2323 @chmod($phpbb_root_path . $trg_path, $perm);
2329 function copy_dir($src, $trg, $copy_subdirs = true, $overwrite = false, $die_on_failure = true, $source_relative_path = true)
2331 global $convert, $phpbb_root_path, $config, $user, $db;
2333 $dirlist = $filelist = $bad_dirs = array();
2334 $src = path($src, $source_relative_path);
2336 $src_path = relative_base($src, $source_relative_path, __LINE__, __FILE__);
2337 $trg_path = $phpbb_root_path . $trg;
2339 if (!is_dir($trg_path))
2341 @mkdir($trg_path, 0777);
2342 @chmod($trg_path, 0777);
2345 if (!phpbb_is_writable($trg_path))
2347 $bad_dirs[] = path($config['script_path']) . $trg;
2350 if ($handle = @opendir($src_path))
2352 while ($entry = readdir($handle))
2354 if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
2359 if (is_dir($src_path . $entry))
2361 $dirlist[] = $entry;
2365 $filelist[] = $entry;
2370 else if ($dir = @dir($src_path))
2372 while ($entry = $dir->read())
2374 if ($entry[0] == '.' || $entry == 'CVS' || $entry == 'index.htm')
2379 if (is_dir($src_path . $entry))
2381 $dirlist[] = $entry;
2385 $filelist[] = $entry;
2392 $convert->p_master->error(sprintf($user->lang['CONV_ERROR_COULD_NOT_READ'], relative_base($src, $source_relative_path)), __LINE__, __FILE__);
2397 for ($i = 0; $i < sizeof($dirlist); ++$i)
2399 $dir = $dirlist[$i];
2406 if (!is_dir($trg_path . $dir))
2408 @mkdir($trg_path . $dir, 0777);
2409 @chmod($trg_path . $dir, 0777);
2412 if (!phpbb_is_writable($trg_path . $dir))
2414 $bad_dirs[] = $trg . $dir;
2415 $bad_dirs[] = $trg_path . $dir;
2418 if (!sizeof($bad_dirs))
2420 copy_dir($src . $dir, $trg . $dir, true, $overwrite, $die_on_failure, $source_relative_path);
2425 if (sizeof($bad_dirs))
2427 $str = (sizeof($bad_dirs) == 1) ? $user->lang['MAKE_FOLDER_WRITABLE'] : $user->lang['MAKE_FOLDERS_WRITABLE'];
2429 $convert->p_master->error(sprintf($str, implode('<br />', $bad_dirs)), __LINE__, __FILE__);
2432 for ($i = 0; $i < sizeof($filelist); ++$i)
2434 copy_file($src . $filelist[$i], $trg . $filelist[$i], $overwrite, $die_on_failure, $source_relative_path);
2438 function relative_base($path, $is_relative = true, $line = false, $file = false)
2440 global $convert, $phpbb_root_path, $config, $user, $db;
2447 if (empty($convert->options['forum_path']) && $is_relative)
2449 $line = $line ? $line : __LINE__;
2450 $file = $file ? $file : __FILE__;
2452 $convert->p_master->error($user->lang['CONV_ERROR_NO_FORUM_PATH'], $line, $file);
2455 return $convert->options['forum_path'] . '/' . $path;
2458 function get_smiley_display()
2460 static $smiley_count = 0;
2462 return ($smiley_count < 50) ? 1 : 0;
2466 function fill_dateformat($user_dateformat)
2470 return ((empty($user_dateformat)) ? $config['default_dateformat'] : $user_dateformat);