<?php
#import script  
#taking care of actual importing from in-link db to in-portal db


if(!strlen($pathtoroot))
{
  $path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
  if(strlen($path))
  {
    /* determine the OS type for path parsing */
    $pos = strpos($path,":");
    if ($pos === false)
    {
      $gOS_TYPE="unix";
      $pathchar = "/";
    }
    else
    {
      $gOS_TYPE="win";
      $pathchar="\\";
    }
    $p = $path.$pathchar;
    /*Start looking for the root flag file */
    while(!strlen($pathtoroot) && strlen($p))
    {
      $sub = substr($p,strlen($pathchar)*-1);
      if($sub==$pathchar)
      {
        $filename = $p."root.flg";
      }
      else
        $filename = $p.$pathchar."root.flg";
      if(file_exists($filename))
      {
        $pathtoroot = $p;
      }
      else
      {
        $parent = realpath($p.$pathchar."..".$pathchar);
	if($parent!=$p)
	{
	  $p = $parent;
	}
	else
	  $p = "";
      }
    }
    if(!strlen($pathtoroot))
      $pathtoroot = ".".$pathchar;
  }
  else
  {
    $pathtoroot = ".".$pathchar;
  }
}

$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
  $pathtoroot = $pathtoroot.$pathchar;
}

require_once($pathtoroot."kernel/startup.php");

$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
    $admin = "admin";  

if ($_POST["Action"]=="Import") 
{
	$objSession->SetVariable("import_user_admin",$_POST["user_admin"]);
	$objSession->SetVariable("import_user_regular",$_POST["user_regular"]);
	$objSession->SetVariable("import_init_cat",$_POST["init_cat"]);
	$objSession->SetVariable("image_name",$_POST["image_name"]);

	$objSession->SetVariable("importtodo","initialize");
	$objSession->SetVariable("importstart",0);
	$objSession->SetVariable("importtotal",0);
    
    if((int)$_POST["init_cat"]>0)
    {          
      $c = $objCatList->GetItemByField("ResourceId",(int)$_POST["init_cat"]);
      $c->UpdateACL();
      $c->UpdateCachedPath();
    }        
    

}
    $allgroups = $objGroups->GetAllGroupList();

	$inlink_sql_type=$objSession->GetVariable("import_inlink_sql_type");
	$inlink_server=$objSession->GetVariable("import_inlink_server");
	$inlink_db=$objSession->GetVariable("import_inlink_db");
	$inlink_user=$objSession->GetVariable("import_inlink_user");
	$inlink_pass=$objSession->GetVariable("import_inlink_pass");

	$user_admin=$objSession->GetVariable("import_user_admin");
	$user_regular=$objSession->GetVariable("import_user_regular");
    if(!is_object($c))
        $c = $objCatList->GetItemByField("ResourceId",$objSession->GetVariable("import_init_cat"));
	$init_cat= $c->Get("CategoryId");
	$image_name=$objSession->GetVariable("image_name");
	$start = $objSession->GetVariable("importstart");
    $acl = explode(",",$c->GetACL("CATEGORY.VIEW"));

//IN-LINK connection
$linkconn=&ADONewConnection($inlink_sql_type);
$linkconn->PConnect($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();
}
if($pconnect)
{
	$linkconn->Close();
	$linkconn = ADONewConnection($inlink_sql_type);
	$linkconn->PConnect($inlink_server, $inlink_user, $inlink_pass, $inlink_db);
}

//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";

//In-Portal
$portalconn = GetAdodbConnection();

$TablePrefix = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix();  

$olddbname=$inlink_db; 
//$newdbname="inportal"; 
$newdbname=$g_DBName; 
##############creating a temproary table have to be here
if ($_POST["Action"]=="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.$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;
		$query="DROP TABLE IF EXISTS ".$TablePrefix."import, ".$TablePrefix."importcat";
		$portalconn->Execute($query);
	}
	
    function reload()
	{
		global $newurl;
		print '<script language="javascript">' ;
		print "  setTimeout('location.href=location.href',40);";
		print ' </script>';
	}
	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;$i<count($glist);$i++)
					{
				        $group=$objGroups->GetItem($glist[$i]);
						$group->AddUser($newid,$Primary);        
						$Primary = 0;
					}
				} 
	            else
	            {            
					$glist = explode(",",$user_regular);
					$Primary=1;
					for($i=0;$i<count($glist);$i++)
					{
				        $group=$objGroups->GetItem($glist[$i]);
						$group->AddUser($newid,$Primary);        
						$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;
		$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"];
                $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");
        }
		while($row && !$row->EOF)
		{
			$counter++;
 
            $cat = new clsCategory();
            if($row->fields["cat_pend"]==0)
            {
                $Status=1;
            }
            else
            {
                if($row->fields["cat_vis"]==0)
                {                
                    $Status=2;
                }
                else
                    $Status=0;
            }
            $CreatedById = getnewid($row->fields["cat_id"]);
            $cat->Set(array("ParentId", "Name", "Description", "CreatedOn",  "EditorsPick", "Status", "HotItem", 
                          "NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById",
                          "CachedDescendantCatsQty"), 
                      array($parentid, $row->fields["cat_name"], $row->fields["cat_desc"], 
                            $row->fields["cat_date"], (int)$row->fields["cat_pick"], $Status, 2, 2, 2, 0, 
                            $row->fields["meta_keywords"],$row->fields["meta_desc"],
                            (int)$CreatedById,(int)$row->fields["cat_cats"]));
            $cat->Set("ResourceId",$ResourceId);
            $ResourceId++;
            $cat->Create();

            $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 = 750; #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"]);
				
			}
		}
		
		$query="select * from inl_lc INNER JOIN inl_links ON (inl_lc.link_id=inl_links.link_id) limit $start,$limit";
		$oldtablename="inl_links";
		$newtablename="link";
		$row =$linkconn->Execute($query);
		if($row && !$row->EOF)
		{
		   $RowCount = $row->NumRows();
		   $ResInc = $RowCount;	
		   $ResourceId = GetNextResourceId($ResInc);
		}
		while($row && !$row->EOF)
		{
			$counter++;
			$oldid=$row->fields["link_id"];	
			$flag=1;
		
            $oldcatid = $row->fields["cat_id"];
            $pending = $row->fields["link_pend"];
			#getting a new category id
           
            $rs = $portalconn->Execute("SELECT nid FROM ".$TablePrefix."import WHERE ntname='Category' and oid=$oldcatid");
			if ($rs && ! $rs->EOF)
			{
			 	$categoryid=$rs->fields["nid"];			
			}
			else 
			{
				$categoryid = $init_cat;
			}	 
            
            $rs = $portalconn->Execute("SELECT * FROM ".$TablePrefix."import WHERE otname='inl_link' AND oid='$oldid'");
            if($rs && ! $rs->EOF)
            {
                $NewLinkId = $rs->fields["nid"];
            }
            else
                $NewLinkId=0;
			if ($NewLinkId==0) 
			{
				#gets the new user id of the user who created a link
				$newuserid=getnewid($row->fields["link_user"]);
				#adds link to the IN-PORTAL
                $link = new clsLink();
                if($Pending==0)
                {
                    $Status=1;
                }
                else
                    $Status=2;
                $link->Set(array("Name", "Description", "Url", "CreatedOn", "Status", "EditorsPick", 
                                 "NewItem","PopItem","HotItem", "CreatedById", "CachedRating",
                                 "CachedVotesQty","Hits", "Priority"), 
                           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));
				$link->Set("ResourceId",$ResourceId);
				$ResourceId++;
				$link->Create();
                $link->AddToCategory($categoryid,"",1);

                $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);																			
				$parentid = 0;						
				$totemp = "INSERT INTO ".$TablePrefix."import (odb,otname,oid,ocustomid,oparentid,ndb,ntname,nid,nrid,npid) ";
				$tovalues= " VALUES ('$olddbname','$oldtablename',$oldid,$oldcustom,$oldcatid,'inportal','$newtablename', $newid, $resid, $parentid )";	
				$totemp = $totemp.$tovalues;
				//$portalconn->Execute($totemp);	
					
			}
			else #if link is related to more than one category
			{
                $link = new clsLink($NewLinkId);					
				$link->AddtoCategory($categoryid,"",0);
			}											
			#prelast while
			$row->moveNext();
		}
	
		if ($counter == $limit)
		{
			setstart($start+$limit, "links");
		}
		else
		{
			setstart(0,"custom");
		}
		
	}
	
	#importing image from the in-link
	function addimage($resourceid, $imageurl)
	{
		global $objImageList, $image_name;
		#echo "<br />IMAGE RESOURCEID:  $resourceid IMAGE URL:  $imageurl <br />";
	    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($oldreviewuser);
				if ($newrid)
				{
					$temp=$myclass->AddReview($newrid,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");

				}
				else
				{
					$temp=$myclass->AddReview(0,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");

				}
			}
			else #meaning was created by guest
			{
				$temp=$myclass->AddReview(0,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");
	
			}
			$row->moveNext();
		}	
	}
	#HELPER FUNCTION THAT GETS THE NEW ID of the USER 
	function getnewid($oldid)
	{
		global $portalconn, $TablePrefix;
		
		$query2="select * from ".$TablePrefix."import where otname='inl_users' and oid=".$oldid;
		$row2=$portalconn->Execute($query2);
		if ($row2->fields["nid"])
		{
			return $row2->fields["nid"];
		}
		else
		{
			return 0;
		}
	}
	
	
	
	//^^^^^^^^^^^^^^^^^^^^^^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
		$counter=0;
		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);
		while($row && !$row->EOF)
		{
			$counter++;
			if ($row->fields["ocustomid"]!=0)
			{
				loadcustom($row->fields["ocustomid"],$row->fields["nrid"],$row->fields["otname"],$r);
			}	
			$row->moveNext();
		}
		if ($counter == $limit)
		{
			setstart($start+$limit, "custom");
		}
		else
		{
			setstart(0,"relcat");
		}
	}
	function loadcustom($customid,$rid,$tablename,$r)
	{
		global $linkconn, $objCustomDataList, $objSession;
		
		$objCustomDataList->Clear();
		if ($tablename =="inl_cats")
		{
			//$myfieldname="cc";
			$fields = explode(",",$objSession->GetVariable("custom_category"));
		}
		else if($tablename =="inl_users")
		{
			//$myfieldname="uc";
			$fields = explode(",",$objSession->GetVariable("custom_user"));
		}
		else if($tablename =="inl_links")
		{
			//$myfieldname="lc";
			$fields = explode(",",$objSession->GetVariable("custom_links"));
		}
		
		$oldtablename="inl_links";
		$newtablename="link";
		$query="select * from inl_custom Where cust_id=$customid";
		$row =$linkconn->Execute($query);
		if ($row)
		{
			for ($x=0; $x<count($fields);$x++)
			{
				$cust=$row->fields["cust".$x];
				if ($cust!="")
				{
					$fieldid =$r[$fields[$x]];
					$objCustomDataList->SetFieldValue($fieldid,$rid,$cust);
				}
	 		}
	 		$objCustomDataList->SaveData();	
 		}	
	}

	function buildfields() #building and populating an array
	{
		global $objCustomFieldList, $objSession,$linkconn;
	
		$lc="lc";
		$uc="uc";
		$cc="cc";
		$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);	
			$r["'".$data["name"]."'"]=$f->Get("CustomFieldId");
			$objSession->SetVariable("custom_".$data["name"],$f->Get("CustomFieldId"));
			$names[] = $data["name"];
			$row->MoveNext();
	 	}
		$objSession->SetVariable("custom_user",implode(",",$names));
		unset($names);

		$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"];
			}
			$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));
		unset($names);

		$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);	
			$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)); 	
	 	
	 	return $r;		
	}
	
	function getfields() #building and populating an array
	{
		global $objSession;
	
		$lc="lc";
		$uc="uc";
		$cc="cc";
		$userfields = explode(",",$objSession->GetVariable("custom_user"));
		for ($x=0;$x<=count($userfields);$x++)
		{
			$r[$userfields[$x]]=$objSession->GetVariable("custom_".$userfields[$x]);
	 	}
		$catfields = explode(",",$objSession->GetVariable("custom_category"));
		for ($x=0;$x<=count($catfields);$x++)
		{
			$r[$catfields[$x]]=$objSession->GetVariable("custom_".$catfields[$x]);
	 	}
		$linkfields = explode(",",$objSession->GetVariable("custom_links"));
		for ($x=0;$x<=count($linkfields);$x++)
		{
			$r[$linkfields[$x]]=$objSession->GetVariable("custom_".$linkfields[$x]);
	 	}

	 	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 
?>