GetVariable('import_category_id');
if ( isset($_POST['Action']) && $_POST['Action'] == 'Import')
{
	$objSession->SetVariable('import_user_admin',$_POST['user_admin']);
	$objSession->SetVariable('import_user_regular',$_POST['user_regular']);
	$objSession->SetVariable('image_name',$_POST['link_image']);
	$objSession->SetVariable('importtodo','initialize');
	$objSession->SetVariable('importstart',0);
	$objSession->SetVariable('importtotal',0);
	if((int)$_POST['init_cat'] > 0)
	{
		$c = $objCatList->GetItemByField('CategoryId', $root_cat_id);
		$c->UpdateACL();
		$c->UpdateCachedPath();
	}
}
$allgroups = $objGroups->GetAllGroupList();
// connection related
$inlink_sql_type	=	$objSession->GetVariable('import_sql_type');
$inlink_server		=	$objSession->GetVariable('import_server');
$inlink_db			=	$objSession->GetVariable('import_db');
$inlink_user		=	$objSession->GetVariable('import_user');
$inlink_pass		=	$objSession->GetVariable('import_pass');
// import related
$user_admin			=	$objSession->GetVariable('user_admin_values');
$user_regular		=	$objSession->GetVariable('user_regular_values');
if( !isset($c) || !is_object($c) && $root_cat_id )
$c = $objCatList->GetItemByField('CategoryId', $root_cat_id);
$image_name=$objSession->GetVariable('image_name');
$start = $objSession->GetVariable('importstart');
$init_cat = $root_cat_id ? $c->Get('CategoryId') : 0;
//In-Portal
$portalconn = &GetADODBConnection();
if( $init_cat == 0)
{
	/*$prefix = GetTablePrefix();
	$sql = 'SELECT ACL 
			FROM '.$prefix.'PermCache pc, '.$prefix.'Permissions p
			WHERE p.PermissionId = pc.PermId AND p.CategoryId = 0 AND p.Permission = \'CATEGORY.VIEW\'';
	$acl = $portalconn->GetCol($sql);*/
	$acl = Array(0 => 0);
}
else
{
	$acl = explode(',',$c->GetACL('CATEGORY.VIEW'));
}
//IN-LINK connection
$linkconn = &ADONewConnection($inlink_sql_type);
$linkconn->NConnect($inlink_server, $inlink_user, $inlink_pass, $inlink_db);
if(!$linkconn)
{	echo "Database connection failed. DB Type: $sql_type, DB Server: $inlink_server, DB User: $inlink_user, DB Name: $inlink_db"; //fatal;
echo $linkconn->ErrorMsg();
die();
}
//admin only util
$pathtolocal = $pathtoroot.'kernel/';
require_once ($pathtoroot.'admin/include/elements.php');
require_once ($pathtoroot.'kernel/admin/include/navmenu.php');
require_once ($pathtolocal.'admin/include/navmenu.php');
require_once($pathtoroot.'admin/toolbar.php');
//Set Section
$section = 'in-portal:inlink_inport';
//Set Environment Variable
$envar = 'env=' . BuildEnv();
$sec = $objSections->GetSection($section);
$objCatToolBar = new clsToolBar();
$title = admin_language('la_performing_import').' - '.admin_language('la_Step').' 4';
$TablePrefix = 'ses_'.$objSession->GetSessionKey().'_'.GetTablePrefix();
$olddbname=$inlink_db;
//$newdbname='inportal';
$newdbname=$g_DBName;
##############creating a temproary table have to be here
if( GetVar('Action', true) == 'Import' )
{
	$portalconn->Execute('DROP TABLE IF EXISTS '.$TablePrefix.'import');
	$portalconn->Execute('DROP TABLE IF EXISTS '.$TablePrefix.'importcat');
	$temptable = 'CREATE TABLE '.$TablePrefix.'import (otname varchar(40), oid int(11), ocustomid int(11), oparentid int(11), ntname varchar(40), nid int(11), nrid int(11), npid int(11)) ';
	$portalconn->Execute($temptable);
	$cattable ='CREATE TABLE '.$TablePrefix.'importcat (op int(11), np int(11), flag int(11)) ';
	$portalconn->Execute($cattable);
	$newcat = 1;
}
global $admin, $pathtoroot;
require_once ($pathtoroot.'in-link/'.$admin.'/import/status.php'); #for status bar and all visual effects
$todo= $objSession->GetVariable('importtodo');
$total = $objSession->GetVariable('importtotal');
switch ($todo)
{
	case 'users':
	status($start, $total, 'users');
	usersimport();
	//setstart(0,'cats'); #for debugging
	break;
	case 'cats':
	status($start, $total, 'cats');
	catmanager();
	//setstart(0,'links'); #for debugging
	break;
	case 'links':
	status($start, $total, 'links');
	linksimport();
	//setstart(0,'custom');#For debugging only
	break;
	case 'custom':
		status($start, $total, 'custom');
	
		customimport();
		//setstart(0,'relcat');#for debuggin only
		break;
		
	case 'relcat':
	status($start, $total, 'relcat');
	relcatimport();
	//setstart(0,'terminate'); #for debuggin only
	break;
	case 'terminate':
	terminator();
	status(1,1,'terminate');
	break;
	default:
	status(0,0,'initializing');
	setstart(0,'users'); #to start importing from users first
	break;
}
function terminator()
{
	global $portalconn, $TablePrefix, $adminURL, $objSession;
	$query='DROP TABLE IF EXISTS '.$TablePrefix.'import, '.$TablePrefix.'importcat';
	$portalconn->Execute($query);
	$objSession->SetVariable('PermCache_UpdateRequired', 1);
	$objSession->SetVariable('ReturnScript', 'browse.php'); // redirect to catalog when finished
	m_ParseEnv(); // sets default values to "m" prefix, because it is not passed through import anymore
	echo '';
}
function reload()
{
	//global $newurl;
	print '';
}
function setstart($mystart, $part)
{
	global $objSession;
	$objSession->SetVariable('importstart',$mystart);
	$objSession->SetVariable('importtodo',$part);
	reload();
}
function settotal($total)
{
	global $objSession;
	$objSession->SetVariable('importtotal',$total);
}
//users import from inlink to inportal
function usersimport()
{
	global $objUsers, $objSession, $linkconn, $portalconn, $olddbname,
	$user_admin,$objGroups, $user_regular, $start, $TablePrefix;
	$counter = 0;
	$limit = 350;
	$oldtablename = 'inl_users';
	$newtablename = $objUsers->SourceTable;
	if ($start == 0)
	{
		$query='select count(*) as NumUsers from inl_users';
		$row =$linkconn->Execute($query);
		if ($row && !$row->EOF)
		{
			settotal($row->fields['NumUsers']);
		}
	}
	$query="select * from inl_users LIMIT $start, $limit";
	$row =$linkconn->Execute($query);
	while($row && !$row->EOF)
	{
		$counter++; #needed to know when close to time out
		if ($row->fields['user_name'] != 'root') {
			$olduserid=$row->fields['user_id'];
			//$Login, $Password, $Email, $CreatedOn, $FirstName='', $LastName='', $Status=2,
			//          $Phone='', $Street='', $City='', $State='', $Zip='', $Country=''
			if($row->fields['user_status']==1)
			{
				$Status=1;
			}
			else
			{
				if($row->fields['user_pend']==0)
				{
					$Status=2;
				}
				else
				$Status=0;
			}
			$u = $objUsers->Add_User( $row->fields['user_name'], $row->fields['user_pass'], $row->fields['email'],
			$row->fields['user_date'], $row->fields['first'], $row->fields['last'],
			$Status);
			$oldid=$row->fields['user_id'];
			$oldcustom = $row->fields['user_cust'];
			$newid = $u->Get('PortalUserId');
			$resid = $u->Get('ResourceId');
			#adding user to usergroup
			$userpermission = $row->fields['user_perm'];
			if ($userpermission==2 || $userpermission==1)
			{
				$glist = explode(',',$user_admin);
				$Primary=1;
				for($i=0;$iGetItem($glist[$i]);
					$group->AddUser($newid,$Primary,false);
					$Primary = 0;
				}
			}
			else
			{
				$glist = explode(',',$user_regular);
				$Primary=1;
				for($i=0;$iGetItem($glist[$i]);
					$group->AddUser($newid,$Primary,false);
					$Primary = 0;
				}
			}
			//$group=$objGroups->GetItem($g);
			//$group->AddUser($newid,1);
			#inserting values to the temproary table
			$totemp = 'INSERT INTO '.$TablePrefix.'import (otname,oid,ocustomid,oparentid,ntname,nid,nrid,npid) ';
			$tovalues= " VALUES ('$oldtablename',$olduserid,$oldcustom,0,'$newtablename', $newid, $resid, 0 )";
			$totemp=$totemp.$tovalues;
			$portalconn->Execute($totemp);
		}
		$row->moveNext();
	}
	if ($counter == $limit)
	{
		setstart($start+$limit, 'users');
	}
	else
	setstart(0,'cats');
}
//END OF USERS IMPORT ^^^^^^^^^^^^^^^^^^^^^
//Categories Import
function catmanager()
{
	global $portalconn, $init_cat,$start,$TablePrefix;
	if ($start == 0)
	{
		$counter = catimport(0,$init_cat);
		setstart($counter,'cats');
		$portalconn->Execute('UPDATE '.$TablePrefix.'importcat SET flag = 1 WHERE np = '.$init_cat);
	}
	else
	{
		$query='select * from '.$TablePrefix.'importcat WHERE flag=0 LIMIT 0,1';
		$row =$portalconn->Execute($query);
		if($row && !$row->EOF)
		{
			$oldid= $row->fields['op'];
			$newid = $row->fields['np'];
			$counter= catimport($oldid,$newid);
			$query2='UPDATE '.$TablePrefix.'importcat SET flag = 1 WHERE op = '.$oldid.' AND np = '.$newid;
			$portalconn->Execute($query2);
			setstart($counter+$start-1,'cats');
			//$x=5;
		}
		else
		{
			setstart(0,'links');
		}
	}
}
#pushes into the quque
function pushid($op,$np)
{
	global $linkconn, $portalconn, $TablePrefix;
	$addnew = 'INSERT INTO '.$TablePrefix.'importcat (op,np,flag) VALUES ('.$op.','.$np.',0)';
	$portalconn->Execute($addnew);
}
function checkifexist($id)
{
	global $linkconn;
	$addnew = 'select * from inl_cats where cat_sub = '.$id;
	$row =$linkconn->Execute($addnew);
	if ($row && !$row->EOF)
	{
		if ($row->fields['cat_id'] !=0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}
#import itself
function catimport($oldparentid, $parentid)
{
	global $objCatList, $linkconn, $objUsers, $linkconn, $portalconn,
	$olddbname, $user_admin,$objGroups, $user_regular, $acl,$allgroups,
	$c, $start, $TablePrefix, $init_cat;
	$counter=0;
	$objCacheCount = new clsCacheCountList();
	if ($start == 0)
	{
		$query='select count(*) as CatCount from inl_cats';
		$row =$linkconn->Execute($query);
		if ($row && !$row->EOF)
		{
			settotal($row->fields['CatCount']);
			$catcount = $row->fields['CatCount'];
			
			if( is_object($c) )
			{
				$catcount += (int)$c->Get('CachedDescendantCatsQty');
				$c->Set('CachedDescendantCatsQty',$catcount);
				$c->Update();
			}
			
		}
	}
	$query='select * from inl_cats WHERE cat_sub = '.$oldparentid;
	$oldtablename = 'inl_cats';
	$newtablename = 'Category';
	$row =$linkconn->Execute($query);
	if($row && !$row->EOF)
	{
		$RowCount = $row->NumRows();
		$ResInc = $RowCount;
		$ResourceId = GetNextResourceId($ResInc);
	}
	if($parentid>0)
	{
		$ParentCat = new clsCategory($parentid);
		$Path = $ParentCat->Get('ParentPath');
	}
	else
	{
		global $objConfig;
		$Path = prompt_language( $objConfig->Get('Root_Name') );	
	}
	while($row && !$row->EOF)
	{
		$counter++;
		
		if($row->fields['cat_pend'] == 1)
		{
			$Status = 2;
		}
		else
		{
			$Status = ($row->fields['cat_vis'] == 1) ? 1 : 0;
		}
		
		$CreatedById = GetNewID( 'users', $row->fields['cat_id'] );
		
		$fields_hash = Array(	'ParentId'					=>	$parentid,
								'Name'						=>	$row->fields['cat_name'],
								'Description'				=>	$row->fields['cat_desc'],
								'CreatedOn'					=>	$row->fields['cat_date'],
								'EditorsPick'				=>	(int)$row->fields['cat_pick'],
								'Status'					=>	$Status,
								'HotItem'					=>	2,
								'NewItem'					=>	2,
								'PopItem'					=>	2,
								'Priority'					=>	0,
								'MetaKeywords'				=>	$row->fields['meta_keywords'],
								'MetaDescription'			=>	$row->fields['meta_desc'],
								'AutomaticFilename'			=>	1,
								'Filename'					=>	'',
								'CategoryTemplate'			=>	'',
								'ItemTemplate'				=>	'',
								'CreatedById'				=>	(int)$CreatedById,
								'CachedDescendantCatsQty'	=>	(int)$row->fields['cat_cats'],
								'ResourceId'				=>	$ResourceId,
						);
		
		$cat =& $objCatList->Add_NEW($fields_hash, true);
		$ResourceId++;
		$FullPath = $Path.$cat->Get('CategoryId').'|';
		$cat->Set('ParentPath',$FullPath);
		$cat->SetViewPerms('CATEGORY.VIEW',$acl,$allgroups);
		$cat->SetViewPerms('LINK.VIEW',$acl,$allgroups);
		$cat->Update();
		$cat->UpdateCachedPath();
		$objCacheCount->CategoryId= $cat->Get('CategoryId');
		$objCacheCount->SetValue(0,0,0,0,0);
		$newid = $cat->Get('CategoryId');
		$resid = $cat->Get('ResourceId');
		$oldid = $row->fields['cat_id'];
		$oldcustom = $row->fields['cat_cust'];
		$oldpid = $row->fields['cat_sub'];
		#inserting values to the temproary table
		$totemp = 'INSERT INTO '.$TablePrefix.'import (otname,oid,ocustomid,oparentid,ntname,nid,nrid,npid) ';
		$tovalues= " VALUES ('$oldtablename',$oldid,$oldcustom,$oldpid,'$newtablename', $newid, $resid, $parentid )";
		$totemp=$totemp.$tovalues;
		$portalconn->Execute($totemp);
		#pushes into the queue
		if(checkifexist($oldid))
		{
			pushid($oldid,$newid);
		}
		$row->moveNext();
	}
	// disable lost+found category (if found one)
	$tmp_cat = $objCatList->GetItemByField('Name','Lost+Found');
	if( is_object($tmp_cat) )
	{
		$tmp_cat->Set('Status',0);
		$tmp_cat->Update();
	}
	return $counter;
}
//Links Import
function linksimport()
{
	global $objLinkList, $init_cat, $linkconn, $portalconn, $olddbname,
	$user_admin,$objGroups, $user_regular, $start, $TablePrefix;
	$limit = 200; #need to change to a higher number like 100, forty is only for debugging
	$counter = 0;
	set_time_limit(0);
	if ($start == 0)
	{
		$query = 'select count(*) as LinkCount from inl_lc';
		$row =$linkconn->Execute($query);
		if ($row && !$row->EOF)
		{
			settotal($row->fields['LinkCount']);
		}
	}
	// create index - what links are in what categories
	$LimitClause = ' LIMIT '.$start.','.$limit;
	$sql = 'SELECT link_id FROM inl_links ORDER BY link_id'.$LimitClause;
	$LinkIDs = $linkconn->GetCol($sql);
	if( count($LinkIDs) > 0 )
	{
		$LinkCatIndex = Array();
		$PendingLinks = Array();
		$sql = "SELECT * FROM inl_lc WHERE link_id IN (%s)";
		$rs = $linkconn->Execute( sprintf($sql, implode(',', $LinkIDs) ) );
		while(!$rs->EOF)
		{
			$rec =& $rs->fields;
			if( !isset($PendingLinks[ $rec['link_id'] ]) && $rec['link_pend'] == 1 )
				$PendingLinks[ $rec['link_id'] ] = 1;
			
			$LinkCatIndex[ $rec['link_id'] ][] = $rec['cat_id'];
			$rs->MoveNext();
		}
	}
	// get links
	$query = 'SELECT * FROM inl_links ORDER BY link_id'.$LimitClause; // get links info
	$row = $linkconn->Execute($query); // row is recordset here, not easy to figure out by variable name :(
	if($row && !$row->EOF)
	{
		$RowCount = $row->NumRows();
		$ResInc = $RowCount;
		$ResourceId = GetNextResourceId($ResInc);
	}
	$get_cat_sql = "SELECT nid FROM %simport WHERE ntname = 'Category' AND oid = %s";
	
	while($row && !$row->EOF)
	{
		$counter++;
		$oldid = $row->fields['link_id'];
		$flag = 1;
		$Pending = isset($PendingLinks[$oldid]);
		// create new link
		#gets the new user id of the user who created a link
		if( !$row->fields['link_user'] )
			$newuserid = -1;
		else
			$newuserid = GetNewID('users', $row->fields['link_user'] );
		#adds link to the IN-PORTAL
		$link = new clsLink();
		$Status = ($Pending == 0) ? 1 : 2;
		$link->Set(	array(	'Name', 'Description', 'Url', 'CreatedOn', 'Status', 'EditorsPick',
		'NewItem','PopItem','HotItem', 'CreatedById', 'CachedRating',
		'CachedVotesQty','Hits', 'Priority','Expire'),
		array(	$row->fields['link_name'], $row->fields['link_desc'], $row->fields['link_url'], $row->fields['link_date'], $Status,
		$row->fields['link_pick'], 2, 2, 2, $newuserid, (int)$row->fields['link_rating'],
		(int)$row->fields['link_votes'],(int)$row->fields['link_hits'], 0,$row->fields['link_expires']));
		$link->Set('ResourceId',$ResourceId);
		$ResourceId++;
		$link->Create();
		// add link to desired categories (add 1st category found as primary)
		$cats = $LinkCatIndex[$oldid];
		$PrimaryCat = 1;
		foreach($cats as $OldCatID)
		{
			$categoryid = $portalconn->GetOne( sprintf($get_cat_sql, $TablePrefix, $OldCatID) );
			$link->AddToCategory($categoryid, '', $PrimaryCat);
			if($PrimaryCat)
			{
				$PrimaryCat = 0;
				$oldcatid = $OldCatID;
			}
		}
		$newid = $link->Get('LinkId');
		$resid = $link->Get('ResourceId');
		$oldcustom = $row->fields['link_cust'];
		$linkimage = $row->fields['link_image'];
		if($linkimage) addimage($resid,$linkimage);
		#calls to import reviews
		reviewimport($link,$oldid,$resid);
													   
		$totemp = 'INSERT INTO '.$TablePrefix.'import (otname,oid,ocustomid,oparentid,ntname,nid,nrid,npid) ';
		$tovalues= " VALUES ('inl_links',$oldid,$oldcustom,$oldcatid,'link', $newid, $resid, 0 )";
		$totemp = $totemp.$tovalues;
		$portalconn->Execute($totemp);
		#prelast while
		$row->moveNext();
	}
	if ($counter == $limit)
	{
		setstart($start + $limit, 'links');
	}
	else
	{
		$sql = 'UPDATE '.GetTablePrefix().'CategoryItems SET CategoryId = '.$init_cat.' WHERE CategoryId = 0 AND PrimaryCat = 1';
		$portalconn->Execute($sql);
		setstart(0,'custom');
	}
}
#importing image from the in-link
function addimage($resourceid, $imageurl)
{
	global $objImageList, $image_name;
	#echo "
IMAGE RESOURCEID:  $resourceid IMAGE URL:  $imageurl 
";
	if(!is_object($objImageList))
	$objImageList = new clsImageList();
	$LocalImage = 0;
	$LocalThumb = 0;
	if(!strlen($image_name))
	$image_name='inlink_image';
	$img = $objImageList->Add($image_name,'',$resourceid, 0, 0,'', $imageurl, 1,0, 1, 0,1);
}
#Reviews Import for links
function reviewimport($myclass,$oldid,$rid)
{
	global $objCustomFieldList, $linkconn, $portalconn;
	#ITEM AddReview($createdBy,$reviewText,0)
	$query='select * from inl_reviews where rev_link = '.$oldid;
	$row =$linkconn->Execute($query);
	while($row && !$row->EOF)
	{
		$oldreviewuser= $row->fields['rev_user'];
		if($oldreviewuser !=0) #meaning was not created by guest
		{
			$newrid = GetNewID('users', $oldreviewuser);
			if ($newrid)
			{
				$temp=$myclass->AddReview($newrid, $row->fields['rev_text'], $row->fields['rev_pend'], '127.0.0.1', 1, 'In-Link', $row->fields['rev_date']);
			}
			else
			{
				$temp=$myclass->AddReview(0, $row->fields['rev_text'], $row->fields['rev_pend'], '127.0.0.1', 1, 'In-Link', $row->fields['rev_date']);
			}
		}
		else #meaning was created by guest
		{
			$temp=$myclass->AddReview(0, $row->fields['rev_text'], $row->fields['rev_pend'], '127.0.0.1', 1, 'In-Link', $row->fields['rev_date']);
		}
		$row->moveNext();
	}
}
#HELPER FUNCTION THAT GETS THE NEW ID of the USER
/**
* @return int
* @param string $IDType
* @param int $OldID
* @desc Returns new id for specified record type ($IDType) with id ($OldID)
*/
function GetNewID($IDType, $OldID)
{
	global $TablePrefix;
	$get_id_sql = "SELECT nid FROM %simport WHERE otname = 'inl_%s' AND oid = %s";
	$db =&GetADODBConnection();
	$id = $db->GetOne( sprintf($get_id_sql, $TablePrefix, $IDType, $OldID) );
	return $id;
}
//^^^^^^^^^^^^^^^^^^^^^^ABOVE IS LINKS IMPORT
#########################################Custom Fields Import
#create a new CustomField first and then
#by selecting all and receiving from one record of inl_config the values of cc1,cc2,cc3,cc4,cc5,cc6,uc1,uc2,uc3,uc4,uc5,uc6,lc1,lc2,lc3,lc4,lc5,lc6
#go through all import table and if ocustomid occures get the row from inl_custom and
#create CustomMetaData field
#---------------------
#Regarding CustomField:
#FieldName= cc1,cc2 .... from inl_config
#FieldLabel= value of cc1, cc2 ....
#Type=4 for links 6 for users 0 category
#------------
#Regarding CustomMetaData
#ResourceId <= link id
#CustomFieldId <= id from the top
#Value = Value from the table custom
//VVVVV BELOW ARE CUSTOM FIELD IMPORT REQUIRES TO HAVE A TEMPROARY TABLE IMPORT
function customimport()
{
	global $linkconn, $portalconn, $start, $TablePrefix;
	$limit = 40; #just for debugging purposes, in real life set it to higher number
	
	if ($start == 0) {
		$r = buildfields();
		$query = 'SELECT count(*) as cc from '.$TablePrefix.'import WHERE NOT ocustomid=0';
		$row = $portalconn->Execute($query);
		if ($row && !$row->EOF) settotal($row->fields['cc']);
	}
	else {
		$r = getfields();
	}
	$query = 'SELECT * from '.$TablePrefix.'import WHERE ocustomid != 0 limit '.$start.','.$limit;
	$row = $portalconn->Execute($query);
	$counter = 0;
	
	while ($row && !$row->EOF) {
		$counter++;
		loadcustom($row->fields['ocustomid'],$row->fields['nrid'],$row->fields['otname'],$r);
		$row->moveNext();
	}
	
	if ($counter == $limit) {
		setstart($start + $limit, 'custom');
	}
	else {
		// goto next step
		setstart(0, 'relcat');
	}
}
function loadcustom($customid,$rid,$tablename,$r)
{
	global $linkconn, $objCustomDataList, $objSession;
	
	$objCustomDataList->Clear();
	switch ($tablename) {
		case 'inl_cats':
			$SessionVar = 'custom_category';
			$prefix = 'c';
			break;
			
		case 'inl_users':
			$SessionVar = 'custom_user';
			$prefix = 'u';
			break;
			
		case 'inl_links':
			$SessionVar = 'custom_links';
			$prefix = 'l';
			break;
	}
	$fields = explode(',', $objSession->GetVariable($SessionVar) );
	
	$query = 'select * from inl_custom Where cust_id = '.$customid;
	$row = $linkconn->Execute($query);
	if($row && $row->RecordCount() )
	{
		for($x = 0; $x < count($fields); $x++)
		{
			$cust = $row->fields[ 'cust'.($x + 1) ];
			$fieldid = $r[ $fields[$x] ];
			$objCustomDataList->SetFieldValue($fieldid, $rid, $cust);
		}
		$objCustomDataList->SaveData($prefix, $rid);
	}
}
function buildfields() #building and populating an array
{
	global $objCustomFieldList, $objSession, $linkconn;
	$application =& kApplication::Instance();
	$ml_helper =& $application->recallObject('kMultiLanguageHelper');
	
	// User Custom Fields:
	$query = "SELECT * FROM inl_config WHERE name LIKE 'uc%'";
	$row = $linkconn->Execute($query);
	$names = Array();
	while($row && !$row->EOF)
	{
		$data = $row->fields;
		$fieldlabel = $data['name'];
		if( strlen($data['value']) ) $fieldlabel = $data['value'];
		//$f = $objCustomFieldList->AddField(6, $data['name'], $fieldlabel);
		$f = $objCustomFieldList->AddField(6, $data['name'], $fieldlabel, 1, 'la_inlink', 'lu_fieldcustom__'.$data['name'], 'text', '');
		
		$r[ $data['name'] ] = $f->Get('CustomFieldId'); // Save ID of created CustomField
		$objSession->SetVariable('custom_'.$data['name'], $f->Get('CustomFieldId') ); // Save that ID to session
		$names[] = $data['name'];
		$row->MoveNext();
	}
	$objSession->SetVariable('custom_user',implode(',',$names) ); // save list of user custom fields
	$ml_helper->createFields('u-cdata', true);
	unset($names);
	// Category Custom Fields:
	$names = Array();
	$query = "SELECT * FROM inl_config WHERE name LIKE 'cc%'";
	$row = $linkconn->Execute($query);
	while($row && !$row->EOF)
	{
		$data = $row->fields;
		$fieldlabel = $data['name'];
		if( strlen($data['value']) ) $fieldlabel = $data['value'];
		//								   DT_USER, $pending_uf, '', 1, 'la_bb', 'lu_fieldcustom__'.$pending_uf, 'text', '');
		$f = $objCustomFieldList->AddField(1, $data['name'], $fieldlabel,1,'la_inlink', 'lu_fieldcustom__'.$data['name'], 'text', '');
		//$f = $objCustomFieldList->AddField(1, $data['name'], $fieldlabel);
		
		$r[ $data['name'] ] = $f->Get('CustomFieldId');
		$objSession->SetVariable('custom_'.$data['name'], $f->Get('CustomFieldId') );
		$names[] = $data['name'];
		$row->MoveNext();
	}
	$objSession->SetVariable('custom_category', implode(',',$names) );
	$ml_helper->createFields('c-cdata', true);
	unset($names);
	
	// Links Custom Fields:
	$names = Array();
	$query = "SELECT * FROM inl_config WHERE name LIKE 'lc%'";
	$row = $linkconn->Execute($query);
	while($row && !$row->EOF)
	{
		$data = $row->fields;
		$fieldlabel = $data['name'];
		if( strlen($data['value']) ) $fieldlabel = $data['value'];
		//$f = $objCustomFieldList->AddField(4, $data['name'], $fieldlabel);
		$f = $objCustomFieldList->AddField(4, $data['name'], $fieldlabel,1,'la_inlink', 'lu_fieldcustom__'.$data['name'], 'text', '');
		$r[ $data['name'] ] = $f->Get('CustomFieldId');
		$objSession->SetVariable('custom_'.$data['name'], $f->Get('CustomFieldId') );
		$names[] = $data['name'];
		$row->MoveNext();
	}
	$objSession->SetVariable('custom_links', implode(',',$names) );
	$ml_helper->createFields('l-cdata', true);
	return $r;
}
function getfields() #building and populating an array
{
	global $objSession;
	
	$r = Array();
	$tmp_fields = explode(',', $objSession->GetVariable('custom_user') ); // Array(uc1,uc2,uc3,...)
	foreach($tmp_fields as $tmp_name) $r[$tmp_name] = $objSession->GetVariable('custom_'.$tmp_name);
	
	$tmp_fields = explode(',', $objSession->GetVariable('custom_category') );
	foreach($tmp_fields as $tmp_name) $r[$tmp_name] = $objSession->GetVariable('custom_'.$tmp_name);
	
	$tmp_fields = explode(',', $objSession->GetVariable('custom_links') );
	foreach($tmp_fields as $tmp_name) $r[$tmp_name] = $objSession->GetVariable('custom_'.$tmp_name);
	return $r;
}
################################################Relationships Import
function relcatimport()
{
	global $linkconn,$objSession, $start;
	$limit = 100;
	$counter =0;
	if ($start == 0)
	{
		$query='SELECT count(*) from inl_rel_cats';
		$row =$linkconn->Execute($query);
		if ($row && !$row->EOF)
		{
			settotal($row->fields[0]);
		}
	}
	$objRelList = new clsRelationshipList();
	$query='select * from inl_rel_cats LIMIT '.$start.', '.$limit;
	$row =$linkconn->Execute($query);
	while($row && !$row->EOF)
	{
		$counter++;
		$sourceid = newcatrid($row->fields['cat_id']);
		$targetid = newcatrid($row->fields['rel_id']);
		if ($sourceid !='' && $targetid !='')
		{
			$r = $objRelList->Add($sourceid, 1,$targetid, 1);
			$r->Create();
		}
		$row->moveNext();
	}
	if ($counter == $limit)
	{
		setstart($start + $limit, 'relcat');
	}
	else
	{
		setstart(0,'terminate');
	}
}
function newcatrid($oid)
{
	global $portalconn, $TablePrefix;
	$query2='select * from '.$TablePrefix.'import where otname=\'inl_cats\' and oid = '.$oid;
	$row =$portalconn->Execute($query2);
	if ($row->fields['nrid'])
	{
		return $row->fields['nrid'];
	}
	else
	{
		return '';
	}
}
// END OF RELATIONSHIP IMPORT
?>