Index: trunk/kernel/action.php
===================================================================
--- trunk/kernel/action.php	(revision 347)
+++ trunk/kernel/action.php	(revision 348)
@@ -1,2269 +1,2269 @@
 <?php
 
 $ro_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
 
 if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & KERNEL_ACTIONS) == KERNEL_ACTIONS )
 {
 	if($Action) echo '<span class="debug_text">Kernel Action [<b>'.$Action."</b>]</span><br>\n";
 }
 
 if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & SHOW_REQUEST) == SHOW_REQUEST )
 {
 	// don't show debug output in tree & header of admin & while logging in
 	$script = basename($_SERVER['PHP_SELF']);
 	$skip_debug = Array('index.php','tree.php','head.php','credits.php');
 	if( !in_array($script, $skip_debug) )
 	{
 		echo "ScriptName: <b>$script</b> (<b>".dirname($_SERVER['PHP_SELF'])."</b>)<br><br>";
 		$div_height = (count($_REQUEST)+1)*26;
 		if($div_height > 300) $div_height = 300;
 		echo '<div class="debug_layer" style="height: '.$div_height.'px;">';
 		echo '<table border="0" cellspacing="0" cellpadding="4" class="debug_table">';
 		echo '<thead style="font-weight: bold;"><td>Src</td><td>Name</td><td>Value</td></thead>';
 		
 		foreach($_REQUEST as $key => $value)
 		{
 			if( !is_array($value) && trim($value) == '' ) $value = '&nbsp;';
 			$src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') );	
 			echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.print_r($value, true).'</td></tr>';
 		}
 		echo '</table></div>';
 		echo '<a href="javascript:self.location.reload();">Reload Frame</a>';
 	}
 	unset($script, $skip_debug);
 }
 
 	switch($Action)
 	{
 		case "m_save_import_config":
          	// Set New Import Category
          	if( isset($_POST['categorylist']) )
          	{
    		 		$cat_id = $_POST['categorylist'];
 			  	$objSession->SetVariable('categoryid', $cat_id); 		  	
    			  	$cat = $objCatList->GetByResource($cat_id);
     			if(is_object($cat))
 			    {    
       				$navbar = $cat->Get('CachedNavbar');
       				$objSession->SetVariable('catnavbar', $navbar);
       				$objSession->SetVariable('import_category_id', $cat->UniqueId() );
 			    }
 			    $objSession->SetVariable('categorylist', $_POST['categorylist']);
 			}
 			
 			// Set Import Admin Group
 			if( isset($_POST['grouplist1']) )
 			{              
 				$group_id = $_POST['grouplist1'];
-				$group = $objGroups->GetItem($group_id);
+				$group = $objGroups->GetItemByField('ResourceId',$group_id);
                 $objSession->SetVariable('user_admin_names', $group->Get('Name')); 
                 $objSession->SetVariable('user_admin_values', $group->Get('GroupId'));
                 $objSession->SetVariable('grouplist1', $_POST['grouplist1']);
 			}   
               
 			// Set Import User Group
 			if( isset($_POST['grouplist2']) )
 			{              
             	$group_id = $_POST['grouplist2'];
-				$group = $objGroups->GetItem($group_id);
+				$group = $objGroups->GetItemByField('ResourceId', $group_id);
                 $objSession->SetVariable('user_regular_names', $group->Get('Name')); 
                 $objSession->SetVariable('user_regular_values', $group->Get('GroupId'));
                 $objSession->SetVariable('grouplist2', $_POST['grouplist2']);
 			}
         	break;
 		
 		case "m_add_user":		  
 	  	  	$dupe_user = '';
 			//$user_pending = (int)$_POST["user_pending"];
 			//$user_enabled = (int)$_POST["user_enabled"];
 			$CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat()); 
 			$dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
 			
 		  	$objEditItems = new clsUserManager();
 		  	$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 
 		  	if(strlen($_POST["user_login"]))
           		$id = $objUsers->GetUserId($_POST["user_login"]);
 		  	else
 		    	$dob = 0;
 		    
           	if($id)
           	{
               	$lvErrorString = language('la_error_duplicate_username');
               	$dupe_user = $_POST["user_login"];
               	$_POST["user_login"] = '';
             }
           	         
           		$password = md5($_POST["password"]);
 		    	$u = $objEditItems->Add_User($_POST["user_login"], $password,
                 	                    $_POST["user_email"], $CreatedOn, $_POST["user_firstname"], 
                     	                $_POST["user_lastname"], $_POST["status"], 
                         	            $_POST["user_phone"], 
                             	        $_POST["user_street"], $_POST["user_city"], 
                                 	    $_POST["user_state"], $_POST["user_zip"], $_POST["user_country"], $dob);
      
             	$objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
             	$objCustomEdit->SetTable('edit');
             	$objCustomEdit->LoadResource($u->Get("ResourceId"));
             	$CustomFields = new clsCustomFieldList(6);
             	$DataChanged = FALSE;
             	foreach($_POST as $key=>$value)
             	{
             		if(substr($key,0,1)=="_")
             		{
             			$field = substr($key,1);
             			$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             			if(is_object($cvalue))
             			{
             				$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
             				$DataChanged = TRUE;
             			}
             		}
             	}          	
             	if($DataChanged) $objCustomEdit->SaveData();
             	$objCustomEdit->SetTable('live');
           	
           	
 			break;    
 		case "m_edit_user":
 		    $CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat()); 
             $dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
 			$objEditItems = new clsUserManager();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 			//$user_pending = (int)$_POST["user_pending"];
             //$user_enabled = (int)$_POST["user_enabled"];
             $UserId = (int)$_POST["user_id"];
             //echo $UserId."<br>\n";
             if(!strlen($_POST["user_login"]))
               $dob = 0;
             if(strlen($_POST["password"]))
             {
               $password = md5($_POST["password"]);	
             }  
             else
               $password = "";
 			$u = $objEditItems->Edit_User($UserId, $_POST["user_login"], $password,
                                      $_POST["user_email"], $CreatedOn, $_POST["user_firstname"], 
                                      $_POST["user_lastname"], $_POST["status"], 
                                      $_POST["user_phone"], 
                                      $_POST["user_street"], $_POST["user_city"], 
                                      $_POST["user_state"], $_POST["user_zip"], $_POST["user_country"],
                                      $dob);
            
             $objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
             $objCustomEdit->SetTable('edit');
            	$DataChanged = false;
            	
             $objCustomEdit->LoadResource($u->Get("ResourceId"));
             $CustomFields = new clsCustomFieldList(6);
             
             foreach($_POST as $key=>$value)
             {
             	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			//echo "Saving CF: (".$cvalue->Get("CustomFieldId")." ; ".$u->Get("ResourceId")." ; $value)<br>";
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
             }
         	
             if($DataChanged)
             	$objCustomEdit->SaveData();
             $objCustomEdit->SetTable('live');
 		break;
 		case "m_user_primarygroup":		 
 		  	//print_pre($_REQUEST);
 		  	if($ro_perm) break;
 		  	$users = explode(',', $_POST["userlist"]);
 		  	$GroupResourceId = $_POST['grouplist'];
 		  	$g = $objGroups->GetItemByField("ResourceId", $GroupResourceId);
 		  	$GroupId = $g->UniqueId();
 		  	
 		  	if( is_array($users) )
 		  		foreach($users as $user_id)
 		  		{
 		  			$u = $objUsers->GetItemByField("ResourceId", $user_id);
 		  			$g->AddUser($u->Get("PortalUserId"), 1);
 		  		}
      		break;
      		
 		case "m_edit_group":		   
 			$objEditItems = new clsGroupList();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 			$objEditItems->Edit_Group($_POST["group_id"], $_POST["group_name"],$_POST["group_comments"]);
 		break;
         case "m_add_group":
 			$objEditItems = new clsGroupList();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 			$objEditItems->Add_Group($_POST["group_name"], $_POST["group_comments"],0);
 		break;
      case "m_group_sysperm":
 		  if($_POST["GroupEditStatus"]==0)
           {          
             $objSession->ResetSysPermCache();
             $GroupId = $_POST["GroupId"];
 			if($GroupId)
 			{
 			  $objEditItems = new clsGroupList();
 			  $objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 			  $g = $objEditItems->GetItemByField("ResourceId",$GroupId);              
               if(is_object($g))
 			  {
                 
 			    $PermList = explode(",",$_POST["PermList"]);                
 				for($i=0;$i<count($PermList);$i++)
 				{
 				  if(@in_array($PermList[$i],$_POST["inherit"]))
 				  {
 				    $value = -1;
 				  }
 				  else
                   {
 				    $value = 0;
                     if(@in_array($PermList[$i],$_POST["permvalue"]))
 				      $value = 1;
 				  }                  
 				  $g->SetSystemPermission($PermList[$i],$value);
 				}
 			  }
 			}
           }
 		break;
         case "m_user_sysperm":
           if($ro_perm) break;
           if($_POST["UserEditStatus"]==0)
           {
 		    $UserId = $_POST["ItemId"];
 			if($UserId)
 			{
 			  $objEditItems = new clsUserManager();
 			  $objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 			  $u = $objEditItems->GetItemByField("ResourceId",$UserId);
 			  unset($g);
               if(is_object($u))
 			  {
                 $objSession->ResetSysPermCache();
 			    $g = $u->GetPersonalGroup(FALSE);
 			    $PermList = explode(",",$_POST["PermList"]);
 				for($i=0;$i<count($PermList);$i++)
 				{
 				  if(!@in_array($PermList[$i],$_POST["inherit"]))
 				  {
                     if(!is_object($g))
 					  $g = $u->GetPersonalGroup(TRUE);
 
 					$value = 0;
 					if(is_array($_POST["permvalue"]))
 					{
 				      if(in_array($PermList[$i],$_POST["permvalue"]))
 				        $value =1;
 					  $g->SetSystemPermission($PermList[$i],$value);
 					}
 					else
 					  $g->SetSystemPermission($PermList[$i],-1);
 				  }
 				  else
                   {
 				    if(is_object($g))
 					  $g->SetSystemPermission($PermList[$i],-1);
 				  }
 				}
 			  }
 			}
           }
 	    break;
 		case "m_approve_user":
 			if($ro_perm) break;
 			foreach($_POST["itemlist"] as $userid)
 			{
 				$user = $objUsers->GetItemByField("ResourceId",$userid);
 				$user->Approve();
 			}
             $objUsers->Clear();
 		break;
 
         case "m_deny_user":
             if($ro_perm) break;
             foreach($_POST["itemlist"] as $userid)
             {
                 $user = $objUsers->GetItemByField("ResourceId",$userid);
                 $user->Deny();
             }
             $objUsers->Clear();
         break;
 		case "m_delete_user":
 				if($ro_perm) break;
 				foreach($_POST["itemlist"] as $userid)
 					$objUsers->Delete_User($userid);
 		break;
 		case "m_delete_group":
             if($ro_perm) break;
             foreach($_POST["itemlist"] as $groupid)
             {            
 			  	$objGroups->Delete_Group($groupid);
 			}
 		break;
 		case "m_user_assign":
 			$useridlist = implode("-", $userlist);
 			$objSession->SetUserStatus($useridlist, "g_usergroup_status");
 			$g_usergroup_status = $useridlist;
 		break;
 		case "m_group_assign":
 			foreach($grouplist as $group)
 				$objGroups->Add_Users_To_Group($group);
 		break;
 		case "m_remove_group":
 			$adodbConnection = GetAdodbConnection();
 			$adodbConnection->Execute("DELETE FROM UserGroup where UserId='$UserId' AND GroupId='$GroupId'");
 		break;
 
         case "m_SetVariable":  
             $objSession->SetPersistantVariable($_POST["fieldname"], $_POST["varvalue"]);
         break;
         case "m_SetSessionVariable":
             $objSession->SetVariable($_POST["fieldname"], $_POST["varvalue"]);
             //echo "Setting $fieldname to $varvalue<br>\n";
             if($_POST["fieldname"]=="SearchType")
                 $objSession->SetVariable("SearchWord","");
         break;
  
        case "m_edit_permissions":           
           if($ro_perm) break;
           
           if($_POST["CatEditStatus"] != -1)
           {
           	$objSession->SetVariable('PermCache_UpdateRequired', 1);
             $GroupId = $_POST["GroupId"];
             $CatId = $_POST["CategoryId"];
             $Module = $_POST["Module"];
             $ado = GetADODBConnection();
             $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE ModuleId='$Module'";
             $rs = $ado->Execute($sql);
             $PermNames = array();
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $PermNames[] = $data["PermissionName"];
                 $rs->MoveNext();
             }
             
             $inherit = array();
             if(is_array($_POST["inherit"]))
             {            
               foreach($_POST["inherit"] as $perm)
               {
                 $inherit[$perm] = 1;
               }
             }
             $access = array();
             if(is_array($_POST["permvalue"]))
             {            
               foreach($_POST["permvalue"] as $perm)
               {
                 $access[$perm] = 1;
               }
             }
             $objPermList = new clsPermList($CatId,$GroupId);
             $objPermList->LoadCategory($CatId);
 
             for($i=0;$i<count($PermNames);$i++)
             {                 
                if(!array_key_exists($PermNames[$i],$inherit))
                {
                    $PermValue = (int)$access[$PermNames[$i]];
                    
                    $Perm = $objPermList->GetPermByName($PermNames[$i]);                   
                    if($Perm)
                    {
                        $Id = $Perm->Get("PermissionId");
                        //echo "Editing $Id<br>\n";
                        $objPermList->Edit_Permission($Id,$CatId,$GroupId,$PermNames[$i],$PermValue,0);
                    }
                    else
                    {
                        //echo "Adding ".$PermNames[$i];
                        $objPermList->Add_Permission($CatId,$GroupId,$PermNames[$i],$PermValue,0);
                    }
                }
                else
                {        
                   $Perm = $objPermList->GetPermByName($PermNames[$i]);
                   if($Perm)
                   {
                       $Id = $Perm->Get("PermissionId");
                       $objPermList->Delete_Permission($Id);
                   }
                }
             }
             //$c = $objCatList->GetItem($CatId);
             //$glist = $objGroups->GetAllGroupList();
             //$ViewList = $objPermList->GetGroupPermList($c,"CATEGORY.VIEW",$glist );
             //$c->SetViewPerms("CATEGORY.VIEW",$ViewList,$glist);
             //$c->Update();
           }
         break; 
      case "m_perm_delete_group":
               
               $ado = GetADODBConnection();
               $CatId = $_POST["CategoryId"];
               foreach($_POST["itemlist"] as $groupid)
               {
                 $g = $objGroups->GetItemByField("ResourceId",$groupid);
                 if(is_object($g))
                 {                
                     $sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=$CatId AND GroupId=".$g->Get("GroupId");
                     if($objSession->HasSystemPermission("DEBUG.LIST"))
                         echo $sql."<br>\n";
                     $ado->Execute($sql);                  
                 }
               }
         break;
 
       case "m_user_addto_group":      	
             if($ro_perm) break;
             $user = $_POST["UserId"];
             if(is_numeric($user))
             {            
               if(strlen($_POST["grouplist"]))
               {              
                 $groups = explode(",",$_POST["grouplist"]);
                 if(is_array($groups))
                 {                
                   for($i=0; $i<count($groups);$i++)
                   {                 
                     $g = $objGroups->GetItemByField("ResourceId",$groups[$i]);
                     $g->AddUser($user);                 
                   }
                 }
                 else
                 {
                     $g = $objGroups->GetItem($groups);
                     $g->AddUser($user);
                 }
               }
             }
       break;
      case "m_group_add_user":       
          if($ro_perm) break;
          $group = $_POST["GroupId"];
          $EditGroups = new clsGroupList();
          $EditGroups->SourceTable = $objSession->GetEditTable($objGroups->SourceTable);
          $g = $EditGroups->GetItem($group);
 //         echo "Group: $group <br>\n";
          if(is_numeric($group))
          {
              $users = explode(",",$_POST["userlist"]);
              foreach($users as $userid)
              {
                 $u = $objUsers->GetItemByField("ResourceId",$userid);
                 $g->AddUser($u->Get("PortalUserId"));
              }
          }
 
       break;
       case "m_group_removeuser":
           if($ro_perm) break;
           $group = $_POST["GroupId"];
           $g =  $objGroups->GetItem($group);
           if($group>0)
           {
               foreach($_POST["itemlist"] as $user_id)
               {
                   $u = $objUsers->GetItemByField("ResourceId",$user_id);
                   $g->DeleteUser($u->Get("PortalUserId"));
               }
           }
       break;    
       case "m_user_removegroup":
            if($ro_perm) break;
            $user = $_POST["UserId"];
            if($user>0)
            {  
              foreach($_POST["itemlist"] as $groupid)
              {
                 $g = $objGroups->GetItem($groupid);
                 $g->DeleteUser($user);
              }
            }
       break;
       case "m_sendmail":
           $idlist = explode(",",$_POST["idlist"]);
           $html = (int)$_POST["html_enable"];
           $body = inp_escape($_POST["email_body"],$html);
           $subject = inp_escape($_POST["email_body"],$html);
           $Email = new clsEmailMessage();
      	  $Email->Set("Subject",$subject);
      	  $Email->Set("Template",$body);
      	  if($html)
      	    $Email->Set("MessageType","HTML");
      	  if(count($idlist)>0)
      	  {
      	    switch($_POST["IdType"])
              {        
      	      case "group":
      	      	foreach($idlist as $id)
      	        	$Email->SendToGroup($id);
      	      break;
                case "user":
      	        foreach($idlist as $id)
      	          	$Email->SendToUser($id);
                break;
      	    }/*switch*/
      	  }
      break;
      case "m_item_recount":
       RunDown($m_var_list["cat"],"UpdateCacheCounts");
      break;
      case "m_cat_delete":         
          if($objSession->HasCatPermission("CATEGORY.DELETE",$objCatList->CurrentCategoryID()))
          {         
            if(isset($_POST["catlist"]))
            {
              if(is_array($_POST["catlist"]))
                foreach($_POST["catlist"]  as $catid)
                {
                   $objCatList->Delete_Category($catid);
 
                }
            }
          }
      break;
      case "m_cat_cut":
          if(isset($_POST["catlist"]))
          { 
              if($objSession->HasCatPermission("CATEGORY.DELETE",$catid))
              {             
                $objCatList->CopyToClipboard("CUT","CategoryId",$_POST["catlist"]);
              }
              else
                $objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
          }
      break;
      case "m_cat_copy":
          if(isset($_POST["catlist"]))
          {
              $objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
          }
      break;
 
      case "m_paste":
 	     if($objCatList->ItemsOnClipboard()>0)
          { 
            /* category's paste function populates a sparse array where array[old_id]=new_id */
            $PastedCatIds = array();
  	       $objCatList->PasteFromClipboard($objCatList->CurrentCategoryID(),"Name");   
          }
          else
          {
            $clip = $objSession->GetVariable("ClipBoard");
            if(strlen($clip))
            {
                $ClipBoard = ParseClipboard($clip);               
                $Action= strtolower($ClipBoard["table"])."_paste";
            }
          }
        break;
      case "m_cat_move_up":
          if (isset($_POST["catlist"]))
          {         
              foreach($_POST["catlist"] as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
                  $cat->MoveUp();
              }
          }
      break;
      case "m_cat_move_down":
          if (isset($_POST["catlist"]))
          {
              $catlist=array_reverse($_POST["catlist"]);
              foreach($catlist as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
                  $cat->MoveDown();
              }
          }
      break;
      case "m_cat_approve":      
          if (isset($_POST["catlist"]))
          {         
              foreach($_POST["catlist"] as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
                  $cat->Approve();                 
              }         
          }
      break;
      case "m_cat_decline":
          if (isset($_POST["catlist"]))
          {         
              foreach($_POST["catlist"] as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
 //                 $cat->Deny();
                  RunDown($catid,"Deny");
              }         
          }
      break;     
 
      case "m_rel_delete":
          $adodbConnection= GetADODBConnection();
          $table = $objSession->GetEditTable("Relationship");
          if(isset($_POST["itemlist"]))
          {
            if(is_array($_POST["itemlist"]))
            {
              foreach($_POST["itemlist"] as $id)
              {
                $sql = "DELETE FROM ".$table." WHERE RelationshipId=".$id;
                $adodbConnection->Execute($sql);
                if($objSession->HasSystemPermission("DEBUG.LIST"))
                    echo $sql."<br>\n";
              }
            }
            else
            {
               $sql = "DELETE FROM ".$table." WHERE RelationshipId=".$_POST["itemlist"];
               $adodbConnection->Execute($sql);
               if($objSession->HasSystemPermission("DEBUG.LIST"))
                   echo $sql."<br>\n";
            }
          }
          break;
      case "m_add_relation":
        if($_POST["CatEditStatus"]==0)
        {       
          $RelList = new clsRelationshipList();
          $RelList->SourceTable = $objSession->GetEditTable("Relationship");
 
          //$r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
            //               0,(int)$_POST["Enabled"],$_POST["RelType"], $Rel);
          $ado = GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(RelationshipId) as MinValue FROM ".$RelList->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          
          $r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
                           0,(int)$_POST["Enabled"],$_POST["RelType"], $NewId);         
          
          $sql = "UPDATE ".$RelList->SourceTable." SET RelationshipId=".$NewId." WHERE RelationshipId=".$r->Get("RelationshipId");         
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);
        }
      break;
      case "m_edit_relation":
        if($_POST["CatEditStatus"]==0)
        {
          $RelList = new clsRelationshipList();
          $RelList->SourceTable = $objSession->GetEditTable("Relationship");
 
          $r = $RelList->GetItem($_POST["RelationshipId"]);
          if(is_object($r))
          {
            $r->Set("Enabled",(int)$_POST["Enabled"]);
            $r->Set("Type",(int)$_POST["RelType"]);
            $r->Set("Priority",(int)$_POST["priority"]);
            $r->Update();
          }
        }
      break;
      case "m_rel_move_up":
          $objRelList = new clsRelationshipList();
          $objRelList->SourceTable = $objSession->GetEditTable("Relationship");
          if (isset($_POST["itemlist"]))
          {         
              foreach($_POST["itemlist"] as $id)
              {
                  $r = $objRelList->GetItem($id);
                  $r->MoveUp($_POST["SourceId"]);
              }
          }
      break;
      case "m_rel_move_down":
          $objRelList = new clsRelationshipList();
          $objRelList->SourceTable = $objSession->GetEditTable("Relationship");
          if (isset($_POST["itemlist"]))
          {
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $r = $objRelList->GetItem($id);
                  $r->MoveDown($_POST["SourceId"]);
              }
          }
      break;
 
 
      case "m_add_category":
          if(ValidDate($_POST["cat_date"],GetDateFormat()))
          {         
            $CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
          }
          else
            $CreatedOn = time();
          $html = (int)$_POST["html_enable"];
 
          $cat_pick = $_POST["cat_pick"];
          $Status = (int)$_POST["status"];
          $Hot=(int)$_POST["itemhot"];
          $Pop = (int)$_POST["itempop"];      
          $New = (int)$_POST["itemnew"];
 
          $objEditItems = new clsCatList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Category");
          $cat = $objEditItems->Add($_POST["ParentId"], $_POST["cat_name"], inp_escape($_POST["cat_desc"],$html), $CreatedOn, 
                             $cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"], 
                             $_POST["meta_keywords"],$_POST["meta_desc"]);
             $objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
             $objCustomEdit->LoadResource($cat->Get("ResourceId"));
             $CustomFields = new clsCustomFieldList(1);
             $DataChanged = FALSE;
             foreach($_POST as $key=>$value)
             {
             	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
             }          	
             if($DataChanged)
             	$objCustomEdit->SaveData();                            
                          
      break;              
 
      case "m_edit_category":                 
          $CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
          $cat_pick = $_POST["cat_pick"];
          $Status = (int)$_POST["status"];
          $Hot=(int)$_POST["itemhot"];
          $Pop = (int)$_POST["itempop"];      
          $New = (int)$_POST["itemnew"];
 
          $html = (int)$_POST["html_enable"];
          $objEditItems = new clsCatList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Category");
          
          // check if name of cat isn't changed: begin
          $original_cats = new clsCatList();
          $original_cat = $original_cats->GetItemByField('CategoryId', $_POST['CategoryId']);
          if( $original_cat->Get('Name') != $_POST['cat_name'] ) 
          	$objSession->SetVariable('PermCache_UpdateRequired', 1);
          unset($original_cat, $original_cats);
          // check if name of cat isn't changed: end
          
          $cat = $objEditItems->Edit_Category($_POST["CategoryId"],inp_escape($_POST["cat_name"],$html), inp_escape($_POST["cat_desc"],$html), $CreatedOn, $cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"], $_POST["meta_keywords"], $_POST["meta_desc"]);         
                                       
          $objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
          $objCustomEdit->LoadResource($cat->Get("ResourceId"));
          $CustomFields = new clsCustomFieldList(1);
          $DataChanged = FALSE;
          foreach($_POST as $key=>$value)
          {
 	       	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
          }          	
          if($DataChanged)
          	$objCustomEdit->SaveData();  
          	                                      
      break;
      case "m_edit_custom_data":
      	
      	$id = $_POST["ItemId"];                   
         $objEditData = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));		
         $objEditData->SetTable('edit');
         $ado = GetADODBConnection();
 
         if($id && is_array($_POST["CustomData"]))
         {
             foreach($_POST["CustomData"] as $FieldId => $Value)
             {                                
                 $sql = "SELECT count(*) as reccount FROM ".$objEditData->SourceTable." WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
                 $rs = $ado->Execute($sql);            
                 $intable = $rs->fields["reccount"];
                 if(!$intable)
                 {                
                     $sql = "INSERT INTO ".$objEditData->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$id."','$FieldId','$Value')";
                     $ado->Execute($sql);
                     //echo $sql."<br>\n";
                 }
                 else
                 {
                   $sql = "UPDATE ".$objEditData->SourceTable." SET Value='".$Value."' WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
                   $ado->Execute($sql);
                   //echo $sql."<br>\n";
                 }
             }            
         }
         $objEditData->SetTable('live');
      break;
      case "m_customfield_edit":
        	if($ro_perm) break;
         $DataType = $_POST["DataType"];
         $FieldId = $_POST["CustomFieldId"];
         $FieldName = $_POST["fieldname"];
         //$FieldLabel = $_POST["fieldlabel"];
         if(strlen($FieldName))
         {        
         	$objCustomFields = new clsCustomFieldList($DataType);
         	$objCustomFields->EditField($FieldId,$DataType,$FieldName,"",(int)$_POST["generaltab"],
           							    $_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
           							    $_POST["valuelist"]);
         }
         unset($objCustomFields);
      break;
      case "m_customfield_add":
         if($ro_perm) break;
         $DataType = $_POST["DataType"];        
         $FieldName = $_POST["fieldname"];
         //$FieldLabel = $_POST["fieldlabel"];
         if(strlen($FieldName))
         {
           $objCustomFields = new clsCustomFieldList($DataType);
           $objCustomFields->AddField($DataType,$FieldName,"",(int)$_POST["generaltab"],
           							 $_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
           							 $_POST["valuelist"]);
           unset($objCustomFields);
         }
      break;
      case "m_customfield_delete":
      	if($ro_perm) break;
         $DataType = $_POST["DataType"];        
         $objCustomFields = new clsCustomFieldList($DataType);
 
         foreach($_POST["itemlist"] as $f)
         {
             $objCustomFields->DeleteField($f);
         	//$c = $objCustomFields->GetItem($f);
             //$c->Delete();
         }
         unset($objCustomFields);
      break;
      case "m_SearchConfig_Edit":
      	if($ro_perm) break;
         $SimpleValues = $_POST["simple"];
         $AdvValues = $_POST["advanced"];
         $module = $_POST["module"];
         $priority = $_POST["pri"];
         //phpinfo(INFO_VARIABLES);
         $objSearchConfig = new clsSearchConfigList($module);
         foreach($objSearchConfig->Items as $i)
         {
           $id = $i->Get("SearchConfigId");
           $objSearchConfig->EditFieldSettings($id,(int)$SimpleValues[$id],(int)$AdvValues[$id],$priority[$id]);       
         }
         $objSearchConfig->Clear();
         /* save relevence settings */
         $vals = $_POST["req_increase"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Increase_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_keyword"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Keyword_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_pop"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Pop_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_rating"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Rating_".$var;
             $objConfig->Set($cfg,$value);
         }
      break;
      case "m_keyword_reset":
          if($ro_perm) break;
          $objSearchList = new clsSearchLogList();
          foreach($_POST["itemlist"] as $k)
          {
              $c = $objSearchList->GetItem($k);
              $c->Delete();
          }
      break;
      case "m_review_add":     
        $post_info = GetSubmitVariable($_POST, 'EditStatus');
        if($post_info['variable'] > -1)
        {
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          $Pending = (int)$_POST["review_pending"];
          $Enabled = (int)$_POST["review_enabled"];
          $Status = (int)$_POST["status"];
          $CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat()); 
          $CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
          $html = (int)$_POST["html_enable"];         
          $ReviewText = inp_escape($_POST["review_body"],1);
          
          $CreatedById = 0;
          if(strlen($_POST["createdby"])>0)
          {
          	if(strtolower($_POST["createdby"])=="root")
          	{
          	  $CreatedById = -1;
          	}
          	else 
          	{
            	  $u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
            	  if(is_object($u))
            	  {
            	    $CreatedById = $u->Get("PortalUserId");
            	    if($CreatedById<1)
            	    {
            	  	  $CreatedById = $objSession->Get("PortalUserId");
            	    }
            	  }
            	  else
            	    $CreatedById = $objSession->Get("PortalUserId");
          	}
          }
          else
            $CreatedById = $objSession->Get("PortalUserId");
          
          $r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress, 
                                      (int)$_POST["review_priority"], $_POST["ItemId"],$_POST["ItemType"],
                                      $CreatedById,$html, $post_info['Module']);                                    
          $ado = GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(ReviewId) as MinValue FROM ".$objReviews->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objReviews->SourceTable." SET ReviewId=".$NewId." WHERE ReviewId=".$r->Get("ReviewId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);
        }
      break;
      case "m_review_edit":     
        $post_info = GetSubmitVariable($_POST, 'EditStatus');
        if($post_info['variable'] > -1)
        {
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          $Status = (int)$_POST["status"];
          $CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat()); 
          $CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
          $html = (int)$_POST["html_enable"];
          $ReviewText = inp_escape($_POST["review_body"],1);
          $ReviewId = $_POST["ReviewId"];         
          $CreatedById = 0;
          if(strlen($_POST["createdby"])>0)
          {
          	if(strtolower($_POST["createdby"])=="root")
          	{
          	  $CreatedById = -1;
          	}
          	else 
          	{
            	  $u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
            	  if(is_object($u))
            	  {
            	    $CreatedById = $u->Get("PortalUserId");
            	    if($CreatedById<1)
            	    {
            	  	  $CreatedById = $objSession->Get("PortalUserId");
            	    }
            	  }
            	  else
            	    $CreatedById = $objSession->Get("PortalUserId");
          	}
          }         
          $r = $objReviews->EditReview($ReviewId,$CreatedOn,$ReviewText,$Status, $IPAddress, 
                                       (int)$_POST["review_priority"],$_POST["ItemId"],$_POST["ItemType"],
                                       $CreatedById,$html, $post_info['Module']);  
        }
      break;
      case "m_review_delete":
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          foreach($_POST["itemlist"] as $id)
          {
              $objReviews->DeleteReview($id);
          }         
      break;
      case "m_review_approve":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->Set("Status",1);
                  $i->Update();
              }
          }
      break;
      case "m_review_deny":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->Set("Status",0);
                  $i->Update();
              }
          }
      break;     
      case "m_review_move_up":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->MoveUp();
              }
          }
      break;
      case "m_review_move_down":
          if (isset($_POST["itemlist"]))
          {
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->MoveDown();
              }
          }
      break;
      case "m_theme_add":
          $objEditItems = new clsThemeList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Theme");
          $Primary = (int)$_POST["primary"];
          if(!(int)$_POST["enabled"])
            $Primary = 0;
          $t = $objEditItems->AddTheme($_POST["name"],$_POST["description"],(int)$_POST["enabled"],
                                       (int)$_POST["CacheTimeout"],$Primary);
 
          $ado = GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(ThemeId) as MinValue FROM ".$objEditItems->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objEditItems->SourceTable." SET ThemeId=".$NewId." WHERE ThemeId=".$t->Get("ThemeId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          if ($Primary==1) 
          {
              $objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
          }
          $ado->Execute($sql);
      break;
      case "m_theme_edit":        
          $objEditItems = new clsThemeList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Theme");
          $Primary = (int)$_POST["primary"];
          if(!(int)$_POST["enabled"])
            $Primary = 0;         
            
          $objEditItems->EditTheme($_POST["ThemeId"],$_POST["name"],$_POST["description"],
                                   (int)$_POST["enabled"],$Primary,(int)$_POST["CacheTimeout"]);
          if ($Primary==1) 
          {
              $objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
          }
      break;
      case "m_theme_delete":
          if (isset($_POST["itemlist"]))
          {   
              $Themes = new clsThemeList();
              foreach($_POST["itemlist"] as $id)
              {
                  $Themes->DeleteTheme($id);
              }
          }
      break;
      case "m_theme_primary":
          if( count($_POST['itemlist']) )
          {
          	$ThemeId = array_shift( $_POST['itemlist'] );
            	$t = new clsThemeList();
            	$t->SetPrimaryTheme($ThemeId);
          }
      break;
      
      case "m_template_edit":
        
        	$ThemeId = $_POST["ThemeId"];
        	$FileId = $_POST["FileId"];
        	$f = new clsThemeFile($FileId);
        
        	$f->Set("Description", $_POST["Description"] );
        	$f->Update();
        	$c = stripslashes($_POST["contents"]);
        	$f->SaveFileContents($c);
        	break;    
      case "m_template_add":
       	
       	$ThemeId = $_POST["ThemeId"];
       	if( !is_object($f) ) $f = new clsThemeFile();
        	
        	$FilePath = $_POST['name'];
       
        	if(!$FilePath)
        	{
        		$f->SetError('Template Name is required',3);
        		break;
        	}
        	else
        	{
        		if( substr($FilePath,1) != '/' ) $FilePath = '/'.$FilePath;
        		if( substr($FilePath,-3) != '.tpl' ) $FilePath .= '.tpl';
        		$FileName = basename($FilePath);
        		$FilePath = dirname($FilePath);
  			
  			// test if such file not already created
        		
        		$f->LoadFromDataBase( Array($FilePath,$FileName), Array('FilePath','FileName') );      	
        		if( !$f->Get('FileId') )
        		{
        			$f->Set( 	Array('FilePath','FileName','ThemeId', 'Description'),
        						Array($FilePath, $FileName,$_POST['ThemeId'], $_POST["Description"])
        					);
        			
        			if( $f->IsWriteablePath(true) )
        			{	
        				$f->Create();
        				$c = stripslashes($_POST["contents"]);
        				$f->SaveFileContents($c, true);
        			}
        		}
        		else
        			$f->SetError('Template with this name already exists',4);
 		}
      	break;
      case "m_template_delete":
 		$dummy = new clsThemeFile();
 		foreach($_POST["itemlist"] as $FileId)
         {            
 			$dummy->LoadFromDatabase($FileId);
 			$dummy->Delete();
 		}		
      	break;
      	
      case "m_lang_add":         
          $objEditItems = new clsLanguageList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Language");
          $l = $objEditItems->AddLanguage($_POST["packname"],$_POST["localname"],
                                          (int)$_POST["enabled"],(int)$_POST["primary"],
                                          $_POST["icon"],$_POST["date_format"],$_POST["time_format"],
                                          $_POST["decimal"],$_POST["thousand"]);
 
          $ado = GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(LanguageId) as MinValue FROM ".$objEditItems->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objEditItems->SourceTable." SET LanguageId=".$NewId." WHERE LanguageId=".$l->Get("LanguageId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);         
          if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
          {         	
             $sql = "SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"];
             if($objSession->HasSystemPermission("DEBUG.LIST"))
                 echo $sql."<br>\n";
 
             $rs = $ado->Execute($sql);            
             $plist = new clsPhraseList();
             $plist->SourceTable = $objSession->GetEditTable("Phrase");
             $sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
             $as = $ado->Execute($sql);
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else
               $MinId = 0;
             $MinId--;              
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $plist->AddPhrase($data["Phrase"],$NewId,$data["Translation"],$data["PhraseType"]);
                 $sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
                 $ado->Execute($sql);
                 $MinId--;
                 $rs->MoveNext();
             }
          }
      break;
      case "m_lang_export":
      	 include_once($pathtoroot."kernel/include/xml.php");
          $Ids = $_POST["LangList"]; // language ids list to export phrases from
          
          $phrase_types = GetVar('langtypes');
          $phrase_types = ($phrase_types !== false) ? implode(',',$phrase_types) : null;
          
          $filename=$_POST["filename"];
          if(strlen($filename)>0)
          {
              $ExportFilename = $pathtoroot.$admin."/export/".$filename;                         
   	         $ExportResult = $objLanguages->ExportPhrases($ExportFilename,$Ids, $phrase_types);
          }
      break;
      case "m_lang_edit":
          $objEditItems = new clsLanguageList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Language");
          $objEditItems->EditLanguage($_POST["LanguageId"],$_POST["packname"],
                                      $_POST["localname"],(int)$_POST["enabled"],
                                      (int)$_POST["primary"], $_POST["icon"],$_POST["date_format"],
                                      $_POST["time_format"], $_POST["decimal"],$_POST["thousand"]);
                                      
          if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
          {
             $ado = GetADODBConnection();
             $rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"]);
             $plist = new clsPhraseList();
             $plist->SourceTable = $objSession->GetEditTable("Phrase");
             $sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
             $as = $ado->Execute($sql);
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else
               $MinId = 0;
             $MinId--;  
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $plist->AddPhrase($data["Phrase"],$_POST["LanguageId"],$data["Translation"],$data["PhraseType"]);
                 $sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
                 $ado->Execute($sql);
                 $MinId--;
                 $rs->MoveNext();
             }
             unset($plist);
          }
 
      break;
      case "m_lang_delete":
      	if($ro_perm) break;
          if (isset($_POST["itemlist"]))
          {   
             $Phrases = new clsPhraseList();
             foreach($_POST["itemlist"] as $id)
             {
                 $objLanguages->DeleteLanguage($id);
                 $Phrases->DeleteLanguage($id);
             }    
             unset($Phrases);
          }
      break;
      case "m_lang_select":
          $LangId = (int)$_POST["langselect"];         
          if($LangId)
          {           	
            if($objSession->Get("PortalUserId")>0)
            {
              	//echo "$LangId";
            		$objSession->SetPersistantVariable("Language",$LangId);              
            }
            $objSession->Set("Language",$LangId); 
            $objSession->Update();
            $m_var_list_update["lang"] = $LangId;
            $m_var_list["lang"] = $LangId;
          }
      break;     
      case "m_phrase_edit":     
          $objPhraseList = new clsPhraseList();
          if((int)$_POST["direct"] != 1)                 	
          	$objPhraseList->SourceTable = $objSession->GetEditTable("Phrase");
          $Phrases = $_POST["name"];
          foreach($Phrases as $PhraseId =>$name)
          {
            if($PhraseId>0)
            {         
            		$objPhraseList->EditPhrase($PhraseId,$_POST["name"][$PhraseId],$_POST["LanguageId"],$_POST["translation"][$PhraseId],$_POST["phrasetype"][$PhraseId]);
            }
          }
          
          if(strlen($_POST["name"][0]) && strlen($_POST["translation"][0]) && $_POST['Action1'] == "new")
          {
            		$r = $objPhraseList->AddPhrase($_POST["name"][0],$_POST["LanguageId"],$_POST["translation"][0],$_POST["phrasetype"][0]);           
            		if ($r != "Error") {
 	           		$ado = GetADODBConnection();
 	           		$rs = $ado->Execute("SELECT MIN(PhraseId) as MinValue FROM ".$objPhraseList->SourceTable);
 	           		$NewId = $rs->fields["MinValue"]-1;
 	           		$sql = "UPDATE ".$objPhraseList->SourceTable." SET PhraseId=".$NewId." WHERE PhraseId=$PhraseId";
 	           		if($objSession->HasSystemPermission("DEBUG.LIST"))
 	               		echo $sql."<br>\n";
 	           		$ado->Execute($sql);    
            		}
            		else {
            			$add_error = "Language tag with the same name already exists!";
            		}
          }
          else if ($_POST['Action1'] == "new") {
          	$add_error = "Fields name and translation are required!";
          }
          unset($objPhraseList);
      break;
      case "m_config_missing_phrase":
         //phpinfo(INFO_VARIABLES);
         $LangId = $_POST["LangId"];
         $ThemeId = $_POST["ThemeId"];
         if(is_array($_POST["Phrase"]))
         {
             $objPhraseList = new clsPhraseList();
             $objPhraseList->SourceTable = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 
             foreach($_POST["Phrase"] as $p => $value)
             {
                 if(strlen($value))
                 {           
                   $obj = $objPhraseList->GetItemByField("Phrase",$p,TRUE);
                   if(is_object($obj))
                   {                  
                       if($obj->Get("Phrase")==$p)
                       {
                           $obj->Set("Translation",$value);
                           $obj->Update();
                       }
                       else
                           $objPhraseList->AddPhrase($p,$LangId,$value,1);
                   }
                   else
                     $objPhraseList->AddPhrase($p,$LangId,$value,1);
                 }
             }
         }
      break;
      case "m_phrase_delete":
         if (isset($_POST["itemlist"]))
         {   
            foreach($_POST["itemlist"] as $id)
            {
            	 $sql = "UPDATE ".$objSession->GetEditTable("Phrase")." SET LanguageId = 0 WHERE PhraseId = ".$id;
            	 $ado = GetADODBConnection();
            	 $ado->Execute($sql);
            }
         }
         unset($objPhraseList);
      break;
      case "m_emailevent_disable":
         if($ro_perm) break;
         $objEvents = new clsEventList();
         if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",0);
               $m->Update();
             }
          }
          unset($objEvents);
      break;
      case "m_emailevent_enable":
          if($ro_perm) break;
          $objEvents = new clsEventList();
          if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",1);
               $m->Update();
             }
          }
          unset($objEvents);
      break;
      case "m_emailevent_frontonly":
         if($ro_perm) break;
         $objEvents = new clsEventList();
         if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",2);
               $m->Update();
             }
          }
          unset($objEvents);
      break;     
      case "m_dlid":
          echo $Action.":".$DownloadId;
          die();
      break;
      case "m_emailevent_user":
          if($ro_perm) break;
          $objEvents = new clsEventList();
          //phpinfo(INFO_VARIABLES);
          //$objEvents->SourceTable = $objSession->GetEditTable("Events");
          $ids = $_POST["EventId"];
 		 $ids = str_replace("[","",$ids);
 		 $ids = str_replace("]","",$ids);
 		 $ids = str_replace("\"","",$ids);
 		 $ids = str_replace("\\","",$ids);
 		 
          
          $idlist = explode(",",$ids);
          foreach($idlist as $EventId)
          {
          	$id = (int)stripslashes($EventId);
              $e =& $objEvents->GetItem((int)$EventId);
              $e->Set("FromUserId", $_POST["FromUserId"]);
              $e->Update();
          }
          $objEvents->Clear();
          unset($objEvents);
      break;
      case "m_emailevent_edit":         
          $Template = $_POST["headers"];
          if(strlen($Template))
          {
          	$Template .= "\n";
          }
 		 $Template = str_replace("\n\n","",$Template);                     
          $Template .= "Subject: ".$_POST["subject"]."\n\n";
          $Template .= $_POST["messageBody"];
          $objMessages = new clsEmailMessageList();
          $objMessages->SourceTable = $objSession->GetEditTable("EmailMessage");
          $m =& $objMessages->GetItem($_POST["MessageId"]);
          if(is_object($m))
          {
              if($_POST["sendhtml"]==1)
              {             
                $m->Set("MessageType","html");
              }
              else
                $m->Set("MessageType","text");
 
              $m->Set("Template",$Template);
              $m->Update();
          }
      break;
      case "m_config_edit":
      	 //phpinfo(INFO_VARIABLES);
          if($ro_perm) break;
          $objAdmin = new clsConfigAdmin();
          $objAdmin->module = $_POST["module"];
          $objAdmin->section = $_POST["section"];
          if($objAdmin->section=="in-portal:configure_users")
          {
          	if(strlen($_POST["RootPass"]) && strlen($_POST["RootPassVerify"]))
          	{
          	  if($_POST["RootPass"]==$_POST["RootPassVerify"])
          	  {
          	  	$_POST["RootPass"] = md5($_POST["RootPass"]);
          	  }	
          	}
          	else
          	{
          	  $_POST["RootPass"] = $objConfig->Get("RootPass");
          	  $_POST["RootPassVerify"] = $objConfig->Get("RootPassVerify");         	  
          	}
          }
          $objAdmin->LoadItems(FALSE);
          $objAdmin->SaveItems($_POST);
      break;
 
      case "m_mod_enable":
         if($ro_perm) break;
          if (isset($_POST["itemlist"]))
          {   
              foreach($_POST["itemlist"] as $id)
              {
                  $m =& $objModules->GetItemByField("Name",$id);
                  if(is_object($m))
                  {
                    $m->Set("Loaded",1);
                    $m->Update();                 
                  }                
              }
              $_GET["Refresh"] = 1;
          }
      break;
      case "m_mod_disable":
      	if($ro_perm) break;
          if (isset($_POST["itemlist"]))
          {   
              foreach($_POST["itemlist"] as $id)
              {
              	if($id != "In-Portal")
              	{
                    $m =& $objModules->GetItemByField("Name",$id);
                    if(is_object($m))
                    {
                      $m->Set("Loaded",0);
                      $m->Update();                 
                    }
              	}
              }
              $_GET["Refresh"] = 1;
          }
      break;
 
      case "m_img_add":
        $objImageList = new clsImageList();
 	   $objImageList->SourceTable = $objSession->GetEditTable("Images");
        $LocalImage=0;
        $LocalThumb=0;
        $DestDir = "kernel/images/";
        
        $UserThumbSource = (int)$_POST["imgLocalThumb"];
 	   $LocalThumb = $UserThumbSource;
        
 	   $thumb_url = !$LocalThumb? $_POST["imgThumbUrl"] : "";
               
        if($_POST["imgSameImages"])
        {
            	$LocalImage = $LocalThumb;
            	$full_url = $thumb_url;
        }
        else
        {
        		$LocalImage = (int)$_POST["imgLocalFull"];
          	$file = $_FILES["imgFullFile"];
          	$full_url = $LocalImage? "" : $_POST["imgFullUrl"];
        }
 
        if((!strlen($thumb_url) && !$LocalThumb) || (!strlen($full_url) && !$LocalImage))
        {
          break;
        }
        
        $ado = GetADODBConnection();
        $sql = "SELECT MIN(ImageId) as MinValue FROM ".$objImageList->SourceTable;
        $rs = $ado->Execute($sql);
        $NewId = ($rs->fields["MinValue"]<0)? $rs->fields["MinValue"]-1 : -1;
        
        $img = $objImageList->Add($_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImage, $LocalThumb, $full_url, $thumb_url, (int)$_POST["imgEnabled"], 0, (int)$_POST["imgDefault"], 0,(int)$_POST["imgSameImages"], $NewId);
        $img->Set("ImageId", $NewId);
        
 //       $img->debuglevel=1;
        
        /*
        $sql = "UPDATE ".$objImageList->SourceTable." SET ImageId=".$NewId." WHERE ImageId=0";
        $ado->Execute($sql);
        
 //       $img->Update();
        */
 //       echo "SL: $sql $NewId<BR>";
        
 //       $img->debuglevel=1;
         
 	   $img->Pending=TRUE;	                                 
        if($LocalImage)
        {
            $file = $_FILES["imgFullFile"];
            if(is_array($file))
            {
              if($file["size"]>0)
              {
                $img->Set("LocalPath",$img->StoreUploadedImage($file,1, $DestDir,0));
                $uploaded=1;
              }
            }
        }
        
        if($LocalThumb)
        {
            $thumb = $_FILES["imgThumbFile"];
            if(is_array($thumb))
            {
              if($thumb["size"]>0)
              {
                $img->Set("ThumbPath",$img->StoreUploadedImage($thumb,1, $DestDir,1));
                $uploaded=1;
              }
            }
        }  
        if($uploaded==1)
           $img->Update();
        
      break;
      
      case "m_img_edit":
      
        	$objImageList = new clsImageList();
        	$objImageList->SourceTable = $objSession->GetEditTable("Images");
        
 //       $img->debuglevel=1;
        
        	$img = $objImageList->GetItem($_POST["ImageId"]);
 
 	    ## Get original values
        	$LocalImage = $img->Get("LocalImage");
        	$LocalThumb = $img->Get("LocalThumb");
        	$SameImages = $img->Get("SameImages");
        	$ThumbPath = $img->Get("ThumbPath");
        
        	## New values
        	$LocalThumbN = (int)$_POST["imgLocalThumb"];
        	$LocalImageN = (int)$_POST["imgLocalFull"];
        	
  		$FULLFile = $_FILES["imgFullFile"];
         $THFile = $_FILES["imgThumbFile"]; 
         
         $DestDir = "kernel/images/";
         $img->Pending = FALSE;
         
         $SameImagesN = 0;
         $uploaded = 0;
 
        	## Images were the same, but not any more
        	if ($SameImages && !$_POST["imgSameImages"])
        	{	
        		## TH was a local file
         	if ($LocalThumb)
         	{
         		## TH image
         		{	
         			## Try to Delete OLD FULL
 				   	$img->DeleteLocalImage(FALSE, TRUE);
 				   	
 				   	## FULL image select, but field EMPTY - make a copy of old TH as FULL 
         			if ($LocalImageN && !(int)$FULLFile["size"])
         			{   
 //        				echo $pathToPending = $img->GetImageDir();
         				if (!eregi("pending/$", $pathToPending))
 	        				$pathToPending.= "pending/"; 
         					
         				$LocalThumb_File = $img->GetFileName(1);
         				
 //        				echo "<b>CAN'T FIND FILE:</b> ".$pathToPending.$LocalThumb_File."<BR>";
         				
         				if (file_exists($pathToPending.$LocalThumb_File))
 						{							
 				   			$LocalThumb_FileN = eregi_replace("^th_", "", $LocalThumb_File);		   			
 							$LocalThumb_FullFileN = $pathToPending.$LocalThumb_FileN;						
 							@unlink($LocalThumb_FullFileN);
 							@copy($pathToPending.$LocalThumb_File, $LocalThumb_FullFileN);
 					
 			   				$uploaded = 1;
 			   				$copied = 1;
 //			   				echo "COPING: ".$DestDir."pending/".$LocalThumb_FileN." <BR>";
 						}
 						else
 						{
 //							echo "CAN'T FIND FILE: ".$pathToPending.$LocalThumb_File."<BR>";
         				}					
         			}
         			## Upload new FULL image
         			elseif ($LocalImageN && (int)$FULLFile['size'])
         			{
         				$FULL_FileToUpload = $FULLFile;
         				$FULL_URL = "";         
         				
 //        				echo "	Upload new FULL image";				
         			}
         			## Full is URL
         			elseif (!$LocalImageN)
         			{
         				$img->DeleteLocalImage(FALSE, TRUE);
         				$FULL_URL = $_POST['imgFullUrl'];  
         				$FULL_FileToUpload = "";      			
         			}
         			else
         			{
 //        				echo "	## Unknow condition";
         			}
         				
         			## Take care of Thumbnail here
         			if ($LocalThumbN)
         			{     			        			
         				## Delete old if NEW TH image selected
         				if ((int)$THFile['size'])
         				{
         					$img->DeleteLocalImage(TRUE, FALSE);
         					$TH_FileToUpload = $THFile;
         				}
         				else
         					$TH_FileToUpload = "";        			
         			}
         			else
         			{
         				$img->DeleteLocalImage(TRUE, FALSE);
         				$TH_FileToUpload = "";
         				$TH_URL = $_POST['imgThumbUrl'];     
         			}
         		}
         	}
         	## TH was URL
         	else
         	{
         		## Take care of FULL image here
         		if ($LocalImageN && (int)$FULLFile["size"])
         		{
         			$FULL_FileToUpload = $FULLFile; 
         			$FULL_URL = "";        				
         		}
         		## Full is URL (or image size 0)
         		else
         		{
         			$FULL_FileToUpload = "";
         			$FULL_URL = $_POST['imgFullUrl'];        	      		
         		}
         		
         		## Take care of Thumbnail here
         		if ($LocalThumbN)    
         		{ 			        			
         			$TH_FileToUpload = (int)$THFile['size']? $THFile : "";        			
         			$TH_URL = "";
         		}
         		else
         		{
         			$TH_FileToUpload = "";
         			$TH_URL = $_POST['imgThumbUrl'];     
         		}     		
         	}
        	}
       	## Images were the same, and still the same
        	elseif ($SameImages && $_POST['imgSameImages'])
        	{       		
        		## Take care of Thumbnail & FULL here
         	if ($LocalThumbN)
         	{	        			        		
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;
         		}
         		else 
         			$TH_FileToUpload = "";
         			
         		$FULL_URL = $TH_URL = "";      			
         	}
         	else
         	{
         		$TH_FileToUpload = $FULL_FileToUpload = "";
         		$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];            		 
         	}
         	
         	## Delete old FULL image    		
        		$img->DeleteLocalImage(FALSE,TRUE);
         	
         	$SameImagesN = 1;        	
        	}
        	## Images were NOT the same, and selected as the same now
        	elseif (!$SameImages && $_POST["imgSameImages"])
        	{
        		## Take care of Thumbnail & FULL here
         	if ($LocalThumbN)
         	{	        			
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;
         		}
         		else 
         			$TH_FileToUpload = "";
         		
         		
         		$FULL_URL = $TH_URL = "";        			
         	}
         	else
         	{   
         		$img->DeleteLocalImage(TRUE, FALSE);
         		$TH_FileToUpload = $FULL_FileToUpload = "";
         		$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];         		           		 
         	}
         	
         	## Clean up FULL image
         	$img->DeleteLocalImage(FALSE, TRUE);	
         	
         	$SameImagesN = 1;
        	}
        	## Images were NOT the same, and selected as NOT the same
        	elseif (!$SameImages && !$_POST["imgSameImages"])
        	{
        		## Take care of Thumbnail
         	if ($LocalThumbN)
         	{	        			
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;        			
         		}
         		else 
         			$TH_FileToUpload = "";       		
         		
         		$TH_URL = "";
         	}
         	else
         	{
         		$img->DeleteLocalImage(TRUE, FALSE);
         		$TH_FileToUpload = "";
         		$TH_URL = $_POST['imgThumbUrl'];            		 
         	}
         	
         	## Take care of FULL here
         	if ($LocalImageN)
         	{
         		if ((int)$FULLFile['size'])
         		{
         			$img->DeleteLocalImage(FALSE, TRUE);
         			$FULL_FileToUpload = $FULLFile;
         		}
         		else
         			$FULL_FileToUpload = "";       	        	
         		
         		$FULL_URL = "";
         	}
         	else
         	{        		
         		$img->DeleteLocalImage(FALSE, TRUE);        		
         		$FULL_FileToUpload = "";
         		$FULL_URL = $_POST['imgFullUrl'];
         	}        	
        	}
        	## Unknow condition	
        	else
        	{
        		;
        	}
      
 		$img = $objImageList->Edit($_POST["ImageId"],$_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImageN, $LocalThumbN, $FULL_URL, $TH_URL, (int)$_POST["imgEnabled"], (int)$_POST["imgPriority"], (int)$_POST["imgDefault"], 0, $SameImagesN);
 		
 //		echo "<B>DATA:</B> <BR> LocalImageN: $LocalImageN, LocalThumbN: $LocalThumbN, FULL_URL: $FULL_URL, TH_URL: $TH_URL, SameImagesN: $SameImagesN <BR>";
        
 	   
 	   	$img->Pending = TRUE;
 	   	
 		if (!empty($FULL_FileToUpload))
 		{
 			$img->Set("LocalPath",$img->StoreUploadedImage($FULL_FileToUpload, 1, $DestDir, 0));
 			$uploaded = 1;
 		}
 		/*
 		elseif (!$LocalImageN)
 		{
 			$img->Set("LocalPath", "");
 			$uploaded = 1;
 		}
 		*/
 		
 		if (!empty($TH_FileToUpload))
 		{
 			$img->Set("ThumbPath", $img->StoreUploadedImage($TH_FileToUpload, 1, $DestDir, 1));
 			$uploaded = 1;
 		}
 		
 		if ($copied)
 		{
 			$img->Set("LocalPath", $DestDir."pending/".$LocalThumb_FileN);	
 			$uploaded = 1;
 		}
 		      
        if($uploaded==1)
           $img->Update();   
               
      break;
      case "m_img_move_up":
          if (isset($_POST["itemlist"]))
          {
              $objImageList = new clsImageList();
              $objImageList->SourceTable = $objSession->GetEditTable("Images");
              foreach($_POST["itemlist"] as $id)
              {
                  $img = $objImageList->GetItem($id);
                  $img->MoveUp();
              }
          }
      break;
      case "m_img_move_down":
          if (isset($_POST["itemlist"]))
          {
              $objImageList = new clsImageList();
              $objImageList->SourceTable = $objSession->GetEditTable("Images");
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $img = $objImageList->GetItem($id);
                  $img->MoveDown();
              }
          }
      break;
 
      case "m_img_delete":
        if(isset($_POST["itemlist"]))
        {       
          $objImageList = new clsImageList();
          $objImageList->SourceTable = $objSession->GetEditTable("Images");
          foreach($_POST["itemlist"] as $id)
          {
              $img = $objImageList->GetItem($id);
              $img->Set("ResourceId", 0);
              $img->Update();
              //$img->Delete();
          }
        }
      break;
      case "m_restore_delete":
        $bdate = $_POST["backupdate"];
        if($bdate>0)
        {
        	 $BackupFile = $objConfig->Get("Backup_Path")."/dump".$bdate.".txt";
        	 if(file_exists($BackupFile))
        	 	unlink($BackupFile);
        }
      break;  
      case "m_taglib":
      	include($pathtoroot."kernel/include/tag-class.php");
      	ParseTagLibrary();
     break; 	
     case "m_sql_query":
 		$SqlQuery = $_POST["sql"];
 		$ado = GetADODBConnection();
 		if(strlen($sql))
 		{
 		  $SqlResult = $ado->Execute(stripslashes($SqlQuery));
   	  	  $SqlError = $ado->ErrorMsg();
 		  $SqlErrorNum = $ado->ErrorNo();
 		}
     break;
     case "m_purge_email_log":
 	 	 if($ro_perm) break;
 	 	 $ado = GetADODBConnection();       	
 
 		$sql = "DELETE FROM ".GetTablePrefix()."EmailLog";
 		$ado->Execute($sql);
     break;    
     case "m_session_delete":
 	 	 if($ro_perm) break;
 	 	 $ado = GetADODBConnection();       	
          if (count($_POST['itemlist']) > 0) {
 	 	 	foreach($_POST["itemlist"] as $id)
          	{
       			$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey='$id'";
       			$ado->Execute($sql);
          	}
          }
          else {
       		$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE Status='0'";
       		$ado->Execute($sql);         	
          }
     break;
     case "m_add_rule":
     	$objEditItems = new clsBanRuleList();
     	$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
     	//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
     	$objEditItems->AddRule($_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
     				   $_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
     				   (int)$_POST["rule_status"], $_POST['rule_error']);
     break;
     case "m_edit_rule":    	
     	$objEditItems = new clsBanRuleList();
     	$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
     	//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
     	$objEditItems->EditRule($_POST["rule_id"],$_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
     				   $_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
     				   (int)$_POST["rule_status"], $_POST['rule_error']);
     break;    
     case "m_rule_move_up":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Increment("Priority");
          }
        }	      
     break;
     case "m_rule_move_down":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Decrement("Priority");
          }
        }	      
     break;
     
 	case "m_rule_delete":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Delete();
          }
        }		
     break;    
     case "m_ban_user":
       if($ro_perm) break;
       if($_POST["UserEditStatus"]==1)
       {
         $UserId = $_POST["user_id"];
         $u = $objUsers->GetItem($UserId);
         if(is_object($u))
         {
         	if((int)$_POST["ban_login"])
         	{
         		if(strlen($_POST["user_login"]))
         			$objBanList->AddRule(6,0,"Login",3,$_POST["user_login"],0,1);
         	}
         	if((int)$_POST["ban_email"])
         	{
         		if(strlen($_POST["user_email"]))
         			$objBanList->AddRule(6,0,"Email",3,$_POST["user_email"],0,1);
         	}
         	if((int)$_POST["ban_ip"])
         	{
         		if(strlen($_POST["user_ip"]))
         			$objBanList->AddRule(6,0,"ip",3,$_POST["user_ip"],0,1);
         	}       
         	$u->Deny(); 	
         }
       }
     	break;  
     	
     }
 
 /* image upload management */
 if( isset($_POST['img']) && $_POST['img'] == 1 )
 {
     foreach($_FILES as $img => $FILE)
     {
         $name = $_POST["img_Name_$img"];
         $alt = $_POST["img_Alt_$img"];
         $url = $_POST["img_Url_$img"];
         $res_id = $_POST["img_Res_$img"];
         $relvalue = $_POST["img_Rel_$img"];
         $thumb = (int)$_POST["img_Thumb_$img"];
         $dest = AddSlash($_POST["img_DestDir_$img"]);
         if($_POST["img_Del_$img"]=="Delete")
         {
             $img = $objImageList->GetImageByResource($res_id,$relvalue);
             $img->Delete();
             unset($img);
             $objImageList->Clear();
         }
         else
         {
           if($FILE["size"]>0)
           {
             /* an image was uploaded */
             $objImageList->HandleImageUpload($FILE,$res_id,$relvalue,$dest, $name,$alt,$thumb);
           }
           else
           {    /* remote images handled here */
             if(strlen($url)>0)
             {                   
               if($relvalue>0)
               {                                            
                $img = $objImageList->GetImageByResource($res_id,$relvalue);
                $img->Set("Name",$name);
                $img->Set("AltName", $alt);
                $img->Set("IsThumbnail",$thumb);
                $img->Set("Url",$url);
                $img->Update();
               }
               else
               {
                $relvalue = $objImageList->GetNextRelateValue($res_id);
                $objImageList->NewRemoteImage($url,$res_id,$relvalue, $name, $alt, $thumb);
               }
             }
           }
         }
     }
 }
 
 // ALL Saving Stuff From Temp Tables Heppens Here
 
 //echo "==== BEGIN ==== <br>";
 $has_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
 //echo "PortalUserID: [".$objSession->Get("PortalUserId")."]<br>";
 //echo "PermSet: [".$has_perm."]<br>";
 
 if( !$has_perm )
 {
 
 	/* category Edit */
 	if( GetVar('CatEditStatus') == 1 )
 	{ 
 	    $adodbConnection = GetADODBConnection();
 	
 	//    $sql = "SELECT * FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=0";    
 	    $sql = "SELECT * FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=-1";
 	    $rs = $adodbConnection->Execute($sql);
 	    while ($rs && !$rs->EOF) 
 	    {
 	        if($rs->fields["ParentId"]>0)
 	            RunUp($rs->fields["ParentId"],"Increment_Count");
 	        $rs->MoveNext();
 	    }
 	    
 	    $objCatList->CopyFromEditTable("CategoryId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objCatList->Clear();
 
 	    if($_REQUEST['CategoryId'] > 0) // not root category is updated
 	    {
 	    	$objImages = new clsImageList();
 	    	$objImages->CopyFromEditTable("ImageId");
 		}
 	}
 	
 	if( GetVar('CatEditStatus') == 2 )
 	{ 
 	    $objCatList->PurgeEditTable("CategoryId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	  	if($_REQUEST['CategoryId'] > 0) // not root category is updated
 	    {
 	    	$objImages = new clsImageList();
 	    	$objImages->CopyFromEditTable("ImageId");
 	    	//$objImages->PurgeEditTable("ImageId");
 	    }
 	    $objCatList->Clear();
 	}
 	
 	/* User Edit */
 	if( GetVar('UserEditStatus') == 1 )
 	{
 	    $objUsers->CopyFromEditTable("PortalUserId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objGroups->Clear();
 	    $objImages = new clsImageList();
 	    $objImages->CopyFromEditTable("ImageId");    
 	}
 	if( GetVar('UserEditStatus') == 2 )
 	{
 	    $objGroups->PurgeEditTable("PortalUserId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	
 	/* Group Edit */
 	if( GetVar('GroupEditStatus') == 1 )
 	{
 	    $objGroups->CopyFromEditTable("GroupId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	if( GetVar('GroupEditStatus') == 2 )
 	{
 	    $objGroups->PurgeEditTable("GroupId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	
 	/* Theme Edit */
 	if( GetVar('ThemeEditStatus') == 1 )
 	{    
 	    $objThemes->CopyFromEditTable();
 	    $objThemes->Clear();
 	}
 	
 	if( GetVar('ThemeEditStatus') == 2 )
 	{
 	    $objThemes->PurgeEditTable();
 	    $objThemes->Clear();
 	}
 	
 	/* Language Edit */
 	if( GetVar('LangEditStatus') == 1 )
 	{
 	    $Messages = new clsEmailMessageList();
 	    $Messages->CopyFromEditTable();
 	    $Messages->Clear();
 	    $objLanguages->CopyFromEditTable();
 	    $objLanguages->Clear();
 	
 	    $Phrases = new clsPhraseList();
 	    $Phrases->CopyFromEditTable();
 	    $Phrases->Clear();
 	    $Phrases->PurgeEditTable();
 	}          
 	if( GetVar('LangEditStatus') == 2 )
 	{
 	    $objLanguages->PurgeEditTable();
 	    $objLanguages->Clear();
 	    $Phrases = new clsPhraseList();
 	    $Phrases->PurgeEditTable();    
 	    $Messages = new clsEmailMessageList();
 	    $Messages->PurgeEditTable();
 	}
 	
 	if( GetVar('MissingLangEditStatus') == 1 )
 	{
 	   $objPhraseList = new clsPhraseList();
 	   $objPhraseList->SourceTable = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 	   
 	   $objEditList = new clsPhraseList();
 	   $objEditList->SourceTable = $objSession->GetEditTable("Phrase");
 	
 	   $ado = GetADODBConnection();
 	   $rs = $ado->Execute("SELECT MIN(PhraseId) as MinValue FROM ".$objEditList->SourceTable);
 	   $NewId = $rs->fields["MinValue"]-1;
 	   
 	   $objPhraseList->Query_Item("SELECT * FROM ".$objPhraseList->SourceTable);
 	   foreach($objPhraseList->Items as $p)
 	   {
 	       if(strlen($p->Get("Translation"))>0)
 	       {       
 	         $p->tablename = $objEditList->SourceTable;
 	         $p->Dirty();
 	         $p->UnsetIDField();
 	         $p->Set("PhraseId",$NewId);
 	         $NewId--;
 	         $p->Create();
 	       }
 	   }
 	   $ado->Execute("DROP TABLE IF EXISTS ".$objPhraseList->SourceTable);
 	}
 	
 	if( GetVar('MissingLangEditStatus') == 2 )
 	{
 	  $table = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 	  $ado = GetADODBConnection();
 	  $ado->Execute("DROP TABLE IF EXISTS ".$table);
 	}
 	
 	/* Ban Rule Edit */
 	if( GetVar('RuleEditStatus') == 1 )
 	{    
 	    $objBanList->CopyFromEditTable("RuleId");
 	    $objBanList->Clear();
 	}
 	if( GetVar('RuleEditStatus') == 2 )
 	{
 	    $objBanList->PurgeEditTable("RuleId");
 	    $objBanList->Clear();
 	}
 }
 elseif( defined('DEBUG_ACTIONS') )
 {
 	if( isset($_REQUEST['Action']) && $_REQUEST['Action'] )
 		echo "<b>USER HAS RO-ACCESS</b> on action [<b>".$_REQUEST['Action']."</b>]<br>";
 }
 
 //echo "==== END ==== <br>";
 
 ?>

Property changes on: trunk/kernel/action.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.30
\ No newline at end of property
+1.31
\ No newline at end of property
Index: trunk/kernel/include/parseditem.php
===================================================================
--- trunk/kernel/include/parseditem.php	(revision 347)
+++ trunk/kernel/include/parseditem.php	(revision 348)
@@ -1,2927 +1,2929 @@
 <?php
 global $ItemTypePrefixes;
 
 $ItemTypePrefixes = array();
 $ItemTagFiles = array();
 
 function RegisterPrefix($class,$prefix,$file)
 {
  	global $ItemTypePrefixes, $ItemTagFiles;
     	
  	$ItemTypePrefixes[$class] = $prefix;
  	$ItemTagFiles[$prefix] = $file;
 }
 
 class clsParsedItem extends clsItemDB
 {
     var $TagPrefix;
     var $Parser;
     var $AdminParser;    
 
     function clsParsedItem($id=NULL)
     {
         global $TemplateRoot;
 
         $this->clsItemDB();
         $this->Parser = new clsTemplateList($TemplateRoot);
         $this->AdminParser = new clsAdminTemplateList();
     }
         
 /*    function ParseObject($element)
     {
         $extra_attribs = ExtraAttributes($element->attributes);
         if(strtolower($element->name)==$this->TagPrefix)
         {
             $field = strtolower($element->attributes["_field"]);
             $tag = $this->TagPrefix."_".$field;
             $ret = $this->parsetag($tag);
         }
         return $ret;
     }
 */
 	function ParseTimeStamp($d,$attribs=array())
 	{
        if( isset($attribs["_tz"]) )
        {
             $d = GetLocalTime($d,$objSession->Get("tz"));
        }
        $part = isset($attribs["_part"]) ? strtolower($attribs["_part"]) : '';
        if(strlen($part))
        {
           $ret = ExtractDatePart($part,$d);
        }
        else
        {
          if($d<=0)
          {
             $ret = "";
          }
          else
             $ret = LangDate($d);
        }		
        return $ret;
 	}		
 	
 	function ParseObject($element)
     {
         global $objConfig, $objCatList, $var_list_update, $var_list, $n_var_list_update, $m_var_list_update;
 
         $extra_attribs = ExtraAttributes($element->attributes);
         $ret = "";
         
         if ($this->TagPrefix == "email" && strtolower($element->name) == "touser") {
         	$this->TagPrefix = "touser";        	
         }
         
         if(strtolower($element->name)==$this->TagPrefix)
         {
             $field = strtolower($element->attributes["_field"]);
             switch($field)
             {     
             case "id":
             	$ret = $this->Get($this->id_field);
             break;	       	
             case "resourceid":
               if(!$this->NoResourceId)
                 $ret = $this->Get("ResourceId");
             break;    
             case "category":
                 $c = $objCatList->GetItem($this->Get("CategoryId"));
                 if(is_object($c))
                 {
                    $ret = $c->parsetag($element->attributes["_cattag"]);
                 }
             break;            
             case "priority":
                 if($this->Get("Priority")!=0)
                 {               
                     $ret = (int)$this->Get("Priority");
                 }
                 else
                     $ret = "";
             break;            
             case "link":
             	if(method_exists($this,"ItemURL"))
             	{     
             	  $ret = $this->ItemURL($element->attributes["_template"],FALSE,"");            	  	
             	}
             break;	
             case "cat_link":
             	if(method_exists($this,"ItemURL"))
             	{
             	  $ret = $this->ItemURL($element->attributes["_template"],TRUE,"");            	  	
             	}            
             break;
             case "fullpath":                                  
                 $ret = $this->Get("CachedNavbar");
                 if(!strlen($ret))
                 {
                     if(is_numeric($this->Get("CategoryId")))
                     {
                        $c = $objCatList->GetItem($this->Get("CategoryId"));
                        if(is_object($c))
                          $ret = $c->Get("CachedNavbar");
                     }
                     else
                     {
                     	if(method_exists($this,"GetPrimaryCategory"))
                     	{
                           $cat = $this->GetPrimaryCategory();
                           $c = $objCatList->GetItem($cat);
                           if(is_object($c))
                             $ret = $c->Get("CachedNavbar");
                     	}
                     }
                 }
                // $ret = $this->HighlightText($ret);
             break;    
                         
             case "relevance":            
 	            $style = $element->attributes["_displaymode"];	            
 	            if(!strlen($style))
 	              $style = "numerical";
 	            switch ($style)
 	            {                
 	            	case "numerical":	            	
 	                	$ret = (100 * LangNumber($this->Get("Relevance"),1))."%";
 	                	break;	                	
 	                case "bar":                                          	 	                
 	                	$OffColor = $element->attributes["_offbackgroundcolor"];
 	                	$OnColor = $element->attributes["_onbackgroundcolor"];
 	                	$percentsOff = (int)(100 - (100 * $this->Get("Relevance")));	                	if ($percentsOff)
 	                	{
 		                	$percentsOn = 100 - $percentsOff;
 		                	$ret = "<td width=\"$percentsOn%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td><td width=\"$percentsOff%\" bgcolor=\"$OffColor\"><img src=\"img/s.gif\"></td>";        	
 	                	}
 	                	else
 	                		$ret = "<td width=\"100%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td>";      	                	
 	                break;	                    
 	                case "graphical":	                	
 	                	$OnImage = $element->attributes["_onimage"];
 	                	if (!strlen($OnImage))
 	                		break;
 	                	// Get image extension
 	                	$image_data = explode(".", $OnImage);
 	                	$image_ext = $image_data[count($image_data)-1];
 	                	unset($image_data[count($image_data)-1]);
 	                	$rel = (10 * LangNumber($this->Get("Relevance"),1));
 	                	$OnImage1 = join(".", $image_data);
 	                	
 	                	if ($rel)
 	                		$img_src = $OnImage1."_".$rel.".".$image_ext;            						
 	                	else
 	                		$img_src = $OnImage;
 	                		
 	                	$ret = "<img src=\"$img_src\" border=\"0\" alt=\"".(10*$rel)."\">";
 	                	break;
 	            }          
             
             break;
               	
             case "rating":
                 $style = $element->GetAttributeByName("_displaymode");
 	            if(!strlen($style))
 	              $style = "numerical";                
                 switch($style)
                 {                
                 case "numerical":
                     $ret = LangNumber($this->Get("CachedRating"),1);
                     break;
                 case "text":
                     $ret = RatingText($this->Get("CachedRating"));
                     break;
                 case "graphical":
                     $OnImage = $element->attributes["_onimage"];
                     $OffImage = $element->attributes["_offimage"];
                     $images = RatingTickImage($this->Get("CachedRating"),$OnImage,$OffImage);
                     
                     for($i=1;$i<=count($images);$i++)
                     {
                       $url = $images[$i];
                       if(strlen($url))
                       {                                                                  
                           $ret .= "<IMG src=\"$url\" $extra_attribs >";
                           $ret .= $element->attributes["_separator"];
                       }
                     }
                     break;
                 }
             break;
             case "reviews":
                 $today = FALSE;
                 
                 if(method_exists($this,"ReviewCount"))
                 {                
                 	if($element->GetAttributeByName("_today"))
                       $today = TRUE;                      
                   $ret = $this->ReviewCount($today);
                 }
                 else
                   $ret = "";
                   
             break;
             case "votes":
             	$ret = (int)$this->Get("CachedVotesQty");
             break;	
 
             case "favorite":
              if(method_exists($this,"IsFavorite"))
              {            
             	if($this->IsFavorite())
             	{
                   $ret = $element->attributes["_label"];
                   if(!strlen($ret))
                     $ret = "lu_favorite";
                   $ret = language($ret);            	  	
             	}
             	else
             	  $ret = "";
              }
             break;	
             case "new":
               if(method_exists($this,"IsNewItem"))
               {            
                 if($this->IsNewItem())
                 {
                   $ret = $element->GetAttributeByName('_label');
                   if(!strlen($ret))
                     $ret = "lu_new";
                   $ret = language($ret);
                 }
                 else
                  $ret = "";
               }
             break;
             case "pop":
              if(method_exists($this,"IsPopItem"))
              {            
                 if($this->IsPopItem())
                 {
                   $ret = $element->attributes["_label"];
                   if(!strlen($ret))
                     $ret = "lu_pop";
                   $ret = language($ret);
                 }
                 else
                  $ret = "";
              }
             break;
             case "hot":
             	if(method_exists($this,"IsHotItem"))
             	{
                   if($this->IsHotItem())
                   {
                     $ret = $element->GetAttributeByName("_label");
                     if(!strlen($ret))
                       $ret = "lu_hot";
                     $ret = language($ret);
                   }
                   else
                     $ret = "";
             	}
             break;
             case "pick":
                 if($this->Get("EditorsPick")==1)
                 {
                   $ret = $element->GetAttributeByName('_label');
                   if(!strlen($ret))
                     $ret = "lu_pick";
                   $ret = language($ret);
                 }
                 else
                    $ret = "";
             break;                            	
             case "admin_icon":
               if(method_exists($this,"StatusIcon"))
               {
                 if($element->GetAttributeByName("fulltag"))
                 {
                     $ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
                 }
                 else
                     $ret = $this->StatusIcon();
               }
             break;            
             case "custom":
             	if(method_exists($this,"GetCustomFieldValue"))
             	{
                   $field =  $element->attributes["_customfield"];
                   $default = $element->attributes["_default"];
                   if (strlen($field))
                   	$ret = $this->GetCustomFieldValue($field,$default);
             	}
             break;            
             case "image":
                $default = $element->attributes["_primary"];
                $name = $element->attributes["_name"];
                
                if(strlen($name))
                {
                    $img = $this->GetImageByName($name);
                }
                else
                {
                    if($default)
                      	$img = $this->GetDefaultImage();
                }
                
                if(is_object($img))
                {
                		
                    if(strlen($element->attributes["_imagetemplate"]))
                    {
                      $ret = $img->ParseTemplate($element->attributes["_imagetemplate"]);
                      break;
                    }
                    else
                    {
                      if($element->attributes["_thumbnail"])
                      {                       	
                        $url = $img->parsetag("thumb_url");
                      }
                      else
                      {
                      	
                      	if(!$element->attributes["_nothumbnail"])
                      	{
                        		$url = $img->parsetag("image_url");                       		
                      	}
                      	else
                      	{   
                      		$url = $img->FullURL(TRUE,"");
                      	}
                    	 }
                    }
                }
                else
                {
                   $url = $element->attributes["_defaulturl"];
                 
                }
 
                if($element->attributes["_imagetag"])
                {
                    if(strlen($url))
                    {
                      $ret = "<IMG src=\"$url\" $extra_attribs >";
                    }
                    else
                        $ret = "";
                }
                else
                    $ret = $url;
             break;
             default:
             	$ret = "Undefined:".$element->name;
             break;
             }
             
         }
         else if ($this->TagPrefix == 'email'){
         	$ret = "Undefined:".$element->name;
         }
         return $ret;
     }
     
     function ParseString($name)
     {
       $el = new clsHtmlTag();
       $el->Clear();
       $el->prefix = "inp";
       $el->name = $name;
 
       $numargs = func_num_args();
       $arg_list = func_get_args();
       for ($i = 1; $i < $numargs; $i++)
       {
          $attr = $arg_list[$i];
          $parts = explode("=",$attr,2);
          $name = $parts[0];
          $val = $parts[1];
          $el->attributes[$name] = $val;
       }
       return $this->ParseObject($el);
     }
 
     /* pass attributes as strings
       ie: ParseStringEcho('tagname','_field="something" _data="somethingelse"');
     */
     function ParseStringEcho($name)
     {
       $el = new clsHtmlTag();
       $el->Clear();
       $el->prefix = "inp";
       $el->name = $name;
 
       $numargs = func_num_args();
       $arg_list = func_get_args();
       for ($i = 1; $i < $numargs; $i++)
       {
          $attr = $arg_list[$i];
          $parts = explode("=",$attr,2);
          $name = $parts[0];
          $val = $parts[1];
          $el->attributes[$name] = $val;
       }
       echo $this->ParseObject($el);
     }
 
     function ParseElement($raw, $inner_html ="")
     {
         $tag = new clsHtmlTag($raw);
         $tag->inner_html = $inner_html;
 
         if($tag->parsed)
         { 
           if($tag->name=="include" || $tag->name=="perm_include" || $tag->name=="lang_include")
           {
               $output = $this->Parser->IncludeTemplate($tag);
           }
           else
           { 
             $output = $this->ParseObject($tag); 
 			//echo $output."<br>";
             if(substr($output,0,9)=="Undefined")
             { 
                $output = $tag->Execute();
   //             if(substr($output,0,8)="{Unknown")
   //                 $output = $raw;
             }            return $output;
           }
         }
         else
             return "";
     }
 
     function AdminParseTemplate($file)
     {
       $html = "";
       $t = $this->AdminParser->GetTemplate($file);
 
       if(is_object($t))
       {
           array_push($this->AdminParser->stack,$file);
           $html = $t->source;
           $next_tag = strpos($html,"<inp:");
           while($next_tag)
           {
               $end_tag = strpos($html,"/>",$next_tag);
               $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2);
               $pre = substr($html,0,$next_tag);
               $post = substr($html,$end_tag+2);
               $inner = $this->ParseElement($tagtext);
               $html = $pre.$inner.$post;
               $next_tag = strpos($html,"<inp:");
           }
           array_pop($this->AdminParser->stack);
       }
       return $html;
     }
 
     function ParseTemplateText($text)
     {
       $html = $text;
       $search = "<inp:".$this->TagPrefix;
       $next_tag = strpos($html,"<inp:");
       //$next_tag = strpos($html,$search);
       
 
       while($next_tag)
       { 
       	  $closer = strpos(strtolower($html),">",$next_tag);
           $end_tag = strpos($html,"/>",$next_tag);
           if($end_tag < $closer || $closer == 0)
           {
             $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2);
             $pre = substr($html,0,$next_tag);
             $post = substr($html,$end_tag+2);
             $inner = $this->ParseElement($tagtext);
             $html = $pre.$inner.$post;
           }
           else
           {
 
           	$OldTagStyle = "</inp>";
           	
           	## Try to find end of TagName
           	$TagNameEnd = strpos($html, " ", $next_tag);
           	
           	## Support Old version
 //          	$closer = strpos(strtolower($html),"</inp>",$next_tag);          
           	if ($TagNameEnd)
           	{   			
           		$Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag));
           		$TagName = explode(":", $Tag);          		
           		if (strlen($TagName[1]))
           			$CloserTag = "</inp:".$TagName[1].">";
           	}          	
           	else
           	{
           		$CloserTag = $OldTagStyle;
           	}          	
             
     	  	$closer = strpos(strtolower($html), $CloserTag, $next_tag);
     	  	
     	  	## Try to find old tag closer
     	  	if (!$closer && ($CloserTag != $OldTagStyle))
     	  	{
 				$CloserTag = $OldTagStyle;
     	  		$closer = strpos(strtolower($html), $CloserTag, $next_tag);	
     	  	}
     	  		
             $end_tag = strpos($html,">",$next_tag);
             $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+1);
             $pre = substr($html,0,$next_tag);
             $inner = substr($html,$end_tag+1,$closer-($end_tag+1));
             $post = substr($html,$end_tag+1+strlen($inner) + strlen($CloserTag));
             //echo "PRE:". htmlentities($pre,ENT_NOQUOTES);
             //echo "INNER:". htmlentities($inner,ENT_NOQUOTES);
             //echo "POST:". htmlentities($post,ENT_NOQUOTES);
 
             $parsed = $this->ParseElement($tagtext);
             if(strlen($parsed))
             {
                 $html = $pre.$this->ParseTemplateText($inner).$post;
             }
             else
                 $html = $pre.$post;
           }
           $next_tag = strpos($html,$search);
       }
       return $html;
     }
 
     function ParseTemplate($tname)
     {
       global $objTemplate, $LogLevel,$ptime,$timestart;
 
       LogEntry("Parsing $tname\n");
       $LogLevel++;
       $html = "";
       $t = $objTemplate->GetTemplate($tname);
       //$t = $this->Parser->GetTemplate($tname);
       if(is_object($t))
       {
           array_push($this->Parser->stack,$tname);
           $html = $t->source;
 
           $html = $this->ParseTemplateText($html);
           array_pop($this->Parser->stack);
       }
       $LogLevel--;
       LogEntry("Finished Parsing $tname\n");
       $ptime = round(getmicrotime() - $timestart,6);
       $xf = 867530; //Download ID
       if($xf != 0)
       {
         $x2 = substr($ptime,-6);
         $ptime .= $xf ^ $x2; //(1/1000);
       }
       return $html;
     }
     
     function SendUserEventMail($EventName,$ToUserId,$LangId=NULL,$RecptName=NULL)
     {
       global $objMessageList,$FrontEnd;
 
       $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
 
       if(is_object($Event))
       {
           if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd))
           {
               $Event->Item = $this;   
               if(is_numeric($ToUserId))
               {           
               	return $Event->SendToUser($ToUserId);
               }
               else
                 return $Event->SendToAddress($ToUserId,$RecptName);
           }
       }
     }
 
     function SendAdminEventMail($EventName,$LangId=NULL)
     {
       global $objMessageList,$FrontEnd;
 
       //echo "Firing Admin Event $EventName <br>\n";
       $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
       if(is_object($Event))
       {
           if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd))
           {
               $Event->Item = $this;
               //echo "Admin Event $EventName Enabled <br>\n";
               return $Event->SendAdmin($ToUserId);
           }
       }
     }
 
     function parse_template($t)
     {
     }
     
 }
 
 class clsItemCollection
 {
     var $Items;
     var $CurrentItem;
     var $adodbConnection;
     var $classname;
     var $SourceTable;
     var $LiveTable;
     var $QueryItemCount;
     var $AdminSearchFields = array();
     var $SortField;
     var $debuglevel;
     var $id_field = null; // id field for list item
     var $BasePermission;
     var $Dummy = null;
     
     function SetTable($action, $table_name = null) // new by Alex
     {
     	// $action = {'live', 'restore','edit'}
     	switch($action)
     	{
     		case 'live': 
     			$this->LiveTable = $table_name;
     			$this->SourceTable = $this->LiveTable;
     			break;
     		case 'restore': 
     			$this->SourceTable = $this->LiveTable; 
     			break;
     		case 'edit':
     			global $objSession;
     			$this->SourceTable = $objSession->GetEditTable($this->LiveTable);
     			break;
     	}
     }
     
     function &GetDummy() // new by Alex
 	{
 		if( !isset($this->Dummy) )
 			$this->Dummy =& new $this->classname();
 		$this->Dummy->tablename = $this->SourceTable;	
 		return $this->Dummy;
 	}
     
     function clsItemCollection()
     {
 
       $this->adodbConnection = GetADODBConnection();
 
       $this->Clear();
       $this->BasePermission="";
     }   
 
 	function GetIDField() // new by Alex
 	{
 		// returns id field for list item
 		if( !isset($this->id_field) )
 		{
 			$dummy =& $this->GetDummy();
 			$this->id_field = $dummy->IdField();
 		}
 		return $this->id_field;
 	}
 
     function &GetNewItemClass()
     {
     	return new $this->classname();
     }
      
     function Clear()
     {
       unset($this->Items);
       $this->Items = array();
       $this->CurrentItem=0;      
     }
 
     function &SetCurrentItem($id)
     {
         $this->CurrentItem=$id;
         return $this->GetItem($id);
     }
 
     function &GetCurrentItem()
     {
         if($this->CurrentItem>0)
         {
           return $this->GetItem($this->CurrentItem);
         }
         else
             return FALSE;
     }
 
     function NumItems()
     {
         if(is_array($this->Items))
         {
 //        	echo "TEST COUNT: ".count($this->Items)."<BR>";
             return count($this->Items);
         }
         else
             return 0;
     }
 	
 	function ItemLike($index, $string)
 	{
 		// check if any of the item field
 		// even partially matches $string
 		$found = false;
 		$string = strtolower($string);
 		$item_data = $this->Items[$index]->GetData();
 		foreach($item_data as $field => $value)
 			if( in_array($field, $this->AdminSearchFields) )
 				if( strpos(strtolower($value), $string) !== false)
 				{
 					$found = true;
 					break;
 				}
 		return $found;
 	}
 	
 	function DeleteItem($index) // by Alex
 	{
 		// deletes item with specific index from list
 		$i = $index; $item_count = $this->NumItems();
 		while($i < $item_count - 1)
 		{
 			$this->Items[$i] = $this->Items[$i + 1];
 			$i++;	
 		}
 		unset($this->Items[$i]);
 	}
 	
 	function ShowItems()
 	{
 		$i = 0; $item_count = $this->NumItems();
 		while($i < $item_count)
 		{
 			echo "Item No <b>$i</b>:<br>";
 			$this->Items[$i]->PrintVars();
 			$i++;	
 		}
 	}
 	
     function SwapItems($Index,$Index2)
     {
         $temp = $this->Items[$Index]->GetData();
         $this->Items[$Index]->SetData($this->Items[$Index2]->GetData());
         $this->Items[$Index2]->SetData($temp);
     
     }
     
     function CopyResource($OldId,$NewId)
     {
     	$this->Clear();
     	
     	$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$OldId";
     	$this->Query_Item($sql);
 //    	echo $sql."<br>\n";
     	if($this->NumItems()>0)
     	{
     		foreach($this->Items as $item)
     		{
     			$item->UnsetIdField();
     			$item->Set("ResourceId",$NewId);
     			$item->Create();
     		}
     	}
     }
     function ItemsOnClipboard()
     {
     	global $objSession;
         $clip = $objSession->GetPersistantVariable("ClipBoard");
         $count = 0;
         $table = $this->SourceTable;
         $prefix = GetTablePrefix();
         
         
         if(substr($table,0,strlen($prefix))==$prefix)
     		$table = substr($table,strlen($prefix));
 
     		
         if(strlen($clip))
         {
             $clipboard = ParseClipboard($clip);
             if($clipboard["table"] == $table)
             {
                 $count = count(explode(",",$clipboard["ids"]));
             }
             else
                 $count = 0;
         }
         else
             $count = 0;
 
         return $count;
     }
     
     function CopyToClipboard($command,$idfield, $idlist)
     {
         global $objSession,$objCatList;
 
         if(is_array($idlist))
         {
           $list = implode(",",$idlist);
         }
         else
              $list  = $idlist;
         $clip = $command."-".$objCatList->CurrentCategoryID().".".$this->SourceTable.".$idfield=".$list;
         
         $objSession->SetVariable("ClipBoard",$clip);
     }
         
     function SortItems($asc=TRUE)
     {
         $done = FALSE;
         
         $field = $this->SortField;
         $ItemCount = $this->NumItems();
         while(!$done)
         {
             $done=TRUE;
             for($i=1;$i<$this->NumItems();$i++)
             {
                   $doswap = FALSE;
                   if($asc)
                   { 
                     $val1 = $this->Items[$i-1]->Get($field);                    
                     $val2 = $this->Items[$i]->Get($field);
                     $doswap = ($val1 > $val2); 
                   }
                   else
                   {
                     $val1 = $this->Items[$i-1]->Get($field);
                     $val2 = $this->Items[$i]->Get($field);                                   
                     $doswap = ($val1 < $val2); 
                   }
                   if($doswap)
                   {
                      $this->SwapItems($i-1,$i);
                     $done = FALSE;
                   }
 
             }
         }
     }
 
     function &GetItem($ID,$LoadFromDB=TRUE)
     {
         $found=FALSE;
 
         if(is_array($this->Items) && count($this->Items) )
         {
           for($x=0;$x<count($this->Items);$x++)
           {
             $i =& $this->GetItemRefByIndex($x);
             if($i->UniqueID()==$ID)
             {                
                 $found=TRUE;
                 break;
             }
           }
         }
 		
         if(!$found)
         {
             if($LoadFromDB)
             {            
               $n = NULL;
               $n = new $this->classname();
               $n->tablename = $this->SourceTable;
               $n->LoadFromDatabase($ID);
               $index = array_push($this->Items, $n);
               $i =& $this->Items[count($this->Items)-1];
             }
             else
                 $i = FALSE;
         }
         return $i;
     }
 
     function GetItemByIndex($index)
     {
         return $this->Items[$index];
     }
 
     function &GetItemRefByIndex($index)
     {
         return $this->Items[$index];
     }
 
     function &GetItemByField($Field,$Value,$LoadFromDB=TRUE)
     {
         $found=FALSE;
 
         if(is_array($this->Items))
         {
           foreach($this->Items as $i)
           {
             if($i->Get($Field)==$Value)
             {
               $found = TRUE;
               break;
             }
           }
         }
         if(!$found && $LoadFromDB==TRUE)
         {
             $sql = "SELECT * FROM ".$this->SourceTable." WHERE $Field = '$Value'";
             //echo $sql;
             $res = $this->adodbConnection->Execute($sql);
 
             if($res && !$res->EOF)
             {
                 $i = $this->AddItemFromArray($res->fields);
                 $i->tablename = $this->SourceTable;
                 $i->Clean();
             }
             else
                 $i = FALSE;
         }
 
         return $i;
     }
 
     function GetPage($Page, $ItemsPerPage)
     {
         $result = array_slice($this->Items, ($Page * $ItemsPerPage) - $ItemsPerPage, $ItemsPerPage);
         return $result;
     }
 
     function GetNumPages($ItemsPerPage)
     { 
     	if( isset($_GET['reset']) && $_GET['reset'] == 1) $this->Page = 1;
         return GetPageCount($ItemsPerPage,$this->QueryItemCount);
     }
 
     function &AddItemFromArray($data, $clean=FALSE)
     {    
         $class = new $this->classname;
         $class->SetFromArray($data);
         $class->tablename = $this->SourceTable;
         if($clean==TRUE)
             $class->Clean();
 		//array_push($this->Items,$class);
         $this->Items[] =& $class;
         return $class;
     }
 
     function Query_Item($sql, $offset=-1,$rows=-1)
     { 
         global $Errors;        
 
         $dummy =& $this->GetDummy();
        	if( !$dummy->TableExists() )
        	{
        		if($this->debuglevel) echo "ERROR: table <b>".$dummy->tablename."</b> missing.<br>";
        		$this->Clear();
        	 	return false;
        	}
        	
         if($rows>-1 && $offset>-1)
         {
 	       	//echo "<b>Executing SelectLimit</b> $sql <b>Offset:</b> $offset,$rows<br>\n";
             $result = $this->adodbConnection->SelectLimit($sql, $rows,$offset);
         }
         else {
             $result = $this->adodbConnection->Execute($sql);
         }
     	
         if ($result === false)
         {
             $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item");
             echo '<br><br>'.$sql.'<br><br>';
             echo "Error: ".$this->adodbConnection->ErrorMsg()."<br>";
             return false;
         }
        
         $this->Clear();
       
         if($this->debuglevel > 0)
         {
         	 echo "This SQL: $sql<br>";
         	 if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) )
         	 {
         	 	echo '<pre>'.print_r($result->GetRows(), true).'</pre>';
         	 	$result->MoveFirst();
         	 }
        	}
         LogEntry("SQL Loop Start\n");
         $count = 0;
 
           while ($result && !$result->EOF)
           {
             $count++;
             $data = $result->fields;
             $this->AddItemFromArray($data,TRUE);    
             if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
                 adodb_movenext($result);
             else
               $result->MoveNext();
           }
 
         LogEntry("SQL Loop End ($count iterations)\n");
         return $this->Items;
     }
 
     function GetOrderClause($FieldVar,$OrderVar,$DefaultField,$DefaultVar,$Priority=TRUE,$UseTableName=FALSE)
     {
     	global $objConfig, $objSession;
 
        if($UseTableName)
        {
        	  $TableName = $this->SourceTable.".";
        }
        else
          $TableName = "";	
 
        $PriorityClause = $TableName."EditorsPick DESC, ".$TableName."Priority DESC";
        
        if(strlen(trim($FieldVar))>0)
        {
          if(is_object($objSession))
          {
            if(strlen($objSession->GetPersistantVariable($FieldVar))>0)  
            {  		
           		$OrderBy = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
             		       $objSession->GetPersistantVariable($OrderVar));
             	$FieldUsed = $objSession->GetPersistantVariable($FieldVar);       	  	       	    
            }
          }       
          $OrderBy = trim($OrderBy);
          if (strlen(trim($OrderBy))==0) 
          {
            if(!$UseTableName)
            {
              $OrderBy = trim($DefaultField." ".$DefaultVar);
            }
            else
            {
            	 if(strlen(trim($DefaultField))>0)
            	 {
            	   $OrderBy = $this->SourceTable.".".$DefaultField.".".$DefaultVar;
            	 }
              $FieldUsed=$DefaultField;  	
            }
          }
        }    	
        if(($FieldUsed != "Priority" || strlen($OrderBy)==0) && $Priority==TRUE)
        {
        	  if(strlen($OrderBy)==0)
        	  {
        	    $OrderBy = $PriorityClause;
        	  }
        	  else 
        	    $OrderBy = $PriorityClause.", ".$OrderBy;
        }
 	   return $OrderBy;    	
     }
 
     function GetResourceIDList()
     {
         $ret = array();
         foreach($this->Items as $i)
             array_push($ret,$i->Get("ResourceId"));
         return $ret;
     }
 
     function GetFieldList($field)
     {
         $ret = array();
         foreach($this->Items as $i)
             array_push($ret,$i->Get($field));
         return $ret;
     }
 
     function SetCommonField($FieldName,$FieldValue)
     {
       for($i=0;$i<$this->NumItems();$i++)
       {
         $this->Items[$i]->Set($FieldName,$fieldValue);
         $this->Items[$i]->Update();
       }
     }
 
     function ClearCategoryItems($CatId,$CatTable = "CategoryItems")
     {
     	$CatTable = AddTablePrefix($CatTable);
         $sql = "SELECT * FROM ".$this->SourceTable." INNER JOIN $CatTable ".
                " ON (".$this->SourceTable.".ResourceId=$CatTable.ItemResourceId) WHERE CategoryId=$CatId";
         $this->Clear();
         $this->Query_Item($sql);
         if($this->NumItems()>0)
         {        
           foreach($this->Items as $i)
           {          	
             $i->DeleteCategoryItems($CatId,$CatTable);
           }
         }
     }
 
     function CopyToEditTable($idfield = null, $idlist = 0)
     {
         global $objSession;
 		
 		if($idfield == null) $idfield = $this->GetIDField();
         $edit_table = $objSession->GetEditTable($this->SourceTable);
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
         if(is_array($idlist))
         {
           $list = implode(",",$idlist);
         }
         else
              $list  = $idlist;
         $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
         $insert = "CREATE TABLE ".$edit_table." ".$query;
         if($objSession->HasSystemPermission("DEBUG.LIST"))
             echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
         $this->adodbConnection->Execute($insert);
     }
 
     function CreateEmptyEditTable($idfield = null)
     {
         global $objSession;
 		if($idfield == null) $idfield = $this->GetIDField();
 		
         $edit_table = $objSession->GetEditTable($this->SourceTable);
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
         $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1";
         $insert = "CREATE TABLE ".$edit_table." ".$query;        
         if($objSession->HasSystemPermission("DEBUG.LIST"))
             echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
         $this->adodbConnection->Execute($insert);
     }
 
     function CopyFromEditTable($idfield = null)
     {
         global $objSession;
 
 		$dropRelTableFlag = false;
 		if($idfield == null) $idfield = $this->GetIDField();
         $edit_table = $objSession->GetEditTable($this->SourceTable);        
         $sql = "SELECT * FROM $edit_table";
         $rs = $this->adodbConnection->Execute($sql);
-        echo $sql."<BR>";
         
+        //echo "In Main <b>CopyFromEditTable</b> in class <b>".get_class($this).'</b><br>';
+        //echo $sql."<BR>";
+    	
         while($rs && !$rs->EOF)
         {
             $data = $rs->fields;            
             $c = new $this->classname;
             $c->SetFromArray($data);
             $c->idfield = $idfield;
             $c->Dirty();
-            if($c->Get($idfield)<1)
+            if($c->Get($idfield) < 1)
             {
                $old_id = $c->Get($idfield);
                $c->UnsetIdField();
                if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0)
                {
                    $c->Clean(array("OrgId"));
                }
                else
                {
 					if($c->Get("Status") != -2)
 					{
 						$org = new $this->classname();
 						$org->LoadFromDatabase($c->Get("OrgId"));
                      	$org->DeleteCustomData();
                      	$org->Delete(TRUE);
                      	$c->Set("OrgId",0);
 					}    	
                }               	
                $c->Create();
             }
           	if(is_numeric($c->Get("ResourceId")))
 			{							
                 if( isset($c->Related) && is_object($c->Related) )
                 { 
               		$r = $c->Related;              
               		$r->CopyFromEditTable($c->Get("ResourceId"));
               		$dropRelTableFlag = true;
             	}	
             
             	unset($r);
            	
             	if( isset($c->Reviews) && is_object($c->Reviews) )
             	{
                 	$r = $c->Reviews;
                 	$r->CopyFromEditTable($c->Get("ResourceId"));
             	}
 			}
             if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0)
             {
                    $c->Clean(array("OrgId"));
             }
             else
             {
 				if($c->Get("Status") != -2)
 				{
 					$org = new $this->classname();
 					$org->LoadFromDatabase($c->Get("OrgId"));
                    	$org->DeleteCustomData();
                    	$org->Delete(TRUE);
                    	$c->Set("OrgId",0);
 				}    	
             }           			
             
             if(method_exists($c,"CategoryMemberList"))
             {
               $cats = $c->CategoryMemberList($objSession->GetEditTable("CategoryItems"));
               $ci_table = $objSession->GetEditTable('CategoryItems');
               $primary_cat = $c->GetPrimaryCategory($ci_table);
               $c->Update();
               UpdateCategoryItems($c,$cats,$primary_cat);
             }
             else
               $c->Update();
 
             unset($c);
             unset($r);
             
             $rs->MoveNext();
         }
         
         if ($dropRelTableFlag)
         {
 	        $objRelGlobal = new clsRelationshipList(); 
 	        $objRelGlobal->PurgeEditTable();
         }
         
         if($edit_table) @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");  
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems"));
     }
 	
 	function GetNextTempID()
 	{
 		// get next temporary id (lower then zero) from temp table
 		$db =& $this->adodbConnection;
 		$sql = 'SELECT MIN(%s) AS MinValue FROM %s';
         return $db->GetOne( sprintf($sql, $this->GetIDField(), $this->SourceTable) ) - 1;
 	}
 	
     function PurgeEditTable($idfield = null)
     {
       global $objSession;
 	
 	  if($idfield == null) $idfield = $this->GetIDField();
       $edit_table = $objSession->GetEditTable($this->SourceTable);
 /*      $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table");
       while($rs && !$rs->EOF)
       {
         $data = $rs->fields;
         $c = new $this->classname;
         $c->SetFromArray($data);
         $c->id_field = $idfield;
         $c->tablename = $edit_table;
         $c->Delete();
         $rs->MoveNext();
       }*/
       @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
       @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->Get("CategoryItems"));
     }
 
     function CopyCatListToEditTable($idfield, $idlist)
     {
         global $objSession;
     
         $edit_table = $objSession->GetEditTable("CategoryItems");
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
         if(is_array($idlist))
         {
           $list = implode(",",$idlist);
         }
         else
              $list  = $idlist;
         $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield IN ($list)";
         
         $insert = "CREATE TABLE ".$edit_table." ".$query;
         if($objSession->HasSystemPermission("DEBUG.LIST"))
             echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
         $this->adodbConnection->Execute($insert);
     }
     
     function CreateEmptyCatListTable($idfield)
     {
         global $objSession;
     
         $edit_table = $objSession->GetEditTable("CategoryItems");
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
         $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield = -1";
         $insert = "CREATE TABLE ".$edit_table." ".$query;
         if($objSession->HasSystemPermission("DEBUG.LIST"))
            echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";                    
         $this->adodbConnection->Execute($insert);
     }
     
     
     function PurgeCatListEditTable()
     {
       global $objSession;
     	
       $edit_table = $objSession->GetEditTable("CategoryItems");
       $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");  
     }
 
 	function AdminSearchWhereClause($SearchList)
     {
       	$sql = "";
       	if( !is_array($SearchList) ) $SearchList = explode(",",$SearchList);
       	if( !count($SearchList) || !count($this->AdminSearchFields) ) return '';
       
       	for($f = 0; $f < count($SearchList); $f++)
       	{        
         	$value = $SearchList[$f];
         	if( strlen($value) )
         	{        
           		$inner_sql = "";
           		for($i = 0; $i < count($this->AdminSearchFields); $i++)
 				{
             		$field = $this->AdminSearchFields[$i];
             		if( strlen( trim($value) ) )
             		{
               			if( strlen($inner_sql) ) $inner_sql .= " OR ";
               			$inner_sql .= $field." LIKE '%".$value."%'";
             		}
           		}
           		if( strlen($inner_sql) )
           		{
            			$sql .= '('.$inner_sql.') ';       
            			if($f < count($SearchList) - 1) $sql .= " AND ";
           		}
         	}
       	}
       	return $sql;
     }
 
     function BackupData($OutFileName,$Start,$Limit)
     {
     	$fp=fopen($Outfile,"a");
     	if($fp)
     	{
     		if($Start==1)
     		{
     			$sql = "DELETE FROM ".$this->SourceTable;
     			fputs($fp,$sql);
     		}
     		$this->Query_Item("SELECT * FROM ".$this->SourceTable." LIMIT $Start, $Limit");
     		foreach($this->Items as $i)
     		{
     			$sql = $i->CreateSQL();
     			fputs($fp,$sql);
     		}
     		fclose($fp);
     		$this->Clear();
     	}
     }
     
     function RestoreData($InFileName,$Start,$Limit)
     {
     	$res = -1;
     	$fp=fopen($InFileName,"r");
     	if($fp)
     	{
 			fseek($fp,$Start);
 			$Line = 0;
 			while($Line < $Limit)
 			{
 				$sql = fgets($fp,16384);
 				$this->adodbConnection->Execute($sql);
 				$Line++;
 			}
 			$res = ftell($fp);
     		fclose($fp);	
     	}
     	return $res;
     }
     
     function Delete_Item($Id)
     {
         global $objCatList;
         
         $l =& $this->GetItem($Id);
         $l->BasePermission=$this->BasePermission;
         $l->DeleteCategoryItems($objCatList->CurrentCategoryID());    	
     }
     
     function Move_Item($Id, $OldCat, $ParentTo)
     {	
         global $objCatList;
 
         $l = $this->GetItem($Id);
         $l->BasePermission=$this->BasePermission;
         $l->AddtoCategory($ParentTo);
         $l->RemoveFromCategory($OldCat);
     }
 
     function Copy_Item($Id, $ParentTo)
     {	
         $l = $this->GetItem($Id);
         $l->BasePermission=$this->BasePermission;
         $l->AddtoCategory($ParentTo);
     }    
     	
 }/* clsItemCollection */
 
 class clsItemList extends clsItemCollection 
 {
 	var $Page;
 	var $PerPageVar;
 	var $DefaultPerPage; // use this perpage value in case if no found in config
 	var $EnablePaging;
 	var $MaxListCount = 0;
 	var $PageEnvar;
 	var $PageEnvarIndex;
 	var $ListType;
 	
 	function clsItemList()
 	{
 		$this->clsItemCollection();
 		$this->EnablePaging = TRUE;	
 		$this->PageEnvarIndex = "p";	
 	}
 	
 	function GetPageLimitSQL()
 	{
 		global $objConfig;
 		$limit = NULL;
 		if($this->EnablePaging)
 		{
         	if($this->Page<1)
             	$this->Page=1;
         	//echo "Limited to ".$objConfig->Get($this->PerPageVar)." items per page<br>\n";
 			if(is_numeric($objConfig->Get($this->PerPageVar)))
 			{
 				$Start = ($this->Page-1)*$objConfig->Get($this->PerPageVar);
 				$limit = "LIMIT ".$Start.",".$objConfig->Get($this->PerPageVar);
 			}
 			else
 				$limit = NULL;			
 		}
 		else 
 		{
 			if($this->MaxListCount)
 			{
 				$limit = "LIMIT 0, $MaxListCount";
 			}
 		}
 		return $limit;
 	}	
 	
 	function GetPageOffset()
 	{
 		$Start = 0;
 		if($this->EnablePaging)
 		{
 			if($this->Page < 1) $this->Page = 1;
 			$PerPage = $this->GetPerPage();
 			$Start = ($this->Page - 1) * $PerPage;
 		}
 		else 
 		{
 			if((int)$this->MaxListCount == 0) $Start = -1;
 		}
 		return $Start;
 	}
 	
 	function GetPageRowCount()
 	{
 		if($this->EnablePaging)
 		{
 			if($this->Page < 1) $this->Page = 1;
 			return $this->GetPerPage();
 		}
 		else 
 		  return (int)$this->MaxListCount;
 	}	
 		
     function Query_Item($sql,$limit = null, $fix_method = 'set_first')
     {
     	// query itemlist (module items) using $sql specified
     	// apply direct limit clause ($limit) or calculate it if not specified
     	// fix invalid page in case if needed by method specified in $fix_method
     	if(strlen($limit))
     	{
 	   	  $sql .= " ".$limit;
 	   	  return parent::Query_Item($sql);
     	}
     	else 
     	{
     		//echo "page fix pre (class: ".get_class($this).")<br>";
     		$this->QueryItemCount = QueryCount($sql); // must get total item count before fixing
     		$this->FixInvalidPage($fix_method);
     		return parent::Query_Item($sql,$this->GetPageOffset(),$this->GetPageRowCount());
     	}
     }  	
 
     function Query_List($whereClause,$orderByClause=NULL,$JoinCats=TRUE,$fix_method='set_first')
     {
         global $objSession, $Errors;
 
         if($JoinCats)
         {
           $cattable = GetTablePrefix()."CategoryItems";
           $t = $this->SourceTable;         
           $sql = "SELECT *,CategoryId FROM $t INNER JOIN $cattable ON $cattable.ItemResourceId=$t.ResourceId";
         }
         else
             $sql = "SELECT * FROM ". $this->SourceTable;
         if(trim($whereClause)!="")
         {
             if(isset($whereClause))
                 $sql = sprintf('%s WHERE %s',$sql,$whereClause);
         }
         if(strlen($orderByClause)>0)
         {
             	if(substr($orderByClause,0,8)=="ORDER BY")
             	{
                   $sql .= " ".$orderByClause;
             	}
             	else 
             	{
             	  $sql .= " ORDER BY $orderByClause";
             	}
         }
 
         if($objSession->HasSystemPermission("DEBUG.LIST"))
             echo $sql."<br>\n";
         
         return $this->Query_Item($sql, null, $fix_method);
     }    
     
     function GetPerPage()
 	{
 		// return category perpage
 		global $objConfig;
 		$PerPage = $objConfig->Get( $this->PerPageVar );
       	if( !is_numeric($PerPage) ) $PerPage = $this->DefaultPerPage ? $this->DefaultPerPage : 10;
 		return $PerPage;
 	}
 	
 	function FixInvalidPage($fix_method = 'set_first')
 	{
 		// in case if current page > total page count,
 		// then set current page to last possible "set_last"
 		// or first possible "set_first"
 		$PerPage = $this->GetPerPage();
       	$NumPages = ceil( $this->GetNumPages($PerPage) );
 /*      	
       	echo "=====<br>";
       	echo "Class <b>".get_class($this)."</b>: Page ".$this->Page." of $NumPages<br>";
       	echo "PerPage: $PerPage<br>";
       	echo "Items Queries: ".$this->QueryItemCount."<br>";
       	echo "=====<br>";
 */      	
       	if($this->Page > $NumPages)
       	{
       		switch($fix_method)
       		{
       			case 'set_first': 
       				$this->Page = 1; 
       				//echo "Move 2 First (class <b>".get_class($this)."</b>)<br>"; 
       				break;
       			case 'set_last': 
       				$this->Page = $NumPages; 
       				//echo "Move 2 Last (class <b>".get_class($this)."</b>)<br>"; 
       				break;
     		}
     		$this->SaveNewPage();
     	}
 	}
     
     function SaveNewPage()
     {
     	// redefine in each list, should save to env array new page value	
     	
     }
     
     function GetPageLinkList($dest_template=NULL,$page = "",$PagesToList=10, $HideEmpty=TRUE)
     {
         global $objConfig, $var_list_update, $var_list;
 
       
         $v= $this->PageEnvar;
                      
         global ${$v};        
         
         if(!strlen($page))
             $page = GetIndexURL();
 
         $PerPage = $objConfig->Get($this->PerPageVar);
         if($PerPage<1)
             $PerPage=20;
         $NumPages = ceil($this->GetNumPages($PerPage));
         if($NumPages==1 && $HideEmpty)
             return "";
 
         if(strlen($dest_template))
         {
             $var_list_update["t"] = $dest_template;
         }
         else
             $var_list_update["t"] = $var_list["t"];
 
         $o = "";
         if($this->Page==0 || !is_numeric($this->Page))
           $this->Page=1;
         if($this->Page>$NumPages)
             $this->Page=$NumPages;
 
         $StartPage = (int)$this->Page - ($PagesToList/2);
         if($StartPage<1)
             $StartPage=1;
 
         $EndPage = $StartPage+($PagesToList-1);
         if($EndPage>$NumPages)
         {
             $EndPage = $NumPages;
             $StartPage = $EndPage-($PagesToList-1);
             if($StartPage<1)
                 $StartPage=1;
         }
 
         $o = "";
         if($StartPage>1)
         {
           ${$v}[$this->PageEnvarIndex] = $this->Page-$PagesToList;
 		  
           $prev_url = $page."?env=".BuildEnv();
           $o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
         }
 
         for($p=$StartPage;$p<=$EndPage;$p++)
         {
             if($p!=$this->Page)
             {
                 ${$v}[$this->PageEnvarIndex]=$p;
                 $href = $page."?env=".BuildEnv();
                 $o .= " <A HREF=\"$href\">$p</A> ";
             }
             else
             {
                 $o .= " <SPAN class=\"current-page\">$p</SPAN>";
             }
         }
         if($EndPage<$NumPages && $EndPage>0)
         {
           ${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList;
 
           $next_url = $page."?env=".BuildEnv();
           $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
         }
         unset(${$v}[$this->PageEnvarIndex],$var_list_update["t"] );
         return $o;
     }   
     
     function GetAdminPageLinkList($url)
     {
         global $objConfig;
           
         $update =& $GLOBALS[$this->PageEnvar]; // env_var_update
                 
         // insteresting stuff :)
         if(!$this->PerPageVar) $this->PerPageVar = "Perpage_Links";
 
         $PerPage = $objConfig->Get($this->PerPageVar);
         if($PerPage < 1) $PerPage = 20;
           
         $NumPages = ceil($this->GetNumPages($PerPage));
         
         //echo $this->CurrentPage." of ".$NumPages." Pages";
 
         if($this->Page > $NumPages) $this->Page = $NumPages;
 
         $StartPage = $this->Page - 5;
         if($StartPage < 1) $StartPage = 1;
         $EndPage = $StartPage + 9;
         if($EndPage > $NumPages)
         {        
             $EndPage = $NumPages;
             $StartPage = $EndPage-9;
             if($StartPage < 1) $StartPage = 1;
         }
 
         $o = '';
 
         if($StartPage > 1)
         {
            $update[$this->PageEnvarIndex]= $this->Page - 10;
            $prev_url = $url.'?env='.BuildEnv();
            $o .= '<a href="'.$prev_url.'">&lt;&lt;</a>';
         }
 
         
         for($p = $StartPage; $p <= $EndPage; $p++)
         {
             if($p != $this->Page)
             {
                 $update[$this->PageEnvarIndex] = $p;
                 $href = $url.'?env='.BuildEnv();
                 $o .= ' <a href="'.$href.'" class="NAV_URL">'.$p.'</a> ';
             }
             else
             {
                 $o .= '<SPAN class="CURRENT_PAGE">'.$p.'</SPAN>';
             }
         }
         if($EndPage < $NumPages)
         {
           $update[$this->PageEnvarIndex] = $this->Page + 10;
           $next_url = $url.'?env='.BuildEnv();
           $o .= '<a href="'.$next_url.'"> &gt;&gt;</a>';
         }
         unset( $update[$this->PageEnvarIndex] );
         return $o;        
     }       
 }
 
 function ParseClipboard($clip)
 {
   $ret = array();
 
   $parts = explode(".",$clip,3);
   $command = $parts[0];
   $table = $parts[1];
   $prefix = GetTablePrefix();
   if(substr($table,0,strlen($prefix))==$prefix)
     $table = substr($table,strlen($prefix));
     
   $subparts = explode("=",$parts[2],2);
   $idfield = $subparts[0];
   $idlist = $subparts[1];
   $cmd = explode("-",$command);
   $ret["command"] = $cmd[0];
   $ret["source"] = $cmd[1];
   $ret["table"] = $table;
   $ret["idfield"] = $idfield;
   $ret["ids"] = $idlist;
 	//print_pre($ret);
   return $ret;
 }
 
 function UpdateCategoryItems($item,$NewCatList,$PrimaryCatId = false)
 {
   	global $objCatList;
   	
   	$CurrentList = explode(",",$item->CategoryMemberList());
   	$del_list = array();
   	$ins_list = array();
 
 
   if(!is_array($NewCatList))
   {
       if(strlen(trim($NewCatList))==0)
           $NewCatList = $objCatList->CurrentCategoryID();
   
       $NewCatList = explode(",",$NewCatList);
   }
   //print_r($NewCatList);
 
     for($i=0;$i<count($NewCatList);$i++)
   {
       $cat = $NewCatList[$i];
       if(!in_array($cat,$CurrentList))
          $ins_list[] = $cat;
   }
   for($i=0;$i<count($CurrentList);$i++)
   {
       $cat = $CurrentList[$i];
       if(!in_array($cat,$NewCatList))
           $del_list[] = $cat;
   }
   for($i=0;$i<count($ins_list);$i++)
   {
       $cat = $ins_list[$i];
       $item->AddToCategory($cat);
   }
   for($i=0;$i<count($del_list);$i++)
   {
       $cat = $del_list[$i];      
       $item->RemoveFromCategory($cat);
   }
   if($PrimaryCatId !== false) $item->SetPrimaryCategory($PrimaryCatId);
 }
 
 class clsCatItemList extends clsItemList 
 {
 	var $PerPageVarLong;
 	var $PerPageShortVar;
 	var $Query_SortField;
 	var $Query_SortOrder;
 	var $ItemType;
 	
   function clsCatItemList()
   {
   	$this->ClsItemList();
   	$this->Query_SortField = array();
   	$this->Query_SortOrder = array();
   }	
   
   function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)  
   {
   	global $objSession;
   	
     if($UseTableName)
     {
       $TableName = $this->SourceTable.".";
     }
     else {
       $TableName = "";	
     }
 
     $Orders = array();
 
     if($EditorsPick)  
     {
     	$Orders[] = $TableName."EditorsPick DESC";
     }
     if($Priority)
     {
        $Orders[] = $TableName."Priority DESC";  	
     }
   
     if(count($this->Query_SortField)>0)
     {
        for($x=0; $x<count($this->Query_SortField); $x++)
        {
        	 $FieldVar = $this->Query_SortField[$x];
        	 $OrderVar = $this->Query_SortOrder[$x];
        	 	   
          if(is_object($objSession))
          {
            $FieldVarData = $objSession->GetPersistantVariable($FieldVar);
            if(strlen($FieldVarData)>0)  
            {  		
 	           	$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
 	                   $objSession->GetPersistantVariable($OrderVar));          	
            }
          }
        }
     }
     
     if(count($Orders)>0)
     {
     	$OrderBy = "ORDER BY ".implode(", ",$Orders);
     }
     else   
 		$OrderBy="";
       
     return $OrderBy; 
   }
   
   function AddSortField($SortField, $SortOrder)
   {
   	 if(strlen($SortField))
   	 {
   	   $this->Query_SortField[] = $SortField;
   	   $this->Query_SortOrder[] = $SortOrder;
   	 }
   }
   
   function ClearSortFields()
   {
   	 $this->Query_SortField = array();
   	 $this->Query_SortOrder = array();
   }
   
   /* skeletons in this closet */
   
   function GetNewValue($CatId=NULL)
   {
   	return 0;
   }
   
   function GetPopValue($CategoryId=NULL)
   {
   	return 0;
   }  
   
   /* end of skeletons */
    
   function GetCountSQL($PermName,$CatId=NULL, $GroupId=NULL, $AdditonalWhere="")
   {
   	global $objSession, $objPermissions, $objCatList;
   	
   	$ltable = $this->SourceTable;
     $acl = $objSession->GetACLClause();
     $cattable = GetTablePrefix()."CategoryItems";
     $CategoryTable = GetTablePrefix()."Category";
     $ptable = GetTablePrefix()."PermCache";  	
     $VIEW = $objPermissions->GetPermId($PermName);
   	
   	$sql = "SELECT count(*) as CacheVal FROM $ltable ";
   	$sql .="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) ";
     $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) ";
     $sql .="INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) ";
     $sql .="WHERE ($acl AND PermId=$VIEW AND $cattable.PrimaryCat=1 AND $CategoryTable.Status=1) ";
 
 	if(strlen($AdditonalWhere)>0)
     {
       $sql .= "AND (".$AdditonalWhere.")";
     }   
     
     return $sql;
   }
   
   function SqlCategoryList($attribs = array())
   { 	 
   	 $CatTable = GetTablePrefix()."CategoryItems";
      $t = $this->SourceTable;
      
      $sql = "SELECT *,$CatTable.CategoryId FROM $t INNER JOIN $CatTable ON $CatTable.ItemResourceId=$t.ResourceId ";
      $sql .="WHERE ($CatTable.CategoryId=".$catid." AND $t.Status=1)";
      
      return $sql;
   }
   
   
   function CategoryCount($attribs=array())
   {  	   	  
   	 global $objCatList, $objCountCache;
   	 
   	 $cat = $attribs["_catid"];
      if(!is_numeric($cat))
      {
         $cat = $objCatList->CurrentCategoryID();
      }
      if((int)$cat>0)
         $c = $objCatList->GetCategory($cat);  	       		 
            
   	 $CatTable = GetTablePrefix()."CategoryItems";
      $t = $this->SourceTable;
      
      $sql = "SELECT count(*) as MyCount FROM $t INNER JOIN $CatTable ON ($CatTable.ItemResourceId=$t.ResourceId) ";     
      if($attribs["_subcats"])
      {
      	$ctable = $objCatList->SourceTable;
      	$sql .= "INNER JOIN $ctable ON ($CatTable.CategoryId=$ctable.CategoryId) ";
      	$sql .= "WHERE (ParentPath LIKE '".$c->Get("ParentPath")."%' ";
      	if(!$attribs["_countcurrent"])
      	{
      	  $sql .=" AND $ctable.CategoryId != $cat) ";
      	}
      	else
      	  $sql .=") ";
      }
      else
        $sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) ";  	
     
       if($attribs["_today"])
       {
         $today = mktime(0,0,0,date("m"),date("d"),date("Y"));             
         $sql .= "AND ($t.CreatedOn>=$today) ";	
       }
       //echo $sql."<br><br>\n";
 	  $rs = $this->adodbConnection->Execute($sql);
 	  $ret = "";
 	  if($rs && !$rs->EOF)
 	    $ret = (int)$rs->fields["MyCount"];
   	  return $ret;
   }
   
   function SqlGlobalCount($attribs=array())
   {
   	 global $objSession;
   	 
   	 $p = $this->BasePermission.".VIEW";
   	 $t = $this->SourceTable;
      if($attribs["_today"])
      {
         $today = mktime(0,0,0,date("m"),date("d"),date("Y"));             
         $where = "($t.CreatedOn>=$today)";	
      }  	 
      
     if($attribs["_grouponly"])
 	{
 	   $GroupList = $objSession->Get("GroupList");	    	  
 	}
 	else        		
 	   $GroupList = NULL;
 		        
   	 $sql = $this->GetCountSQL($p,NULL,$GroupList,$where);
   	 return $sql;
   }
   
   function DoGlobalCount($attribs)
   {
   	  global $objCountCache;
   	  
  	  $cc = $objCountCache->GetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"], 3600);
   	  if(!is_numeric($cc))
   	  {  	
   	  	$sql = $this->SqlGlobalCount($attribs);
   	  	$ret = QueryCount($sql);
   	  	$objCountCache->SetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"],$ret);
   	  }
   	  else
   	    $ret = $cc;
   	  return $ret;
   }
   
 
   function CacheListExtraId($ListType)
   {
   	global $objSession;
   	
   	if(!strlen($ListType))
   	  $ListType="_";  	
   	switch($ListType)
   	{  
   		case "_":
   			$ExtraId = $objSession->Get("GroupList");  			
   		break;
   		case "category":
   			$ExtraId = $objSession->Get("GroupList");
   		break;	
   		case "myitems":
   		     $ExtraId = $objSession->Get("PortalUserId");
   		break;
   		case "hot":
   			$ExtraId = $objSession->Get("GroupList");
   		break;
   		case "pop":
   			$ExtraId = $objSession->Get("GroupList");
   		break;
   		case "pick":
       		$ExtraId = $objSession->Get("GroupList");
   		break;
   		case "favorites":
       		$ExtraId = $objSession->Get("PortalUserId");
   		break;
   		case "new":
   			$ExtraId = $objSession->Get("GroupList");
   		break;	
   	}
   	return $ExtraId;
   }
   
   function CacheListType($ListType)
   {
   	if(!strlen($ListType))
   	  $ListType="_";  	
   	switch($ListType)
   	{  
   		case "_":
   			$ListTypeId = 0; 			
   		break;
   		case "category":
   			$ListTypeId = 1;
   		break;	
   		case "myitems":
   		     $ListTypeId = 2;
   		break;
   		case "hot":
   			$ListTypeId = 3;
   		break;
   		case "pop":
   			$ListTypeId = 4;
   		break;
   		case "pick":
       		$ListTypeId = 5;
   		break;
   		case "favorites":
       		$ListTypeId = 6;
   		break;
   		case "new":
   			$ListTypeId = 8;
   		break;	
   	}
   	return $ListTypeId;
   }  
 
   function PerformItemCount($attribs=array())
   {
   	global $objCountCache, $objSession;
   	       
   	$ret = "";
   	$ListType = $attribs["_listtype"];
   	if(!strlen($ListType))
   	  $ListType="_";
   	    
 	$ListTypeId = $this->CacheListType($ListType);
   	//echo "ListType: $ListType ($ListTypeId)<br>\n";  
 	$ExtraId = $this->CacheListExtraId($ListType);
   	switch($ListType)
   	{  
   		case "_":
   			$ret = $this->DoGlobalCount($attribs);
   		break;
   		case "category":  		
   			$ret = $this->CategoryCount($attribs);
   		break;	
   		case "myitems":
   		     $sql = $this->SqlMyItems($attribs);      		
   		break;
   		case "hot":
   			$sql = $this->SqlHotItems($attribs);      		
   		break;
   		case "pop":
   			$sql = $this->SqlPopItems($attribs);      		
   		break;
   		case "pick":
       		$sql = $this->SqlPickItems($attribs);
   		break;
   		case "favorites":
       		$sql = $this->SqlFavorites($attribs);
   		break;
   		case "search":
       		$sql = $this->SqlSearchItems($attribs);
   		break;
   		case "new":
   			$sql = $this->SqlNewItems($attribs);
   		break;	
   	}
   	//echo "SQL: $sql<br>";
   	if(strlen($sql))
   	{
   		if(is_numeric($ListTypeId))
   		{
   		  $cc = $objCountCache->GetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"], 3600);
   		  
   	   	  if(!is_numeric($cc) || $attribs['_nocache'] == 1)
   		  {
   			$ret = QueryCount($sql);
   			$objCountCache->SetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"],$ret);
   		  }
   		  else
   	  		$ret = $cc;
   		}
   		else
   		  $ret = QueryCount($sql);
   	}
   	  
   	return $ret;  
   }
   
   function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="")
   {
   	global $objSession, $objPermissions;
   	
   	$ltable = $this->SourceTable;
     $acl = $objSession->GetACLClause();
     $cattable = GetTablePrefix()."CategoryItems";
     $CategoryTable = GetTablePrefix()."Category";
     $ptable = GetTablePrefix()."PermCache";  	
     $VIEW = $objPermissions->GetPermId($PermName);
     $sql ="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) ";
     $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) ";
     $sql .= "INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) ";
     $sql .="WHERE ($acl AND  PermId=$VIEW AND PrimaryCat=1 AND $CategoryTable.Status=1) ";
     
     if(is_numeric($CatId))
     {
     	$sql .= " AND ($CategoryTable.CategoryId=$CatId) ";
     }
     if(strlen($AdditionalWhere)>0)
     {
       $sql .= "AND (".$AdditionalWhere.")";
     }
     return $sql;
   }
     
 	function CountFavorites($attribs)
 	{		
 		if($attribs["_today"])
 		{
         	global $objSession, $objConfig, $objPermissions;
 
         	$acl = $objSession->GetACLClause();
         	$favtable = GetTablePrefix()."Favorites";
         	$ltable = $this->SourceTable;
         	$cattable = GetTablePrefix()."CategoryItems";
         	$CategoryTable = GetTablePrefix()."Category";
         	$ptable = GetTablePrefix()."PermCache";
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));             
       		
 	        $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1";
 	        $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;     	   
     	    $p = $this->BasePermission.".VIEW";
         
         	$sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) ";
         	$sql .= $this->GetJoinedSQL($p,NULL,$where);			
         	$ret = QueryCount($sql);
 		}
 		else
 		{
 		  if (!$this->ListType == "favorites")
 		  {
 			$this->ListType = "favorites";
 			$this->LoadFavorites($attribs);
 			$ret = $this->QueryItemCount;			
 	 	  }
 		  else
 			$ret = $this->QueryItemCount;
 		}
 		return $ret;
 	}
 	
 	
 	
 	function CountPickItems($attribs)
 	{		
 		if (!$this->ListType == "pick")
 		{
 			$this->ListType = "pick";
 			$this->LoadPickItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 	
 	function CountMyItems($attribs)
 	{		
 		if (!$this->ListType == "myitems")
 		{
 			$this->ListType = "myitems";
 			$this->LoadMyItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 		
 	function CountHotItems($attribs)
 	{		
 		if (!$this->ListType == "hotitems")
 		{
 			$this->ListType = "hotitems";
 			$this->LoadHotItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 	
 	function CountNewItems($attribs)
 	{		
 		if (!$this->ListType == "newitems")
 		{
 			$this->ListType = "newitems";
 			$this->LoadNewItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 	
 	function CountPopItems($attribs)
 	{		
 		if (!$this->ListType == "popitems")
 		{
 			$this->ListType = "popitems";
 			$this->LoadPopItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 		
 	
 	function CountSearchItems($attribs)
 	{		
 		if (!$this->ListType == "search")
 		{
 			$this->ListType = "search";
 			$this->LoadSearchItems($attribs);
 			$ret = $this->QueryItemCount;			
 		}
 		else
 			$ret = $this->QueryItemCount;
 		
 		return $ret;
 	}
 	
 	function SqlFavorites($attribs)
 	{
         global $objSession, $objConfig, $objPermissions;
 
         $acl = $objSession->GetACLClause();
         $favtable = GetTablePrefix()."Favorites";
         $ltable = $this->SourceTable;
         $cattable = GetTablePrefix()."CategoryItems";
         $CategoryTable = GetTablePrefix()."Category";
         $ptable = GetTablePrefix()."PermCache";
      	   
         $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1";
         if($attribs["_today"])
         {
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));                   	
 	        $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType;          
         }
         $p = $this->BasePermission.".VIEW";
         
         $sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) ";
         $sql .= $this->GetJoinedSQL($p,NULL,$where);
 
 
  	    $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
         $sql .= " ".$OrderBy;
 		return $sql;
 	}
   
     function LoadFavorites($attribs)
     {
 		global $objSession, $objCountCache;
 		
 		$sql = $this->SqlFavorites($attribs);
     	    
 	    if($objSession->HasSystemPermission("DEBUG.LIST"))
               echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong;
         
         $CachedCount = $objCountCache->GetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],3600);         
         if(!is_numeric($CachedCount))
         {
           $this->QueryItemCount = QueryCount($sql);
           $objCountCache->SetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],$this->QueryItemCount);
         }
         else
          $this->QueryItemCount = (int)$CachedCount;
         
         return $this->Query_Item($sql);           
     }
     
     function SqlPickItems($attribs)
     {
        global $objSession, $objCatList;
 
        $catid = (int)$attribs["_catid"];
        $scope = (int)$attribs["_scope"];
 	   //$JoinCats = (int)$attribs["_catinfo"] || $scope;	  
           	          
    	   $TableName = $this->SourceTable;
        if($scope)
        {
             if (!$catid) 
             {
                $catid = $objCatList->CurrentCategoryID();
             }                                            
             $where =  "CategoryId =".$catid." AND ".$TableName.".EditorsPick=1 AND ".$TableName.".Status=1";
        }
        else
        {
             $where = $TableName.".EditorsPick=1 AND ".$TableName.".Status=1 ";
             $catid=NULL;
        }
        if($attribs["_today"])
        {
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));  
    	  		$where .= " AND ($TableName.CreatedOn>=$today)";
        }       
        $CategoryTable = GetTablePrefix()."Category";
  	   $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
  	   $p = $this->BasePermission.".VIEW";
  	   $sql .= $this->GetJoinedSQL($p,$CatUd,$where);
  	   
        $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
        $sql .= " ".$OrderBy; 	         
        return $sql;
     }    	
     
     function LoadPickItems($attribs)
     {
        global $objSession, $objCountCache;
        
        $sql = $this->SqlPickItems($attribs);     
        if($objSession->HasSystemPermission("DEBUG.LIST"))
             echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
             
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong;
                       
        $CachedCount = $objCountCache->GetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],3600);            
        if(!is_numeric($CachedCount))
        {
  	     $this->QueryItemCount= QueryCount($sql);
          $objCountCache->SetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],$this->QueryItemCount);
        }
        else
          $this->QueryItemCount=$CachedCount;
 
        return $this->Query_Item($sql);  	   
     }
     
     function SqlMyItems($attribs= array())
     {
         global $objSession;
 
 		$TableName = $this->SourceTable;
  		$where =  " ".$TableName.".Status>-1 AND ".$TableName.".CreatedById=".$objSession->Get("PortalUserId");
         if($attribs["_today"])
         {
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));  
    	  		$where .= " AND ($TableName.CreatedOn>=$today)";
         }
  		$CategoryTable = GetTablePrefix()."Category"; 	   
  		$sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
  	    $p = $this->BasePermission.".VIEW";
  	    $sql .= $this->GetJoinedSQL($p,$CatUd,$where);
  	        	    
         $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
         $sql .= " ".$OrderBy; 	         
 	
         return $sql;
     }    
     
     function LoadMyItems($attribs=array())
     {        
     	global $objSession,$objCountCache;              
     	$sql = $this->SqlMyItems($attribs);
         if($objSession->HasSystemPermission("DEBUG.LIST"))
               echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong; 		
  		               
        $CachedCount = $objCountCache->GetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],3600);            
        if(!is_numeric($CachedCount))
        {
  	     $this->QueryItemCount= QueryCount($sql);
          $objCountCache->SetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],$this->QueryItemCount);
        }
        else
          $this->QueryItemCount=$CachedCount;
  
         return $this->Query_Item($sql);  	   
     }    
     
     function SqlNewItems($attribs = array())
     {
        global $objSession, $objCatList;
 
        $catid = (int)$attribs["_catid"];
        $scope = (int)$attribs["_scope"];
 	   //$JoinCats = (int)$attribs["_catinfo"] || $scope;	  	  
                  
    	   $TableName = $this->SourceTable;
 	   if($attribs["_today"])
        {
    	  		$cutoff = mktime(0,0,0,date("m"),date("d"),date("Y")); 
        }
        else
        {
        	  if($scope)
        	  {
             if (!$catid) 
             {
                $catid = $objCatList->CurrentCategoryID();
             }           	  	
          	$cutoff = $this->GetNewValue($catid);
        	  }
        	  else
        	    $cutoff = $this->GetNewValue();
        }
        if($scope)
        {
             if (!$catid) 
             {
                $catid = $objCatList->CurrentCategoryID();
             }           	  	                                        
             
             $where =  "CategoryId =".$catid." AND ((".$TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 ";            
        }
        else
        {
             $where =  "((".$TableName.".CreatedOn >=".$this->GetNewValue()." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 ";
        }
 
        $CategoryTable = GetTablePrefix()."Category";
  	   $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
  	   $p = $this->BasePermission.".VIEW";
  	   $sql .= $this->GetJoinedSQL($p,$CatUd,$where);
  	   
        $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
        $sql .= " ".$OrderBy;         
        return $sql;
     }
 
     function LoadNewItems($attribs)
     {
 		global $objSession,$objCountCache;
 		
 		$sql = $this->SqlNewItems($attribs);
 		
         if($objSession->HasSystemPermission("DEBUG.LIST"))
               echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong;
                         
        $CachedCount = $objCountCache->GetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],3600);            
        if(!is_numeric($CachedCount))
        {
  	     $this->QueryItemCount= QueryCount($sql);
          $objCountCache->SetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],$this->QueryItemCount);
        }
        else
          $this->QueryItemCount=$CachedCount;    
          
          
        return $this->Query_Item($sql);  	   
     }    
 
     function SqlPopItems($attribs)
     {
        global $objSession, $objCatList;
 
        $catid = (int)$attribs["_catid"];
        $scope = (int)$attribs["_scope"];
 	   //$JoinCats = (int)$attribs["_catinfo"] || $scope;	  	   
                  
    	   $TableName = $this->SourceTable;
 
        if($scope)
        {
             if (!$catid) 
             {
                $catid = $objCatList->CurrentCategoryID();
             }   
             $where =  "CategoryId =".$catid." AND ((".$TableName.".Hits >=".$this->GetLinkPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1";
        }
        else       	
        {
              $where =  "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
              
        		$where =  "((".$TableName.".Hits >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
        }
         if($attribs["_today"])
         {
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));  
    	  		$where .= " AND ($TableName.CreatedOn>=$today)";
         }        
        $CategoryTable = GetTablePrefix()."Category";
  	   $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
  	   $p = $this->BasePermission.".VIEW";
  	   $sql .= $this->GetJoinedSQL($p,$catid,$where);
  	   
  	   $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
        $sql .= " ".$OrderBy;
        
     	return $sql;
     }
     
     function LoadPopItems($attribs)
     {
        global $objSession,$objCountCache;
        $sql = $this->SqlPopItems($attribs);
             
        if($objSession->HasSystemPermission("DEBUG.LIST"))
               echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong;
                         
        $CachedCount = $objCountCache->GetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],3600);            
        if(!is_numeric($CachedCount))
        {
  	     $this->QueryItemCount= QueryCount($sql);
          $objCountCache->SetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],$this->QueryItemCount);
        }
        else
          $this->QueryItemCount=$CachedCount;
         
        return $this->Query_Item($sql);  	   
     }    
 
     function SqlHotItems($attribs)
     {
        global $objSession, $objCatList;
 
        $catid = (int)$attribs["_catid"];
        $scope = (int)$attribs["_scope"];
 
 //       $JoinCats = (int)$attribs["_catinfo"] || $scope;	 
 
         $TableName = $this->SourceTable;	
 		  	
 		$OrderBy = $TableName.".CachedRating DESC";       
 
         if($scope)
         {
             if (!$catid) 
             {
                $catid = $objCatList->CurrentCategoryID();
             }        
             $where =  "CategoryId =".$catid." AND ((".$TableName.".CachedRating >=".$this->GetHotValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1";
         }
         else
         {
             $where =  "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 ";
         }
         
         if($attribs["_today"])
         {
    	  		$today = mktime(0,0,0,date("m"),date("d"),date("Y"));  
    	  		$where .= " AND ($TableName.CreatedOn>=$today)";
         }        
         $CategoryTable = GetTablePrefix()."Category";
  	    $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName ";
  	    $p = $this->BasePermission.".VIEW";
  	    $CatId = !$scope? NULL : $catid; 	    
  	    $sql .= $this->GetJoinedSQL($p,$CatId,$where);
  	   
         if(strlen($OrderBy))
             $sql .= " ORDER BY $OrderBy "; 	    
                  
     	return $sql;
     }
     
     function LoadHotItems($attribs)
     {
         global $objSession,$objCountCache;    
     	
         $sql = $this->SqlHotItems($attribs);
         if($objSession->HasSystemPermission("DEBUG.LIST"))
               echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
               
         if($attribs["_shortlist"])
         {
             $this->PerPageVar = $this->PerPageShortVar; 
         }
         else 
           $this->PerPageVar = $this->PerPageVarLong;   
                      
        $CachedCount = $objCountCache->GetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"], 0);            
        if(!is_numeric($CachedCount))
        {
  	     $this->QueryItemCount= QueryCount($sql);
          $objCountCache->SetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"],$this->QueryItemCount);
        }
        else
          $this->QueryItemCount=$CachedCount;
         
        return $this->Query_Item($sql);  	       	
     }
     
     function SqlSearchItems($attribs = array())
     {
         global $objConfig, $objItemTypes, $objSession, $objPermissions, $CountVal;
 
         $acl = $objSession->GetACLClause();
         $this->Clear();
         //$stable = "ses_".$objSession->GetSessionKey()."_Search";
         $stable = $objSession->GetSearchTable();
         $ltable = $this->SourceTable;
         $catitems = GetTablePrefix()."CategoryItems";
         $cattable = GetTablePrefix()."Category";
         $ptable = GetTablePrefix()."PermCache";
         $p = $this->BasePermission.".VIEW";
         $i = new $this->classname();
         
         $sql =  "SELECT $cattable.CategoryId,$cattable.CachedNavbar,$ltable.*, Relevance FROM $stable ";
         $sql .= "INNER JOIN $ltable ON ($stable.ItemId=$ltable.".$i->id_field.") ";
         
         $where = "ItemType=".$this->ItemType." AND $ltable.Status=1";
         
         $sql .= $this->GetJoinedSQL($p,NULL,$where);               
         $sql .= " ORDER BY EdPick DESC,Relevance DESC ";
         
         $tmp = $this->QueryOrderByClause(FALSE,TRUE,TRUE);
         $tmp = substr($tmp,9);
         if(strlen($tmp))
         {
         	$sql .= ", ".$tmp." ";
         }
 		return $sql;    	
     }
         
     function LoadSearchItems($attribs = array())
     {
 		global $CountVal, $objSession;
         //echo "Loading <b>".get_class($this)."</b> Search Items<br>";
 		$sql = $this->SqlSearchItems($attribs);
         //echo "$sql<br>";
         $this->Query_Item($sql);
         $Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
         //echo "SQL Loaded ItemCount (<b>".get_class($this).'</b>): '.$this->NumItems().'<br>';
         for($i = 0; $i < $this->NumItems(); $i++)
         {
           $this->Items[$i]->Keywords = $Keywords;
         }
         if(is_numeric($CountVal[$this->ItemType]))
         {
           $this->QueryItemCount = $CountVal[$this->ItemType];
           //echo "CACHE: <pre>"; print_r($CountVal); echo "</pre><BR>";
         }
         else
         {
           $this->QueryItemCount = QueryCount($sql);
           //echo "<b>SQL</b>: ".$sql."<br><br>";
           $CountVal[$this->ItemType] = $this->QueryItemCount;
         }
                 
     }
         
     function PasteFromClipboard($TargetCat,$NameField="")
     {
       global $objSession,$objCatList;
 	
       $clip = $objSession->GetVariable("ClipBoard");
       if(strlen($clip))
       {
           $ClipBoard = ParseClipboard($clip);
           $IsCopy = (substr($ClipBoard["command"],0,4)=="COPY") || ($ClipBoard["source"] == $TargetCat);
 
           $item_ids = explode(",",$ClipBoard["ids"]);
           for($i=0;$i<count($item_ids);$i++)
           {              
               $item = $this->GetItem($item_ids[$i]);
               if(!$IsCopy) // paste to other category then current
               {   
                   $item->MoveToCategory($ClipBoard["source"],$TargetCat);                                                   
                   $clip = str_replace("CUT","COPY",$clip);
                   $objSession->SetVariable("ClipBoard",$clip);
               }
               else
               {              
                     $item->CopyToNewResource($TargetCat,$NameField); // create item copy, but with new ResourceId
                     $item->AddToCategory($TargetCat);
                     UpdateCategoryCount($item->type,$TargetCat);
               
               }
           }
       }
     }
     
     function AdminPrintItems($template)
 	{
 	    // prints item listing for admin (browse/advanced view) tabs
 	    $o = '<table border="0" cellspacing="2" width="100%"><tbody><tr>';
 	
 		$i = 1;
 	    
 	    $topleft		=	0;
 	    $topright		=	0;
 	    $rightcount		=	0;
 	    $total_items	=	$this->NumItems();
 	    $topleft		=	ceil($total_items / 2);
 	    $topright		=	$total_items - $topleft;
 	  
 	    for($x = 0; $x < $topleft; $x++) 
 	    {
 	        //printingleft
 	        $item = $this->Items[$x];
 			if ($i > 2)
 			{
 				$o .= "</tr>\n<tr>";
 				$i = 1;
 			}
 			$o .= $item->AdminParseTemplate($template);
 			$i++;
 	        
 	        //printingright
 	        if ($rightcount < $topright && ( ($x + $topleft) < $total_items) ) 
 	        {
 	            $item = $this->Items[ $x + $topleft ];
 				if ($i > 2)
 				{	
 				    $o.="</tr>\n<tr>";
 				    $i = 1;
 				}
 				$o .= $item->AdminParseTemplate($template);
 				$i++;
 	            $rightcount++;
 	        }
 	    }
 		$o .= "\n</tr></tbody></table>\n";   
 
 		return $o;
 	}
     
 }
 
 // -------------- NEW CLASSES -----------------------
 
 class DBList {
 	
 	// table related attributes
 	var $db = null;
 	var $table_name = '';
 	var $LiveTable = '';
 	var $EditTable = '';
 	
 	
 	// record related attributes
 	var $records = Array();
 	var $record_count = 0;
 	var $cur_rec = -1; // "-1" means no records, or record index otherwise
 	
 	// query related attributes
 	var $SelectSQL = "SELECT * FROM %s";
 	
 	function DBList()
 	{
 		// use $this->SetTable('live', 'table name');
 		// in inherited constructors to set table for list
 		$this->db =& GetADODBConnection();	
 	}
 	
 	function SetTable($action, $table_name = null)
     {
     	// $action = {'live', 'restore','edit'}
     	switch($action)
     	{
     		case 'live': 
     			$this->LiveTable = $table_name;
     			$this->table_name = $this->LiveTable;
     			break;
     		case 'restore': 
     			$this->table_name = $this->LiveTable; 
     			break;
     		case 'edit':
     			global $objSession;
     			$this->table_name = $objSession->GetEditTable($this->LiveTable);
     			break;
     	}
     }
 	
 	function Clear()
 	{
 		// no use of this method at a time :)
 		$this->records = Array();
 		$this->record_count = 0;
 		$this->cur_rec = -1;	
 	}
 	
 	function Query()
 	{
 		// query list	
 		$sql = sprintf($this->SelectSQL, $this->table_name);
 		echo "SQL: $sql<br>";
 		$rs =& $this->db->Execute($sql);
 		
 		if( $this->db->ErrorNo() == 0 )
 		{
 			$this->records = $rs->GetRows();
 			$this->record_count = count($this->records);
 			//$this->cur_rec = $this->record_count ? 0 : -1;
 		}
 		else
 			return false;
 	}
 	
 	function ProcessList($callback_method)
 	{
 		// process list using user-defined method called
 		// with one parameter - current record fields 
 		// (associative array)
 		if($this->record_count > 0)
 		{
 			$this->cur_rec = 0;
 			while($this->cur_rec < $this->record_count)
 			{
 				if( method_exists($this, $callback_method) )
 					$this->$callback_method( $this->GetCurrent() );
 				$this->cur_rec++;	
 			}
 		}
 	}
 	
 	function &GetCurrent()
 	{
 		// return currently processed record (with change ability)
 		return ($this->cur_rec != -1) ? $this->records[$this->cur_rec] : false;
 	}
 	
 	function GetDBField($field_name)
 	{
 		$rec =& $this->GetCurrent();
 		return is_array($rec) && isset($rec[$field_name]) ? $rec[$field_name] : false;
 	}
 }
 
 
 ?>

Property changes on: trunk/kernel/include/parseditem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19
\ No newline at end of property
+1.20
\ No newline at end of property
Index: trunk/kernel/include/itemreview.php
===================================================================
--- trunk/kernel/include/itemreview.php	(revision 347)
+++ trunk/kernel/include/itemreview.php	(revision 348)
@@ -1,614 +1,617 @@
 <?php
 
 function ip_exists($ip,$id,$SourceTable)
 {
         $count = 0;
         $sql = "SELECT count(*) as DupCount FROM $SourceTable WHERE IPAddress='$ip' and ItemId=$id";
         $adodbConnection = GetADODBConnection(); 
         $rs = $adodbConnection->Execute($sql);
         if($rs)
         {
             $count = $rs->fields["DupCount"];
         }
         return ($count>0);           
 }
 
 RegisterPrefix("clsItemReview","review","kernel/include/itemreview.php");
      
 class clsItemReview extends clsParsedItem
 {
     function clsItemReview($ReviewId=NULL,$table="ItemReview")
     {
         $this->clsParsedItem();
         $this->tablename = $table;
         $this->id_field = "ReviewId";
         $this->type=-20;
         $this->NoResourceId=1;
         $this->TagPrefix = "review";
 
         if($ReviewId!=NULL)
             $this->LoadFromDatabase($ReviewId);
     }
 
     function Validate()
     {
         global $Errors;
 
         $dataValid = true;
         if(!isset($this->m_CreatedOn))
         {
             $Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate");
             $dataValid = false;
         }
 
         if(!isset($this->m_ReviewText))
         {
             $Errors->AddError("error.fieldIsRequired",'ReviewText',"","",get_class($this),"Validate");
             $dataValid = false;
         }
         
         if(!isset($this->m_Pending))
         {
             $Error->AddError("error.fieldIsRequired",'Pending',"","",get_class($this),"Validate");
             $dataValid = false;
         }
         
         if(!isset($this->m_IPAddress))
         {
             $Error->AddError("error.fieldIsRequired",'IPAddress',"","",get_class($this),"Validate");
             $dataValid = false;
         }
         
         if(!isset($this->m_ItemId))
         {
             $Error->AddError("error.fieldIsRequired",'ItemId',"","",get_class($this),"Validate");
             $dataValid = false;
         }
         
         if(!isset($this->m_CreatedById))
         {
             $Error->AddError("error.fieldIsRequired",'CreatedBy',"","",get_class($this),"Validate");
             $dataValid = false;
         }
 
         return $dataValid;
     }
 
     function LoadFromDatabase($Id)
     {
         global $objSession, $Errors;
 
         if(!isset($Id))
         {
             $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
             return false;
         }
                 
         $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ReviewId = '%s'",$Id);
         if( $GLOBALS['debuglevel'] ) echo $sql."<br>";
         $result = $this->adodbConnection->Execute($sql);
         if ($result === false)
         {
             $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
             return false;
         }
 		$data = $result->fields;
 		if(is_array($data))
             $this->SetFromArray($data);
         $this->Clean();
         return TRUE;
     }    
   
     function MoveUp()
     {
         $this->Increment("Priority");
     }
 
     function MoveDown()
     {
         $this->Decrement("Priority");
     }
 
     function ParseObject($element)
     { 
         global $objConfig, $objCatList, $rootURL, $objUsers;
 
         $extra_attribs = ExtraAttributes($element->attributes);
         
         if(strtolower($element->name)==$this->TagPrefix)
         {          
             $field = strtolower($element->attributes["_field"]); 
             switch($field)
             {
             case "id":
             	/*
             	@field:review.id
             	@description: review id
             	*/
                 $ret = $this->Get("ReviewId");
                 break;
 		    case "item_id":
 		    	/*
 		    	@field:review.item_id
 		    	@description: ID of the item being reviewed
 		    	*/
                 $ret =  inp_unescape($this->Get("ItemId"));
                 break;
 		    case "text":
 		    	/*
 		    	@field:review.text
 		    	@description:Review text
 		    	*/
 		    	if($this->Get("TextFormat")==0 || $element->attribues["_textonly"])
 		    	{
 		    	  $ret = inp_escape($this->Get("ReviewText"),0);
 		    	}
 		    	else 
 		    	{
                 	$ret = $this->Get("ReviewText");
 		    	}
                 break;		
 		    case "ip":
 		    	/*
 		    	@field:review.ip
 		    	@description:IP address of remote host submitting the review
 		    	*/
 			    $ret = $this->Get("IPAddress");
                 break;
 		    case "pending":
 		    	/*
 		    	@field:review.pending
 		    	@description: Returns the review pening status
 		    	*/
                 $ret = $this->Get("Pending");
                 break;		
             case "item_type":
             	/*
             	@field:review.item_type
             	@description:Returns the name of the reviewed item type
             	*/
                 $type =& $objItemTypes->GetItem($this->Get("ItemType"));
                 if(is_object($type))
                   $ret = $type->Get("ItemName");                
             break;
             case "date":
             	/*
   				@field:review.date
   				@description:Returns the date/time the review was created
   				@attrib:_tz:bool:Convert the date to the user's local time
   				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
             	*/               
                 $d = $this->Get("CreatedOn");
                 if($element->attributes["_tz"])
                 {
                     $d = GetLocalTime($d,$objSession->Get("tz"));
                 }
 
                 $part = strtolower($element->attributes["_part"]);
                 if(strlen($part))
                 {
                     $ret = ExtractDatePart($part,$d);
                 }
                 else
                 {                
                   if($d<=0)
                   {                  
                     $ret = "";
                   }
                   else
                     $ret = LangDate($d);
                 }
             break;
             case "reviewer":
             	/*
             	@field:revier.reviewer
             	@description:Parse a user tag for the user submitting the review
             	@attrib:_usertag::User tag to parse, defaults to the users login name
             	*/
                 $userfield = $element->attributes["_usertag"];
                 if(!strlen($userfield))
                 {
                     $userfield = "login";
                 }
                 if($this->Get("CreatedById")>0)
                 {
                   $u =& $objUsers->GetItem($this->Get("CreatedById"));                
                   $e = new clsHtmlTag(); 
                   $e->name = $u->TagPrefix;
                   $e->attributes = $element->attributes;
                   $e->attributes["_field"] = $userfield;
                   $ret = $u->ParseObject($e);
                 }
                 else 
                   if($userfield=="login")
                     $ret = "root";
             break;
             default:
                     $tag = $this->TagPrefix."_".$field;
                     $ret = "Undefined: ".$tag->name;
             break;
             }
         }
         else
         {
            $ret = $element->Execute();           
         }
         return $ret;
     }
 
     function parsetag($tag)
     {	
         global $objConfig, $objUsers, $objItemTypes;
         if(is_object($tag))
         {        
             $tagname = $tag->name;
         }
         else
             $tagname = $tag;
         switch($tagname)
         {	
             case "review_id":
                 return $this->Get("ReviewId");
                 break;
 		    case "review_item_id":
                 return inp_unescape($this->Get("ItemId"));
                 break;
 		    case "review_text":
                 return $this->Get("ReviewText");
                 break;		
 		    case "review_ip_address":
 			    return $this->Get("IPAddress");
                 break;
 		    case "review_pending":
                 return $this->Get("Pending");
                 break;		
             case "review_item_type":
                 $type =& $objItemTypes->GetItem($this->Get("ItemType"));
                 $res = $type->Get("ItemName");
                 return $res;
                 break;
             case "review_created_date":
                 return LangDate($this->Get("CreatedOn"));
                 break;		
             case "review_created_time":
                 if($this->Get("CreatedOn")<=0)
                     return "";        
                 return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn"));
                 break;
 
 		    case "review_created_date_month":
                 return adodb_date("m", $this->Get("CreatedOn"));
                 break;		
 		    case "review_created_date_day":
                 return adodb_date("d", $this->Get("CreatedOn"));
                 break;		
 		    case "review_created_date_year":
                 return adodb_date("Y", $this->Get("CreatedOn"));
                 break;
             default:
                 if (substr($tagname, 0, 16) == "review_createdby")
                 {
                   /* parse the created by user */
                     $u = $objUsers->GetUser($this->Get("CreatedById"));
                     $usertag = substr($tag,17);
                     return $u->parsetag($usertag);
                 }
                 else
                     return "Undefined:$tagname";
                 break;
         }
     }
 
     function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL)
     {
         global $objItemTypes, $objMessageList;
 
         $type =& $objItemTypes->GetItem($this->Get("ItemType"));
         $res = $type->Get("ItemName");
         $EventName = $res.$Suffix;
 
         $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
         if(is_object($Event))
         {
             if($Event->Get("Enabled")=="1")
             {
                 $Event->Item = $this;
                 return $Event->SendToUser($ToUserId);                
             }
         }
     }
 
     function SendAdminEventMail($EventName,$LangId=NULL)
     {
         global $objItemTypes, $objMessageList;
 
         $type =& $objItemTypes->GetItem($this->Get("ItemType"));
         $res = $type->Get("ItemName");
         $EventName = $res; //.$Suffix;
 
         $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
         if(is_object($Event))
         {
             if($Event->Get("Enabled")=="1")
             {
                 $Event->Item = $this;
                 return $Event->SendAdmin($ToUserId);
             }
         }
     }
 } /*clsIItemReview*/
 
 class clsItemReviewList extends clsItemCollection
 {
     var $itemID;
     var $Page;
     var $PerPageVar;
 
     function clsItemReviewList($id=NULL)
     {
         $this->clsItemCollection();
         $this->classname = "clsItemReview";
         $this->SourceTable = GetTablePrefix()."ItemReview";
         $this->Page = 1;
         $this->PerPageVar = "Perpage_Review";
         if(isset($id))
             $this->itemID=$id;
         $this->AdminSearchFields = array("ReviewText");
     }
 
     function ItemCount()
     {
       return $this->NumItems();
     }
 
     function GetReview($ID)
     {
 	  return $this->GetItem($ID);
     }
 
     function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL)
     {
         $this->Clear();
         $where = "ItemId=".$this->itemID;
         $sql = "SELECT * FROM ".$this->SourceTable." WHERE ";
         if(strlen($StatusWhere))
             $where .= " AND ".$StatusWhere;
         $sql .= $where;
         if(strlen($OrderBy))
             $sql .= " ORDER BY ".$OrderBy;
         $Limit = $this->GetLimitSQL();
         if(strlen($Limit))
             $sql .= " ".$Limit;
         $this->QueryItemCount=TableCount($this->SourceTable,$where,0);
         return $this->Query_item($sql);
     }
 
     function GetItemReviewCount($TodayOnly = FALSE)
     {
         $sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1";
         if($TodayOnly)
         {
             $today = mktime(0,0,0,date("m"),date("d"),date("Y"));            
             $where .= " AND CreatedOn>=$today"; 
         }
         $rs = $this->adodbConnection->execute($sql);
         $count=0;
         if($rs)
             $count = $rs->fields["ItemCount"];
         return (int)$count;
     }
 
     function ip_exists($ip,$id)
     {
       return ip_exists($ip,id,$this->SourceTable);
     }
 
     function GetLimitSQL()
     {
         global $objConfig;
         if($this->Page<1)
             $this->Page=1;
         $PerPage = $objConfig->Get($this->PerPageVar);
         if(is_numeric($PerPage))
         {
             $Start = ($this->Page-1)*$PerPage;
             $limit = "LIMIT ".$Start.",".$PerPage;
         }
         else
             $limit = NULL;
         return $limit;
     }
 
 
     function Query_Review($whereClause=NULL,$orderByClause=NULL)
     {
       global $Errors;
 
       $this->Clear();
       $sql = "SELECT *  FROM ".$this->SourceTable." ";
 
       if(isset($whereClause) && strlen(trim($whereClause))>0)
         $sql = sprintf("%s WHERE %s",$sql,$whereClause);
 
       if(isset($orderByClause) && strlen(trim($orderByClause))>0)
         $sql = sprintf("%s ORDER BY %s",$sql,$orderByClause);
 
       return $this->Query_Item($sql);
     }
 
     function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress,
                        $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module)
     {
         global $objSession;
     	
     	$r = new clsItemReview(NULL,$this->SourceTable);     
         
         $ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText);   
         //$r->debuglevel = 1;
 
         $r->Set(array("CreatedOn","ReviewText","Status", "IPAddress",
                       "Priority","ItemId","ItemType","CreatedById","TextFormat","Module"),
                 array($CreatedOn,$ReviewText,$Status, $IPAddress,
                       $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));                      
         $r->Create();                
         array_push($this->Items,$r);
         if($Status==1)
         {
             $r->SendUserEventMail("REVIEW.ADD",$CreatedById);
             $r->SendAdminEventMail("REVIEW.ADD");      
         }
         else
         {
             $r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById);
             $r->SendAdminEventMail("REVIEW.ADD.PENDING");      
         }
 
         return $r;
     }
 
     function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status, 
                         $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)
     {
         global $objSession;
         
         $r = $this->GetItem($ReviewId);
         if($CreatedById==0)
           $CreatedById = $r->Get("CreatedById");
         $r->Set(array("ReviewId","CreatedOn","ReviewText","Status", 
                       "IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"),
                 array($ReviewId,$CreatedOn,$ReviewText,$Status,
                       $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
         $r->Update();
         //$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId"));
         $r->SendAdminEventMail("REVIEW.MODIFY");      
         return $r;
     }
 
     function DeleteReview($ReviewId)
     {
         $r = $this->GetItem($ReviewId);
         $r->Delete();
     }
 
     function CopyToItemId($OldId,$NewId)
     {
       $this->Clear();
       $this->Query_Review("ItemId=$OldId","");
       if($this->NumItems()>0)
       {
           foreach($this->Items as $i)
           {
               $i->Set("ItemId",$NewId);
               $i->UnsetIdField();
               $i->Create();
           }
       }
     }
 
     function CopyFromEditTable($ResourceId)
     {
         global $objSession;
-
+		//echo "ToLive [Reviews]<br>";
         $edit_table = $objSession->GetEditTable($this->SourceTable);
         $idlist = array();
         $sql = "SELECT * FROM $edit_table";
         $this->Clear();
+        // get all items in edit-table
         $rs = $this->adodbConnection->Execute($sql);
         while($rs && !$rs->EOF)
         {
-            $data = $rs->fields;
+            $data =& $rs->fields;
+            
             $c = $this->AddItemFromArray($data);            
 
             $c->Dirty();
             if($data["ReviewId"]>0)
             {
                 $c->Update();
             }
             else
             {
                 $c->UnsetIdField();
                 $c->Create();
             }
             $idlist[] = $c->Get("ReviewId");
             $rs->MoveNext();
         }
+        //print_pre($idlist);
         $sql = "DELETE FROM ".$this->SourceTable." WHERE ItemId=$ResourceId AND ReviewId NOT IN (".implode(",",$idlist).")";
         $this->adodbConnection->Execute($sql);
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$edit_table);
     }
 
 
     function GetPageLinkList(&$UpdateVar,$dest_template=NULL,$page = NULL,$PagesToList=10,$HideEmpty=TRUE)
     {
         global $objConfig, $var_list_update, $var_list;
 
         if(!strlen($page))
             $page = GetIndexURL();
         $PerPage = $objConfig->Get($this->PerPageVar);
         if($PerPage<1)
             $PerPage=20;
         $NumPages = ceil($this->GetNumPages($PerPage));
 
         if($NumPages==1 && $HideEmpty)
             return "";
 
         if(strlen($dest_template))
         {
             $var_list_update["t"] = $dest_template;
         }
         else
             $var_list_update["t"] = $var_list["t"];
 
         $o = "";
         if($this->Page>$NumPages)
             $this->Page=$NumPages;
 
         $StartPage = (int)$this->Page - ($PagesToList/2);
         if($StartPage<1)
             $StartPage=1;
 
         $EndPage = $StartPage+($PagesToList-1);
         if($EndPage>$NumPages)
         {
             $EndPage = $NumPages;
             $StartPage = $EndPage-($PagesToList-1);
             if($StartPage<1)
                 $StartPage=1;
         }
 
         $o = "";
         if($StartPage>1)
         {
           $UpdateVar["rp"] = $this->Page-$PagesToList;
           $prev_url = $page."?env=".BuildEnv();
           $o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
         }
 
 
         for($p=$StartPage;$p<=$EndPage;$p++)
         {
             if($p!=$this->Page)
             {
                 $UpdateVar["rp"]=$p;
                 $href = $page."?env=".BuildEnv();
                 $o .= " <A HREF=\"$href\" >$p</A> ";
             }
             else
             {
                 $o .= "$p";
             }
         }
         if($EndPage<$NumPages && $EndPage>0)
         {
           $UpdateVar["rp"]=$this->Page+$PagesToList;
           $next_url = $page."?env=".BuildEnv();
           $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
         }                               
         unset($UpdateVar,$var_list_update["t"] );
         return $o;       
     }
 
 
 } /*clsItemReviewList*/
 
 ?>

Property changes on: trunk/kernel/include/itemreview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.5
\ No newline at end of property
Index: trunk/kernel/include/portalgroup.php
===================================================================
--- trunk/kernel/include/portalgroup.php	(revision 347)
+++ trunk/kernel/include/portalgroup.php	(revision 348)
@@ -1,497 +1,497 @@
 <?php
 
 class clsPortalGroup extends clsParsedItem
 {
    var $UserCount;
 
     function clsPortalGroup($GroupId=NULL)
     {
         $this->clsParsedItem($GroupId);
         $this->tablename=GetTablePrefix()."PortalGroup"; 
         $this->type=7;
         $this->BasePermission="GROUP";
         $this->id_field = "GroupId";
         if($GroupId)
             $this->LoadFromDatabase($GroupId);
     }
 
     function Validate()
     {
 		global $objSession, $Errors;
 
         $dataValid = true;
         if(!isset($this->m_Name) || $this->m_Name == "")
         {
             $Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
             $dataValid = false;
         }
         
         return $dataValid;
     }
 
 
 	function HasSystemPermission($PermissionName)
     {
 		$GroupId = $this->Get("GroupId");
 		$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE GroupId=$GroupId AND Permission='$PermissionName' AND type=1";
         $result = $this->adodbConnection->Execute($sql);
         if($result && !$result->EOF)
         {
             $this->SysPermCache[$PermissionName] = (int)$result->fields["PermissionValue"];
             return (int)$result->fields["PermissionValue"];
         }
         else
             return -1;
     }
 
 	/* set $Value to -1 to delete the permission row from the DB */
 	function SetSystemPermission($PermName,$Value)
 	{
       //echo "Setting $PermName to $Value<br>\n";
 	  $oldval = $this->HasSystemPermission($PermName);
 	  if($Value != $oldval)
 	  {
         if($Value>-1)
 	    {
           if($oldval>-1)
 		  {
 		    $sql = "UPDATE ".GetTablePrefix()."Permissions SET PermissionValue=$Value ";
 			$sql .="  WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
 		  }
 		  else
 		  {
 		    $sql = "INSERT INTO ".GetTablePrefix()."Permissions (Permission, GroupId, PermissionValue, Type, CatId) ";
 			$sql .="VALUES ('$PermName',".$this->Get("GroupId").",$Value,1,0)";
           }
 		  $this->adodbConnection->Execute($sql);
           //echo $sql."<br>\n";
 	    }
 		else
 		{
 		  $sql = "DELETE FROM ".GetTablePrefix()."Permissions ";
           $sql .="  WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
 		  $this->adodbConnection->Execute($sql);
           //echo $sql."<br>\n";
 		}
 	  }
 	}
 
     function CheckPermission($permissionName)
     {
         //Check permission and if needs approval set approval
 		global $objSession, $Errors;
 
         if(!$objSession->HasSystemPermission($permissionName))
         {
            //$Errors->AddError("error.AccessDenied","","","",get_class($this),"CheckPermission");
            return false;
         }
         return true;
     }
 
     function LoadFromDatabase($Id)
     {		        
         global $Errors;
 
         if(!isset($Id))
         {
             $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
             return false;
         }
                 
         $sql = "SELECT * FROM ".$this->tablename." WHERE GroupId = $Id";
         $result = $this->adodbConnection->Execute($sql);
         if ($result === false)
         {
             $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
             return false;
         }
         $data = $result->fields;
         $this->SetFromArray($data);
         $this->Clean();
         return true;
     }
 
 	function AddUser($UserId,$PrimaryGroup=0)
 	{
  	  	// add user to group OR just updates it's status there
  	  	$db =& $this->adodbConnection;
  	  	$table = GetTablePrefix().'UserGroup';
  	  	$group_id = $this->Get('GroupId');
  	  
  	  	$sql_patterns['check'] = 'SELECT PortalUserId FROM %s WHERE GroupId = %s AND PortalUserId = %s';
  	  	$sql_patterns['reset_primary'] = 'UPDATE %s SET PrimaryGroup = 0 WHERE PortalUserId = %s';
  	  	$sql_patterns['set_primary'] = 'UPDATE %s SET PrimaryGroup = 1 WHERE GroupId = %s AND PortalUserId = %s';
  	  	$sql_patterns['add_to_group'] = 'INSERT INTO %s (PortalUserId,GroupId,PrimaryGroup) VALUES (%s, %s, %s)';
  	  	
  	  	$tmp_sql = sprintf($sql_patterns['check'], $table, $group_id, $UserId);
       	$check_result = $db->GetOne($tmp_sql);
       	if(!$check_result)
 	  	{
             // user is not a memeber of this group
             $GroupCount = TableCount($table,"PortalUserId = $UserId", 0);
             if(!$PrimaryGroup) $PrimaryGroup = ($GroupCount == 0) ? 1 : 0; // reset primary status if not already
             $tmp_sql = sprintf($sql_patterns['add_to_group'], $table, $UserId, $group_id, $PrimaryGroup);
 			$db->Execute($tmp_sql);
 	  	}
 	  	
 	  	if($PrimaryGroup)
         {
         	$tmp_sql = sprintf($sql_patterns['reset_primary'], $table, $UserId);
         	$db->Execute($tmp_sql);
         	
         	$tmp_sql = sprintf($sql_patterns['set_primary'], $table, $group_id, $UserId);
             $db->Execute($tmp_sql);
         }
 	}	
 
     function DeleteUser($UserId)
     {
         $sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=$UserId AND GroupId=".$this->Get("GroupId");        
         $this->adodbConnection->Execute($sql);
     }
     
 
     function GetCustomField( $fieldName)
     {
         global $Errors;
 
         if(!isset($this->m_UserId))
         {
            $Errors->AddError("error.AppError",NULL,"Get field is required in order to set custom field values","","clsPortalGroup","GetCustomField");
            return false;
         }
 
         return GetCustomFieldValue($this->m_UserId,"portaluser",$fieldName);
     }
      
     function SetCustomField( $fieldName, $value)
     {
 		global $Errors;	
         if(!isset($this->m_UserId))
         {
            $Errors->AddError("error.AppError",NULL,"Set field is required in order to set custom field values","","clsPortalGroup","SetCustomField");
            return false;
         }
         return SetCustomFieldValue($this->m_UserId,"portaluser",$fieldName,$value);
     }
 
     function GetUserCount()
     {
         if(!is_numeric($this->UserCount))
         {
             $sql = "SELECT count(*) as UserCount FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
             $rs = $this->adodbConnection->Execute($sql);
             if($rs && !$rs->EOF)
                 $users = $rs->fields["UserCount"];
             $this->UserCount = (int)$users;
         }
         return $this->UserCount;
     }
 
     function GetUserList()
     {
         $sql = "SELECT * FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
         $rs = $this->adodbConnection->Execute($sql);
         $res = array();
         while($rs && !$rs->EOF) 
         {
             $res[] = $rs->fields["PortalUserId"];
             $rs->MoveNext();
         }
         return $res;
     }
 
     function parsetag($tag)
     {
         global $var_list_update, $objConfig;
         if(is_object($tag))
         {        
             $tagname = $tag->name;
         }
         else
             $tagname = $tag;
         switch($tagname)
         {	
 		    case "group_id":
                 return $this->Get("GroupId");
                 break;
 		    case "group_name":
                 return $this->Get("Name");
                 break;
 		    case "group_desc":
                 return $this->Get("Description");
                 break;
 		    case "group_date":
                 return LangDate($this->Get("CreatedOn"));
                 break;
 		    case "group_name":
                 return $this->Get("Name");
                 break;
 		    case "group_enabled":
                 return $this->Get("Enabled");
                 break;
 		    case "group_date_month":
                 return adodb_date("m", $this->Get("CreatedOn"));
                 break;		
 		    case "group_date_day":
                 return adodb_date("d", $this->Get("CreatedOn"));
                 break;		
 		    case "group_date_year":
                 return adodb_date("Y", $this->Get("CreatedOn"));
                 break;	
 		    case "group_system":
                 if ($this->Get("System") == 1)
                     return "System";
                 else
                     return "User Defined";
                 break;
 		    case "group_status":
                 if ($this->Get("Enabled") == 1)
                     return "Enabled";
                 else
                     return "Disabled";		
                 break;	
                 default:
                     if (substr($tag, 0, 6) == "custom")
                         return Users_Custom($this->Get("ResourceId"), $tag);
                     else
                         return "Undefined:$tagname";
                     break;
         }
     }
 }
 
 class clsGroupList extends clsItemCollection
 {
     var $Page;
 
     function clsGroupList()
     {
         $this->clsItemCollection();
         $this->classname = "clsPortalGroup";
         $this->SetTable('live', GetTablePrefix()."PortalGroup");
         $this->AdminSearchFields = array("name");
         $this->id_field = "GroupId";
     }
     function NumGroups()
     {
         return $this->NumItems();
     }
 
     function GetGroup($GroupID)
     {
         return $this->GetItem($GroupID);
     }
 
     function GetPersonalGroup($UserLogin)
     {
 	    $n = "_".$UserLogin;
         $g = $this->GetItemByField("Name",$n);
         return $g;
     }
 
     function LoadGroups($where = "",$orderBy = "")
     {
         global $objConfig;
 
         $this->Clear();
         if($this->Page<1)
             $this->Page=1;
 
 		if(is_numeric($objConfig->Get("Perpage_Groups")))
 		{
 			$Start = ($this->Page-1)*$objConfig->Get("Perpage_Groups");
 			$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Groups");
 		}
 		else
 			$limit = NULL;
-
-		if(strlen($where)==0)
-		  $where = "1";
-		$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
+		
+		if(strlen($where) == 0) $where = '1';
+		$this->QueryItemCount=TableCount($this->SourceTable, $where, 0);
         //echo $this->QueryItemCount."<br>\n";
 
 			if ($orderBy!="")
 			{
 				$this->Query_PortalGroup($where,$orderBy,$limit);
 			}
 			else
 			{
 				$this->Query_PortalGroup($where,"Name DESC",$limit);
 			}
 
 	}
 
-    function Query_PortalGroup($whereClause=NULL,$orderByClause=NULL)
+    function Query_PortalGroup($whereClause=NULL,$orderByClause=NULL,$limit=null)
     {
         global $m_var_list,$objSession,$Errors;
 
         $sql = "SELECT * FROM ".$this->SourceTable." ";
 
         if(strlen($whereClause))
             $sql = sprintf('%s WHERE %s',$sql,$whereClause);
 
         if(strlen($orderByClause))
             if(strlen(trim($orderByClause)))
               $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
-
+		
+		if( isset($limit) ) $sql .= ' '.$limit;
         return $this->Query_Item($sql);    
     }    
 
     function Query_UserPortalGroup($whereClause,$orderByClause)
     { 
         global $m_var_list,$objSession,$Errors;
     
         if ($m_var_list["action"] == "m_group_search")
             $table = $userSession->Get("SessionKey") . "_search";
         else
             $table = $this->SourceTable;
 	
         $sql = "SELECT * FROM $table LEFT JOIN UserGroup USING (GroupId) ";
     
         if(isset($whereClause))
             $sql = sprintf('%s WHERE %s',$sql,$whereClause);
     
         if(isset($orderByClause))
             if (strlen(trim($orderByClause))) 
             {           
               $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
             }
         $result = $this->adodbConnection->Execute($sql);
     
         return $this->Query_Item($sql);    
     }
 
     function GetAllGroupList()
     {
     	static $GroupListCache;
     	
     	if(!is_array($GroupListCache))
     	{
           $GroupListCache = array();
           $sql = "SELECT GroupId FROM ".$this->SourceTable." WHERE Enabled=1";
 
           $rs = $this->adodbConnection->Execute($sql);
           while($rs && !$rs->EOF)
           {
             $GroupListCache[] = $rs->fields["GroupId"];
             $rs->MoveNext();
           }
     	}
         return $GroupListCache;
     }
 
     function Group_Custom($ResourceId, $tag)    
     {        
         $fieldname= substr($tag, 7);
 
         $sql = "SELECT Value FROM ".GetTablePrefix()."CustomMetaData LEFT JOIN ".GetTablePrefix()."CustomField USING (CustomFieldId) where ".GetTablePrefix()."CustomMetaData.ResourceId=$ResourceId AND ".GetTablePrefix()."CustomField.FieldName='$fieldname'";
 	
         $result = $this->adodbConnection->Execute($sql);
     
         if ($result->EOF)
             return "";
         else
             return $result->fields["Value"];
     }
 
     function Add_Users_To_Group($groupid)
     {	
         global $g_usergroup_status;
         $userids = explode("-", $g_usergroup_status);
         $g = $this->GetItem($groupid);
         foreach($userids as $userid)
             $g->AddUser($userid);
     }
 
     function Delete_Group($GroupId)
     {
         $g = $this->GetItem($GroupId);
         if(is_object($g))
         {
            $g->Delete();
         }
     }
 
     function Edit_Group($GroupId, $Name, $Description)
     {
         $g = $this->GetItem($GroupId);
         $g->Set(array("Name", "Description"), array($Name, $Description));
         $g->Update();
         return $g;
     }
 
     function Add_Group($Name, $Description, $System=1)
     {
         $g = new clsPortalGroup(NULL);
         $g->tablename = $this->SourceTable;
         $g->Set(array("Name", "Description", "System"),array($Name, $Description,$System));
         $g->Set("CreatedOn",adodb_date("U"));
         $g->Create();
         return $g;
     }
     
     function CopyFromEditTable($idfield)
     {
         global $objSession;
 
         $edit_table = $objSession->GetEditTable($this->SourceTable);        
         $sql = "SELECT * FROM $edit_table";
 
         $rs = $this->adodbConnection->Execute($sql);
         while($rs && !$rs->EOF)
         {
             $data = $rs->fields;            
             $c = new $this->classname;
             $c->SetFromArray($data);
             $c->idfield = $idfield;
             $c->Dirty();
             if($c->Get($idfield)<1)
             {
                $old_id = $c->Get($idfield);
                $c->UnsetIdField();
                if(!is_numeric($c->Get("OrgId")))
                    $c->Clean(array("OrgId"));
                $c->Create();
                $sql = "UPDATE ".GetTablePrefix()."UserGroup SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
                $this->adodbConnection->Execute($sql);
                $sql = "UPDATE ".GetTablePrefix()."Permissions SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
                $this->adodbConnection->Execute($sql);
             }
 
             $c->Update();
             unset($c);
             unset($r);
             $rs->MoveNext();
         }
         @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
     }    
 
     function PurgeEditTable($idfield)
     {
       global $objSession;
 
       $edit_table = $objSession->GetEditTable($this->SourceTable);
       @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
 
       $sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE GroupId<1";
       $this->adodbConnection->Execute($sql);
       $sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE GroupId<1";
       $this->adodbConnection->Execute($sql);      
       
     }
 }
 /*
 class clsUserGroupList extends clsItemCollection
 {
     function clsUserGroupList()
     {
         $this->clsItemCollection();
         $this->classname = "clsPortalGroup";
         $this->SetTable('live', GetTablePrefix()."UserGroup");
         $this->id_field = "PortalUserId"; // don't try to insert by this ID :)
     }
 }
 */
 ?>

Property changes on: trunk/kernel/include/portalgroup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/admin/include/toolbar/groupselect.php
===================================================================
--- trunk/kernel/admin/include/toolbar/groupselect.php	(revision 347)
+++ trunk/kernel/admin/include/toolbar/groupselect.php	(revision 348)
@@ -1,187 +1,181 @@
 <?php             
 global $section, $pathtoroot, $envar, $m_user_filter, $m_user_active_disabled, 
        $m_user_pending, $m_user_sort, $m_user_sortby, $m_user_perpage,  
        $rootURL,$imagesURL,$GroupFilter, $adminURL;
 
 $group_select = $adminURL."/users/group_select.php";
 
 
 if (!isset($m_user_active_disabled))
 {
     $m_user_active_disabled=0;
 }
 
 // Article filter
 switch($m_user_active_disabled)
 {
     case 1:
         $m_user_active = 1;
         $m_user_filter = " AND Enabled=1";
         break;
     case 2:
         $m_user_disabled = 1;
         $m_user_filter = " AND Enabled=0";
         break;
     case 3:
         $m_user_active = 1;
         $m_user_disabled = 1;
         break;
 }
 
 if ($m_user_pending == 1)
 {	$m_user_pending = 1;
 	$m_user_filter = " AND Pending=1";	
 }
 
 // Sorting
 $varname = "m_user_sort_" . $m_user_sort;
 $$varname = 1;
 
 $varname = "m_user_sortby_" . $m_user_sortby;
 $$varname = 1;
 
 $varname = "m_user_perpage_" . $m_user_perpage;
 $$varname = 1;
 
-$destform = $_POST["destform"];
-
-if ($destform == '') {
-	$destform = $_GET["destform"];
-}
-
-$destfield = $_GET["destfield"];
+$destform = GetVar('destform', true);
+$destfield = GetVar('destfield');
 
 $User_Page = (int)$objConfig->Get("Perpage_Grouplist");
-if(!$User_Page)
-    $User_Page = 10;
+if(!$User_Page) $User_Page = 10;
 
 /* Set the sort values */
 $SortField = trim($objConfig->Get("GroupSelect_SortField"));
 $SortOrder = trim($objConfig->Get("GroupSelect_SortOrder"));
 if(!strlen($SortOrder))
     $SortOrder = "asc";
 
 
 $browseURL = $adminURL."/browse";
 
 $lang_users = language("la_Text_Users");
 $lang_Username = language("la_prompt_Username");
 $lang_LastName = language("la_prompt_LastName");
 $lang_FirstName = language("la_prompt_FirstName");
 $lang_Email = language("la_prompt_Email");
 $lang_PrimaryGroup = language("la_prompt_PrimaryGroup");
 $lang_Valid = language("la_Text_Valid");
 $lang_GroupName = language("la_Text_Group_Name");
 $lang_Group = language("la_Text_Group");
 $lang_UserCount = language("la_Text_User_Count");
 $lang_Groups = language("la_Text_Groups");
 $lang_Default = language("la_Text_Default");
 
 print <<<END
 
 <script language="Javascript">
 <!--
 
 var lang_Users = "$lang_users";
 var lang_Username = "$lang_Username";
 var lang_LastName = "$lang_LastName";
 var lang_FirstName = "$lang_FirstName";
 var lang_Email = "$lang_Email";
 var lang_PrimaryGroup = "$lang_PrimaryGroup";
 var lang_Valid = "$lang_Valid";
 var lang_Group = "$lang_Group";
 var lang_GroupName = "$lang_GroupName";
 var lang_UserCount = "$lang_UserCount";
 var lang_Groups = "$lang_Groups";
 var lang_Default ="$lang_Default";
 
 function ShowViewMenu()
 {
     button = document.getElementById('viewmenubutton');
 
     x = getRealLeft(button);
     y = getRealTop(button);
 
    if(window.triedToWriteMenus == false)
    {
      fwLoadMenus();
    }
    window.FW_showMenu(window.user_menu,x,y+32);
    return false;
 }
 
 
 
 function fwLoadMenus() {
    	
    // if (window.fw_menu_0) return;
 	
 	window.menu_sorting = new Menu(lang_Sort);
     menu_sorting.imagePath = '$imagesURL'+'/';
 
     menu_sorting.addMenuItem(lang_Asc,"config_val('GroupSelect_SortOrder','asc');",RadioIsSelected('$SortOrder','asc'));
     menu_sorting.addMenuItem(lang_Desc,"config_val('GroupSelect_SortOrder','desc');",RadioIsSelected('$SortOrder','desc'));
     menu_sorting.addMenuSeparator();
  //   menu_sorting.addMenuItem(lang_Default,"config_val('GroupSelect_SortField', 'Name');",''));
 
 	menu_sorting.addMenuItem(lang_GroupName,"config_val('GroupSelect_SortField', 'Name');",RadioIsSelected('$SortField','Name'));
 	menu_sorting.addMenuItem(lang_UserCount,"config_val('GroupSelect_SortField', 'Description');",RadioIsSelected('$SortField','Description'));
 	
     window.menu_results = new Menu(lang_Groups+' '+lang_PerPage);
 	menu_results.imagePath = '$imagesURL'+'/';
     
     menu_results.addMenuItem("10","config_val('Perpage_Grouplist', '10');",PerPageSelected('$User_Page',10));
 	menu_results.addMenuItem("20","config_val('Perpage_Grouplist', '20');",PerPageSelected('$User_Page',20));
 	menu_results.addMenuItem("50","config_val('Perpage_Grouplist', '50');",PerPageSelected('$User_Page',50));
 	menu_results.addMenuItem("100","config_val('Perpage_Grouplist', '100');",PerPageSelected('$User_Page',100));
 
 	window.menu_select = new Menu(lang_Select);
 	menu_select.addMenuItem(lang_All,"GroupChecks.selectAll(true);","");
 	menu_select.addMenuItem(lang_Unselect,"GroupChecks.selectAll(false);","");
 	menu_select.addMenuItem(lang_Invert,"GroupChecks.invertItems();","");
 
 	window.user_menu = new Menu("root");
 //  window.user_menu.childMenuIcon= '$imagesURL'+'/';
     window.user_menu.imagePath = '$imagesURL'+'/';
 //  window.user_menu.addMenuItem(menu_filter);
     window.user_menu.addMenuItem(menu_sorting);
 	window.user_menu.addMenuItem(menu_results);
 	window.user_menu.addMenuItem(menu_select);
 
 	window.triedToWriteMenus = false;
     	window.user_menu.writeMenus();
 }
 //-->
 </script>
 
 <script language="JavaScript1.2" src="$browseURL/fw_menu.js"></script>
 <script language="JavaScript1.2" src="$adminURL/include/checkarray.js"></script>
 <script language="Javascript">
 
 GroupChecks = new CheckArray();
 GroupChecks.formname='grouplistform';
 GroupChecks.envar='$envar';
 
 function SelectSubmit()
 {                    
     bf = window.opener.document.$destform;   
     retval = GroupChecks.getItemList();
     if(retval.length>0)
     {    
       bf.$destfield.value = retval; 
       bf.submit();
       window.close();
     }
 }
 
 function SetStatus()
 {    
     self.status=GroupChecks.countChecks()+" Groups selected";
 }
 
 </script>
 
 
 
 END;
 ?>
\ No newline at end of file

Property changes on: trunk/kernel/admin/include/toolbar/groupselect.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/admin/include/toolbar/main_import.php
===================================================================
--- trunk/kernel/admin/include/toolbar/main_import.php	(revision 347)
+++ trunk/kernel/admin/include/toolbar/main_import.php	(revision 348)
@@ -1,109 +1,128 @@
 <?php
 	// import scripts definitions: begin
 	global $import_scripts, $var, $objSession, $ro_perm;
 	$import_scripts = GetImportScripts();
 	
 	// import scripts definitions: end
 	$ro_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
 ?>
 
 <script language="javascript" type="text/javascript">
 	
 <?php
 	if(!$ro_perm)
 	{
 ?>	
+	var StepInfo = Array();
+	
+	function InitStep(step_id, step_name, total_recs)
+	{
+		StepInfo[step_id] = Array();
+		StepInfo[step_id]['total'] = total_recs;
+		StepInfo[step_id]['current'] = 0;
+		StepInfo[step_id]['name'] = step_name;
+		SetTotal(step_name);
+	}
+	
 	function PageOnLoad(step_no)
 	{
 		if( step_no == 1 )
 		{
 			// uncheck "agree" checkbox if toolbar button is disabled
 			var cb = document.getElementById('agree');
 			var next_btn = document.getElementById('moveright');
 			if(cb.checked == true && next_btn.getAttribute('ButtonState') == 'disabled')
 				cb.checked = false;
 		}
 	}
 	
 	function UsedAgreed()
 	{
 		return document.getElementById('agree').checked ? 1 : 0;
 	}
 	
 	function ImportRedirect(form, import_id)
 	{
 		if( import_id === false ) return false;
 		var frm = document.getElementById(form);
 		frm.import_id.value = import_id;
 		frm.submit();
 	}
 	
 	function CheckFinalForm(form)
 	{
 		// checks if all required fields are filled
 		var frm = document.getElementById(form);
 		<?php
 			$import_script = GetImportScript( $objSession->GetVariable('ImportScriptID') );
 			if( ($import_script !== false) && strlen($import_script['required_fields']) > 0 )
 				$required = explode(',', $import_script['required_fields']);
 			else
 				$required = Array();
 			echo "var required_fields = Array('".implode("','", $required)."');\n";
 		?>
 		var form_is_valid = true;
 		if(frm)
 		{ 
 			var i = 0;
 			var field_count = required_fields.length;
 			for(i = 0; i < field_count; i++)
 				form_is_valid &= frm.elements[ required_fields[i] ].value.length ? true : false;
 		}
 		else
 			return false;
 		return form_is_valid;
 	}
 	
 	function import_submit(formname,formaction,action)
 	{
 	  	f = document.getElementById(formname);
 	  	if(f)
 	  	{
 			f.action = formaction;
 			f.Action.value = HasParam(action) ? action : 'Import';
 			f.submit();
 	  	}
 	}
 	
-	function SetPercent(step_id, new_percent, additional, time_str)
+	function SetPercent(step_id, new_percent, current_rec, time_str)
 	{
 		var step_element = document.getElementById(step_id);
 		step_element.innerHTML = new_percent;
 		
 		var add_element = document.getElementById(step_id+'_additional');
-		add_element.innerHTML = additional;
+		
+		StepInfo[step_id]['current'] = current_rec;
+		add_element.innerHTML = '('+StepInfo[step_id]['current']+' of '+StepInfo[step_id]['total']+')';
 		
 		var time_element = document.getElementById('total_time');
-		time_element.innerHTML = time_str;
+		time_element.innerHTML = time_str+'s';
+	}
+	
+	function SetTotal(text)
+	{
+		var txt = document.getElementById('import_totals');
+		if(txt) txt.innerHTML = text;
 	}
 	
 <?php
 	}
 ?>
 	
 	function ChoiseMade(form, radio_name)
 	{
 		// checks if user has selected enabled radio button
 		var frm = document.getElementById(form);
 		if(frm)
 		{
 			var i = 0;
 			var element_count = frm.elements.length;
 			for(i = 0; i < element_count; i++)
 				if(frm[i].type == 'radio' && frm[i].name == radio_name)
 					if(frm[i].checked == true)
 						return frm[i].value;
 
 			return false;	
 		}
 	}
 </script>
\ No newline at end of file

Property changes on: trunk/kernel/admin/include/toolbar/main_import.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/admin/include/elements.php
===================================================================
--- trunk/admin/include/elements.php	(revision 347)
+++ trunk/admin/include/elements.php	(revision 348)
@@ -1,612 +1,612 @@
 
 <?php
 ##############################################################
 ##In-portal :: Administration Interfaces :: Common Elements ##
 ##############################################################
 ##                   In-portal                     			##
 ##             Intechnic Corporation               			##
 ##          All Rights Reserved, 1998-2002            		##
 ##                                           				##
 ## No portion of this code may be copied, reproduced or  	##
 ##    otherwise redistributed without proper written     	##
 ##   consent of Intechnic Corporation.  Violation will      ##
 ##    result in revocation of the license and support    	##
 ##  privileges along maximum prosecution allowed by law. 	##
 ##############################################################
 
 if( !isset($is_install) ) $is_install = false;
 if(!$is_install)
 {
   if (!admin_login())
   {            
     if(!headers_sent()) {
       setcookie("sid"," ",time()-3600);
       echo "Test";
     }
     $objSession->Logout();
     header("Location: ".$adminURL."/login.php");
     die();
 	//require_once($pathtoroot."admin/login.php");
   }
 }
 
 global $admin,$pathtoroot, $objConfig;
 
 if(!strlen($admin))
 {
     $admin = $objConfig->Get("AdminDirectory");
     if(!strlen($admin))
     {
         $admin = "admin";
     }
 }
 
 require_once($pathtoroot.$admin."/include/sections.php");
 
 
 $envar = "env=" . BuildEnv();
 
 /* this function loads the javascript for each module's toolbar */
 function load_module_javascript($sectionname, $skip_modules = Array() )
 {
     global $adminURL, $pathtoroot;
 
     echo "<SCRIPT LANGUAGE=JavaScript1.2 src=\"".$adminURL."/browse/fw_menu.js\"></SCRIPT>\n";
     echo "<SCRIPT LANGUAGE=JavaScript1.2 src=\"".$adminURL."/include/tabs.js\"></SCRIPT>\n";
     echo "<script language=\"JavaScript1.2\" src=\"$adminURL/include/checkarray.js\"></script>\n";
     
     global $objConfig, $ItemTabs;    
     $m = GetModuleArray("admin");
     echo "<!-- ".count($m)."-->";
     foreach($m as $key=>$value)
     {
         $path = $pathtoroot. $value."admin/include/toolbar/".$sectionname.".php";
         if( !in_array($value, $skip_modules) && file_exists($path) )
         {
           echo "\n<!-- $path -->\n";
           include_once($path);
         }
         else
             echo "\n<!-- $path not found -->\n";
     }
 }
 
 function load_module_styles()
 {
     global $objConfig, $ItemTabs,$rootURL,$pathtoroot;
         
     $m = GetModuleArray("admin");
     echo "<!-- module styles (".count($m).")-->";
     foreach($m as $key=>$value)
     {
         $path = $pathtoroot.$value."admin/include/style.css";
 
         if(file_exists($path))
         {
         	$inc = $rootURL.$value."admin/include/style.css";
         	print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$inc\">\n";	
         }
     }
 }
 
 //***********************************
 //Page Header
 function int_header($toolbar=NULL,$NavBarText=NULL,$ExtraTitle=NULL,$onLoad=NULL, $ExtraHead=NULL,$skip_modules=Array())
 {
    global $pathtoroot;
    global $pathtolocal;
    global $section;
    global $objSections;
     global $rootURL;
     global $localURL;
     global $adminURL;
     global $envar;
     global $admin;
     global $metatag;
 	
     $style_sheet_global = $adminURL."/include/style.css";
     $style_sheet_local = $localURL."admin/include/style.css";
 
     $ExtraTitle = htmlentities($ExtraTitle);
     if (is_object($toolbar))
     {
        if(file_exists($pathtolocal."admin/include/toolbar.php"))
           require_once ($pathtolocal."admin/include/toolbar.php");
         //Aray of the preloaded elems
         //$int_toolbar_preload = array();
 
         print "<html><head><title>In-portal</title>\n";
         if(strlen($metatag))
         {        
             print $metatag."\n";            
         }
         else
         {        
             print "<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">\n";
             print "<meta http-equiv=\"Pragma\" content=\"no-cache\">\n";
         }
         print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$style_sheet_global\">\n";
         load_module_styles();
         require_once($pathtoroot.$admin."/include/mainscript.php");
         //require_once($pathtolocal."admin/include/script.js");
 		print $ExtraHead;
         $sectionname = explode(":", $section);
         $sectionname = $sectionname[sizeof($sectionname)-1];
 
         load_module_javascript($sectionname, $skip_modules);
         if(is_object($toolbar))
           print $toolbar->GetInitScript();
         print '</head><body topmargin="0" leftmargin="8" marginheight="8" marginwidth="8" bgcolor="#FFFFFF"';
         //*** Preload toolbar images
         if(strlen($onLoad))
         {    
             print $onLoad;
         }
         else
             print " ONLOAD=\"clear_list_checkboxes();\"";
         
         //*** Preload toolbar images
         if(is_object($toolbar))
         {
           if (strlen($toolbar->Get("CheckClass")))
           {
             print $toolbar->onLoadString().">";
           }
           else
               print " >";
 
           $menufunc = $toolbar->Get("load_menu_func");
           if (strlen($menufunc))
           {
             print "<script language=\"JavaScript1.2\">$menufunc</script>";
           }
         }
         else
             print " >";
     }
     else
     {
         print "<html><head><title>In-Portal </title>";
         print "<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">";
         print "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
         print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$style_sheet_global\">";
         load_module_styles();
         require_once ($pathtoroot.$admin."/include/mainscript.php"); 
         //require_once ($pathtolocal."admin/include/script.js"); 
         $sectionname = explode(":", $section);
         $sectionname = $sectionname[sizeof($sectionname)-1]; 
         load_module_javascript($sectionname); 
 
 
         print "</head><body topmargin=\"0\" leftmargin=\"8\" marginheight=\"8\" marginwidth=\"8\" bgcolor=\"#FFFFFF\">";
     }
 
     if(strlen($section)>0)
     {
       	$objSections->SetCurrentSection($section);
       	$sec = $objSections->GetCurrentSection();
       	if ($sec->Get("notitle") != 1) print $objSections->page_title();
 
     	print $objSections->page_tabs($envar);
 
     	if ($sec->Get("nonavbar") != 1) //Section Navigatior
         	print $objSections->section_header($envar,$NavBarText,$ExtraTitle);
 
     	//Toolbar if appropriate
     	if ( isset($sections[$section]) && ($sections[$section]['toolbar']==1) || ( is_object($toolbar) ) )
           	print $toolbar->Build();
     }
 }//Page Header
 
 // HELP Page Header
 function int_help_header()
 {
    global $pathtoroot;
    global $pathtolocal;
    global $section;
    global $objSections;
     global $rootURL;
     global $localURL;
     global $adminURL;
     global $envar;
     global $admin;
     global $metatag;
 
     $style_sheet_global = $adminURL."/include/style.css";
     $style_sheet_local = $localURL."admin/include/style.css";
 
     $ExtraTitle = htmlentities($ExtraTitle);
     
     // TOOLBAR:
         print "<html><head><title>In-Portal - Help</title>";
         print "<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">";
         print "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
         print "<link rel=\"stylesheet\" type=\"text/css\" href=\"$style_sheet_global\">";
         load_module_styles();
         require_once ($pathtoroot.$admin."/include/mainscript.php"); 
         
         print "</head><body topmargin=\"0\" leftmargin=\"8\" marginheight=\"8\" marginwidth=\"8\" bgcolor=\"#FFFFFF\">";
     
 
     if(strlen($section)>0)
     {
       	$objSections->SetCurrentSection($section);
       	$sec = $objSections->GetCurrentSection();
       	
       	if ($sec->Get("notitle") != 1) print $objSections->page_title();
 		
     	if ($sec->Get("nonavbar") != 1) //Section Navigatior
         	print $objSections->section_header($envar,$NavBarText,$ExtraTitle, true);
     	
     }
 }// HELP Page Header
 
 
 function int_SectionHeader($toolbar=NULL,$onLoad=NULL,$NavBarText=NULL,$ExtraTitle=NULL)
 {
     global $pathtoroot;
     global $pathtolocal;
     global $section, $sections;
     global $objSections;
     global $rootURL;
     global $adminURL,$admin;
     global $localURL;
     global $envar;
     global $b_topmargin;
     if (!isset($b_topmargin))
       $b_topmargin = 8;
 
         $sectionname = explode(":", $section);
         $sectionname = $sectionname[sizeof($sectionname)-1];
         load_module_javascript($sectionname);
         if(is_object($toolbar))
           print $toolbar->GetInitScript();
         print "</head><body topmargin=\"$b_topmargin\" leftmargin=\"8\" marginheight=\"$b_topmargin\" marginwidth=\"8\" bgcolor=\"#FFFFFF\"";
         //*** Preload toolbar images
         if(strlen($onLoad))
         {        
             print $onLoad;
         }
         else 
             print " onload=\"if (clear_checkboxes) clear_checkboxes();\"";
 
    print ">";
      global $b_header_addon;
    
       if (isset($b_header_addon)) echo $b_header_addon;
 
     if(strlen($section)>0)
     {
       $objSections->SetCurrentSection($section);
       $sec = $objSections->GetCurrentSection();
       if ($sec->Get("notitle")!=1)
          print $objSections->page_title();
 
       print $objSections->page_tabs($envar);
 
       //Section Navigatior
       if ($sec->Get("nonavbar")!=1)
       { 
         if (is_null($ExtraTitle))
         	$ExtraTitle = "";
         	        
       	print $objSections->section_header($envar,$NavBarText,$ExtraTitle);
         
       }
       //Toolbar if appropriate
       if( isset($sections[$section]) )
       	if($sections[$section]['toolbar'] == 1 || (is_object($toolbar)) )
           print $toolbar->Build();
     }
 }//Section Page Header
 
 //***********************************
 //SubSection Title
-function int_subsection_title($caption)
+function int_subsection_title($caption, $ColSpan = 5)
 {
    int_table_color(1);
    print <<<END
 
 <!-- Subsection Title -->
  <tr class="subsectiontitle">
-  <td colspan="5">$caption</td>
+  <td colspan="$ColSpan">$caption</td>
  </tr>
 END;
 }
 
 function int_subsection_title_install($caption)
 {
    int_table_color(1);
    print <<<END
 
 <!-- Subsection Title -->
  <tr class="subsectiontitle">
   <td colspan="3">$caption</td>
  </tr>
 END;
 }
 
 function int_subsection_title_ret($caption)
 {
    int_table_color_ret(1);
    $o = "<!-- Subsection Title --><tr class=\"subsectiontitle\"><td colspan=\"5\">$caption</td></tr>";
    return $o;
 }
 
 //SubSection Title
 
 //***********************************
 //Table Alternating colors
 function int_table_color($reset_color=0, $return_result = false)
 {
    static $colorset;
 
    if($reset_color)
    {  $colorset="table_color2";
       return;
    }
 
    if ($colorset == "table_color1")
       $colorset = "table_color2";
    else
       $colorset = "table_color1";
 
    $ret = "class=\"".$colorset."\"";
    if($return_result)
    	return $ret;
    else
    	print $ret;
    
 }//Table Alternating colors
 
 //Table Alternating colors with return
 function int_table_color_ret($reset_color=0)
 { 
    static $colorset;
 
    if($reset_color)
    {  $colorset="table_color2";
       return;
    }
 
    if ($colorset == "table_color1")
       $colorset = "table_color2";
    else
       $colorset = "table_color1";
 
    return "class=\"".$colorset."\"";
 }//Table Alternating colors
 
 
 //***********************************
 //Hint
 function int_hint($caption)
 {
 
    global $imagesURL;
 
    print <<<END
 <table width="100%" border="0" cellspacing="0" cellpadding="2">
   <tr>
   <td>
    <span class="hint"><img src="$imagesURL/smicon7.gif" width="14" height="14" align="absmiddle">$caption</span> 
   <td>
   </tr>
 </table>
 END;
 }//Hint
 
 function int_hint_red($caption)
 {
 
    global $imagesURL;
 
    print <<<END
 <table width="100%" border="0" cellspacing="0" cellpadding="2">
   <tr>
   <td>
    <span class="hint_red">$caption</span> 
   <td>
   </tr>
 </table>
 END;
 }//Hint
 
 //***********************************
 //Navigation String
 function int_nav($caption)
 {
    global $pathtoroot;
     global $imagespath;
 
    print <<<END
 <table width="100%" border="0" cellspacing="0" cellpadding="2" bgcolor="#f0f0f0">
   <tr>
   <td><b class="text"><span class="navbar"><a class="navbar" href="">$caption</a></span></b></td>
  </tr>
 </table>
 END;
 }//Navigation String
 
 
 
 //***********************************
 //Print Out Images
 function int_img($img)
 {
    global $images;
    global $pathtoroot;
     global $imagesURL;
 
    $src = $imagesURL."/".$images[$img]['file'];
     $alt = $images[$img]['alt'];
    $width = $images[$img]['width'];
    $height = $images[$img]['height'];
    $name = $img;
 
    //Set ID if needed
    if ($img == 'img:tool:view')
       $id = "ID=\"viewbutton\"";
 
    print "<img alt=\"$alt\" name=\"$name\" src=\"$src\" width=\"$width\" height=\"$height\" $id border=\"0\" align=\"absmiddle\">";
 
 }//Print Out Images
 
 //***********************************
 //Page Footer
 function int_footer()
 {
   global $objSession;
 
   if($objSession->HasSystemPermission("DEBUG.INFO"))
   {
       //phpinfo();
   } 
    print <<<END
  </body>
 </html>
 END;
 }//Page Footer
 
 
 function HomeEnv()
 {
   global $m_var_list_update;
   
   $m_var_list_update["cat"]=0;
 
   return BuildEnv();
 }
 
 function UpEnv()
 {
   global $m_var_list_update,$objCatList;
 
   $current = $objCatList->CurrentCat();
   $parent = $current->Get("ParentId");  
   $m_var_list_update["cat"]=$parent;
 
   return BuildEnv();
 }
 
 function ModuleInclude($file)
 {
     global $pathtoroot;
 
     $m = GetModuleArray();
     foreach($m as $key=>$value)
     {
         $path = $pathtoroot.$value.$file;
         if(file_exists($path))
         {
             echo "<!-- $path -->";
             @include_once($path);
         }
     }
 }
 
 function MultiEditButtons(&$ToolBar,$next,$prev,$Form,$StatusField, $url,$onClick, $ExtraVar="", $prev_phrase = 'Phrase Not Passed', $next_phrase = 'Phrase Not Passed')
 {   
   global $adminURL;
   
   $ToolBar->Add("divider");
 
   if($prev>-1)
   {
     $MouseOver="swap('moveleft','toolbar/tool_prev_f2.gif');";
 	$MouseOut="swap('moveleft', 'toolbar/tool_prev.gif');";
 	
     $var="env=".BuildEnv()."&en=$prev&lpn=".GetVar('lpn');
     if (strlen($ExtraVar))
 		$var.= $ExtraVar;   
 	
 	if ($onClick != 'LangSubmitMove') {
 		$link = "javascript:edit_submit('$Form','$StatusField','$url',0,'$var');";
   	}
   	else {
   		$link = "javascript:$onClick('$url', '$prev')";
   	}
     $ToolBar->Add("moveleft",$prev_phrase,$link,$MouseOver,$MouseOut,"","toolbar/tool_prev.gif");
   }
   else
   {
     $MouseOver="";
     $MouseOut="";
     //$onClick="";
     $link="#";
     $ToolBar->Add("moveleft",$prev_phrase,"#","","","","toolbar/tool_prev_f3.gif");
 
   }  
   
   if($next>-1)
   {
     $MouseOver="swap('moveright','toolbar/tool_next_f2.gif');";
     $MouseOut="swap('moveright', 'toolbar/tool_next.gif');";
 
     $var="env=".BuildEnv()."&en=$next".( isset($_REQUEST['lpn']) ? '&lpn='.$_REQUEST['lpn'] : '');
     
     if (strlen($ExtraVar))
 		$var.= $ExtraVar;
 
 	if ($onClick != 'LangSubmitMove') {
 		$link = "javascript:edit_submit('$Form','$StatusField','$url',0,'$var');";
   	}
   	else {
   		$link = "javascript:$onClick('$url', '$next')";
   	}
     $ToolBar->Add("moveright",$next_phrase,$link,$MouseOver,$MouseOut,"","toolbar/tool_next.gif");
   }
   else
   {
     $ToolBar->Add("moveright",$next_phrase,"#","","","","toolbar/tool_next_f3.gif");
   }	
 }
 
 function InsertButtons(&$ToolBar, $Buttons = Array(), $params = Array() )
 {
 	foreach($Buttons as $button)
 		switch($button)
 		{	
 			case 'save':
 				$ToolBar->Add(	"img_save", "la_Save", "#",
 								"swap('img_save','toolbar/tool_select_f2.gif');", 
 								"swap('img_save', 'toolbar/tool_select.gif');",
 								"edit_submit('".$params['form']."','".$params['status_field']."','".$params['url']."',1,'&lpn=".$_REQUEST['lpn']."');","tool_select.gif");
 
 				break;
 			case 'cancel':
 				$ToolBar->Add(	"img_cancel", "la_Cancel", "#",
 								"swap('img_cancel','toolbar/tool_cancel_f2.gif');", 
 								"swap('img_cancel', 'toolbar/tool_cancel.gif');",
 								"edit_submit('".$params['form']."','".$params['status_field']."','".$params['url']."',2,'&lpn=".$_REQUEST['lpn']."');","tool_cancel.gif");
 				break;
 			case 'edit':
 				break;
 			case 'delete':
 				break;
 		
 		}
 		
 	
 	
 }
 
 function GetTitle($item_phrase, $tab_phrase, $id)
 {
 	// gets correct caption for editing windows with tabs
 	//echo "In: $item_phrase, $tab_phrase, $id";
 	$is_new = isset($_REQUEST['new']) && ($_REQUEST['new'] == 1) ? 1 : 0; 
 	$text = $is_new ? 'la_Text_Adding' : 'la_Text_Editing';
 	$text = admin_language($text).' '.admin_language($item_phrase);
 	
 	if($is_new == 0) $text .= ' #'.$id;
 	$text .= ' - '.admin_language($tab_phrase);
 	return $text;
 }
 
 function MarkFields($form_name)
 {
 	// mark specified form fields as required
 	?> <script language="JavaScript">MarkAsRequired(document.getElementById("<?php echo $form_name; ?>"));</script> <?php
 }
 ?>

Property changes on: trunk/admin/include/elements.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/admin/import/step4.php
===================================================================
--- trunk/admin/import/step4.php	(revision 347)
+++ trunk/admin/import/step4.php	(revision 348)
@@ -1,224 +1,224 @@
 <?php 
 
 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;
 }
 //echo $pathtoroot;
 //echo $pathtoroot;
 require_once($pathtoroot."kernel/startup.php");
 $rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
 
 $admin = $objConfig->Get("AdminDirectory");
 if(!strlen($admin))
     $admin = "admin";
 
 $localURL=$rootURL."kernel/";
 $adminURL = $rootURL.$admin;
 $imagesURL = $adminURL."/images";
 //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:main_import";
 	
 	//Set Environment Variable
 	$envar = "env=" . BuildEnv();
 	
 	$sec = $objSections->GetSection($section);
 	$objCatToolBar = new clsToolBar();
 
 	//check if the previous input is correct
 	if( $_POST["Action"] == 'checkconn')
 	{
 	    // save supplied connection info
 	    $objSession->SetVariable("import_sql_type",	$_POST["db_sql_type"]);
 	    $objSession->SetVariable("import_server",	$_POST["db_server"]);
 	    $objSession->SetVariable("import_db",		$_POST["db_db"]);
 	    $objSession->SetVariable("import_user",		$_POST["db_user"]);
 	    $objSession->SetVariable("import_pass",		$_POST["db_pass"]);
 	    $objSession->SetVariable("error_importing", '');
 		
 	    // get them for using here
 	    $db_sql_type	=	$objSession->GetVariable("import_sql_type");
 	    $db_server		=	$objSession->GetVariable("import_server");
 	    $db_db			=	$objSession->GetVariable("import_db");
 	    $db_user		=	$objSession->GetVariable("import_user");
 	    $db_pass		=	$objSession->GetVariable("import_pass");
 		
 		// check supplied connection
 	   	$linkconn = ADONewConnection($db_sql_type);
 	    if( !$linkconn->PConnect($db_server, $db_user, $db_pass, $db_db) || !$db_server || !$db_db )
 	    {
 	        $objSession->SetVariable("error_importing","Error: The connection to the DB failed please check your settings");
 	        header('Location: step3.php?'.$envar);
 	   	}
 	    unset($linkconn);
 	}
 	
 	$import_script = GetImportScript( $objSession->GetVariable('ImportScriptID') );
-	
+		
 	$var = "?env=".BuildEnv();
     
     // Previous Button
     $MouseOver = "swap('moveleft','toolbar/tool_prev_f2.gif');";
     $MouseOut = "swap('moveleft', 'toolbar/tool_prev.gif');";
     $link = $adminURL."/import/step3.php".$var;
     $objCatToolBar->Add("moveleft",admin_language("la_ToolTip_Previous")." ".admin_language("la_Text_Step"),$link,$MouseOver,$MouseOut,"","tool_prev.gif");
    
 	// Next Button  
     $MouseOver = "swap('moveright','toolbar/tool_next_f2.gif');";
     $MouseOut = "swap('moveright', 'toolbar/tool_next.gif');";
     
     $formaction = $rootURL.$import_script['module'].'/'.$admin.'/import/'.$import_script['url'].'.php?'.$envar;
     
     $onClick = "if( !CheckFinalForm('import_form') ) alert('Please fill in all of the fields'); else import_submit('import_form','$formaction',''); ";
     $objCatToolBar->Add("moveright",admin_language("la_ToolTip_Next")." ".admin_language("la_Text_Step"),'#',$MouseOver,$MouseOut,$onClick,"tool_next.gif");
   
   	// Header
   	$title = admin_language("la_performing_import")." - ".admin_language("la_Step")." 4";
   	int_header($objCatToolBar,NULL,$title);
 
 ?>
          
 <form id="import_form" name="import_form" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>">
 	<input type="hidden" name="Action" value="m_save_import_config">  
 <table width="100%" border="0" cellspacing="0" cellpadding="4" class="tableborder">
 	<?php int_subsection_title("Matching Fields - Intechnic In-Portal ");  ?>
 <!-- script common fields: begin -->
 <?php
 if( $import_script['id'] == 'in-link' )
 {
 ?>	
 	<tr <?php echo int_table_color(); ?>> 
 		<td width="60%" valign="top"><span class="text"><?php echo admin_language("la_prompt_AdminId"); ?></span></td>
 		<td> 
 			<b><?php echo $objSession->GetVariable("user_admin_names"); ?></b>
 			<input type="hidden" name="user_admin" size="15" class="text" value="<?php echo $objSession->GetVariable("user_admin_values"); ?>">
 			<input type="hidden" name="grouplist1" value="<?php echo $objSession->GetVariable('grouplist1'); ?>">
 			<a href="#"><img src="../images/icon_users_sm.gif" style="cursor:hand;" border="0" onclick="OpenGroupSelector('<?php echo $envar; ?>&en=0&destform=import_form&destfield=grouplist1&Selector=radio');"></a>
 		</td>
 	</tr>
 <?php
 }
 ?>
 	<tr <?php echo int_table_color(); ?>> 
 		<td width="60%" valign="top"><span class="text"><?php echo admin_language("la_prompt_RegUserId"); ?></span></td>
 		<td>
 			<b><?php echo $objSession->GetVariable("user_regular_names"); ?></b>
 			<input type="hidden" name="user_regular" size="15" class="text" value="<?php echo $objSession->GetVariable("user_regular_values"); ?>">
  		    <input type="hidden" name="grouplist2" value="<?php echo $objSession->GetVariable('grouplist2'); ?>">
  		    <a href="#"><img src="../images/icon_users_sm.gif" style="cursor:hand;" border="0" onclick="OpenGroupSelector('<?php echo $envar; ?>&en=0&destform=import_form&destfield=grouplist2&Selector=radio');"></a>
 		</td>
 	</tr>
 	<tr <?php echo int_table_color(); ?>> 
 		<td width="60%" valign="top"><span class="text"><?php 
 			echo admin_language("la_prompt_InitImportCat");                         
             $catid = $objSession->GetVariable('categoryid');
 			$path = prompt_language($objConfig->Get("Root_Name"));
 			if($catid > 0)
 			{
 				$c = $objCatList->GetItemByField('ResourceId', $catid);
 				$path .= "&gt;".$c->GetCachedNavBar();
 			}          
              ?>
 		</td>
 		<td> 
 			<b><?php echo $path; ?></b>
 			<input type="hidden" name="init_cat" size="15" class="text" value="<?php echo $objSession->GetVariable("categoryid"); ?>">
 			<a href="#"><img src="<?php echo $imagesURL; ?>/folder.gif" style="cursor:hand;" border="0" ONCLICK="OpenCatSelector('<?php echo $envar; ?>&source=inlinkimport4&continue_sess=1&destform=import_form&destfield=categorylist&Selector=radio');"></a>
 			<input type="hidden" name="categorylist" value="<?php echo $objSession->GetVariable('categorylist'); ?>">
 		</td>
 	</tr>         
 <!-- script common fields: end -->	
 <!-- script spefific fields: begin -->	
 <?php
 	if( $import_script['id'] == 'in-link' )
 	{
 		if( GetVar('link_image') ) $objSession->SetVariable('link_image', GetVar('link_image') );
 ?>	
 	<tr <?php echo int_table_color(); ?>> 
 		<td width="60%" valign="top"><span class="text"><?php echo admin_language("la_prompt_Import_ImageName"); ?></span></td>
 		<td> 
 			<input type="text" name="link_image" class="text" size="30" value="<?php echo $objSession->GetVariable('link_image'); ?>">
 		</td>
 	</tr>
 <?php
 	}
 	
 	if( $import_script['module'] == 'in-bulletin' )
 	{
 		if( GetVar('bb_prefix') ) $objSession->SetVariable('import_table_prefix', GetVar('bb_prefix') );
 ?>
 	<tr <?php echo int_table_color(); ?>> 
 		<td width="60%" valign="top"><span class="text"><?php echo admin_language("la_prompt_Import_Prefix"); ?></span></td>
 		<td> 
 			<input type="text" name="bb_prefix" class="text" size="30" value="<?php echo $objSession->GetVariable('import_table_prefix'); ?>">
 		</td>
 	</tr>
 <?php
 	}
 ?>
 <!-- script spefific fields: end -->
 </table>
 </form>
 <?php
 int_footer();
 ?>

Property changes on: trunk/admin/import/step4.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/globals.php
===================================================================
--- trunk/globals.php	(revision 347)
+++ trunk/globals.php	(revision 348)
@@ -1,1407 +1,1411 @@
 <?php
 
 $vars = parse_portal_ini($pathtoroot."config.php");
 
 while($key = key($vars))
 {
   $key = "g_".$key;
   global $$key;
   $$key = current($vars); //variable variables
   next($vars);
 }
 
 /*list the tables which contain item data */
 $ItemTables = array();
 
 $KeywordIgnore = array();
 global $debuglevel;
 
 $debuglevel = 0;
 //$GLOBALS['debuglevel'] = 0;
 
 /*New, Hot, Pop field values */
 define('NEVER', 0);
 define('ALWAYS', 1);
 define('AUTO', 2);
 
 /*Status Values */
 define('STATUS_DISABLED', 0);
 define('STATUS_ACTIVE', 1);
 define('STATUS_PENDING', 2);
 
 $LogLevel=0;
 $LogFile = NULL;
 
 
 function parse_portal_ini($file, $parse_section = false) { 
     if(!file_exists($file) && !is_readable($file))  
         die('Could Not Open Ini File'); 
      
     $contents = file($file); 
      
     $retval = array(); 
      
     $section = ''; 
     $ln = 1;
     $resave = false;
     foreach($contents as $line) { 
     		if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
     			$resave = true;
     		}
     		$ln++;
         $line = trim($line); 
         $line = eregi_replace(';[.]*','',$line); 
         if(strlen($line) > 0) { 
             //echo $line . " - "; 
             if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) { 
                 //echo 'section'; 
                 $section = substr($line,1,(strlen($line)-2)); 
                 if ($parse_section) {
                 	$retval[$section] = array(); 
                 }
                 continue;
             } elseif(eregi('=',$line)) { 
                 //echo 'main element'; 
                 list($key,$val) = explode(' = ',$line); 
                 if (!$parse_section) {
                 	$retval[trim($key)] = str_replace('"', '', $val); 
                 }
                 else {
 					$retval[$section][trim($key)] = str_replace('"', '', $val);                 	
                 }
             } //end if 
             //echo '<br />'; 
         } //end if 
     } //end foreach 
     if ($resave) {
     	$fp = fopen($file, "w");
     	reset($contents);
 			fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
 			foreach($contents as $line) fwrite($fp,"$line");
 			fclose($fp);
 		}   
     
     return $retval; 
 }
 
 function &GetADODBConnection()
 {
 	global $g_adodbConnection, $g_DBType, $g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_DebugMode;
     global $ADODB_FETCH_MODE,$ADODB_COUNTRECS,$ADODB_CACHE_DIR,$pathtoroot; 
 	//echo '<pre>'.print_r( debug_backtrace() , true).'</pre>';
     if(!isset($g_adodbConnection) && strlen($g_DBType)>0)
     {
 		$g_adodbConnection = ADONewConnection($g_DBType);
 		
 		$connected = $g_adodbConnection->Connect($g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName);
         if(!$connected)
         {
             echo "Error connecting to database $g_DBHost <br>\n";
             die();
         }
         $ADODB_CACHE_DIR = $pathtoroot."cache"; 
         $ADODB_FETCH_MODE = 2;    
         $ADODB_COUNTRECS = FALSE; 
         $g_adodbConnection->debug = defined('ADODB_OUTP') ? 1 : 0;
         $g_adodbConnection->cacheSecs = 3600;
         $g_adodbConnection->Execute('SET SQL_BIG_SELECTS=1');
     }
     elseif (!strlen($g_DBType)) {
     	global $rootURL;
     	echo "In-Portal is probably not installed, or configuration file is missing.<br>";
 			echo "Please use the installation script to fix the problem.<br><br>";
 			if (!preg_match('/admin/', $_SERVER['SCRIPT_FILENAME'])) {
 				$ins = 'admin/'; 
 			}
 			echo "<a href='$rootURL".$ins."install.php'>Go to installation script</a><br><br>";
 			flush();
 			die();
     }
 	return $g_adodbConnection;
 }
 
 function GetNextResourceId($Increment=1)
 {
 	$sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment;
     $adodbConnection = GetADODBConnection();
     $adodbConnection->Execute($sql);    
     $rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator");
     $val = $rs->fields["lastid"];
     if(!$rs || $rs->EOF)
     {   
     	echo $adodbConnection->ErrorMsg(); 
         $sql = "INSERT INTO ".GetTablePrefix()."IdGenerator (lastid) VALUES ($Increment)";
         $adodbConnection->Execute($sql);
         $val = 1;
     }
     $val = $val-($Increment-1); 
     return $val;
 }
 
 function AddSlash($s)
 {
     if(substr($s,-1) != "/")
     {
         return $s."/";
     }
     else
         return $s;
 }
 
 function StripNewline($s)
 {
 	$bfound = false;
 	while (strlen($s)>0 && !$bfound)
 	{
 		if(ord(substr($s,-1))<32)
 		{
 			$s = substr($s,0,-1);
 		}
 		else
 		  $bfound = true;
 	}
 	return $s;
 }
 
 function DeleteElement($array, $indice) 
 {
   for($i=$indice;$i<count($array)-1;$i++) 
         $array[$i] = $array[$i+1]; 
   unset($array[count($array)-1]);
   return $array;
 }
 
 function DeleteElementValue($needle, &$haystack) 
 {
   while(($gotcha = array_search($needle,$haystack)) > -1)
    unset($haystack[$gotcha]);
 }	
 
 function TableCount($TableName, $where="",$JoinCats=1)
 {
     $db = GetADODBConnection();
     if(!$JoinCats)
     {    
       $sql = "SELECT count(*) as TableCount FROM $TableName";
     }
     else
         $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
     if(strlen($where)>0)
         $sql .= " WHERE ".$where;
    
     $rs = $db->Execute($sql);
         
 //    echo "SQL TABLE COUNT: ".$sql."<br>\n";
     
     $res = $rs->fields["TableCount"];
     return $res;
 }
 
 Function QueryCount($sql)
 {
   $countsql = "SELECT count(*) as TableCount ".substr($sql,strpos($sql," FROM "));
   if(strpos($countsql,"LIMIT"))
     $countsql = substr($countsql,0,strpos($countsql,"LIMIT"));
   if(strpos($countsql,"ORDER BY"))
     $countsql = substr($countsql,0,strpos($countsql,"ORDER BY"));
     
   $db = GetADODBConnection();
   $rs = $db->Execute($countsql);
   //echo $countsql."<br>\n";
   $res = $rs->fields["TableCount"];
   return $res;  
 }
     
 function GetPageCount($ItemsPerPage,$NumItems)
 {
  if($ItemsPerPage==0 || $NumItems==0)
  {
    return 1;
  }            
  $value = $NumItems/$ItemsPerPage;
  return ceil($value);        
 }
 
 
 function GetTablePrefix()
 {
     global $g_TablePrefix;
 
     return $g_TablePrefix;
 }
 
 function TableHasPrefix($t)
 {
 	$pre = GetTablePrefix();
 	
 	if(strlen($pre)>0)
 	{
 		if(substr($t,0,strlen($pre))==$pre)
 		{
 			return TRUE;
 		}
 		else 
 		  return FALSE;
 	}
 	else
 	  return TRUE;
 }
 
 function AddTablePrefix($t)
 {
 	if(!TableHasPrefix($t))
 	  $t = GetTablePrefix().$t;
 	  
 	return $t;
 }
 
 function ThisDomain()
 {
 	global $objConfig, $g_Domain;
 	
 	if($objConfig->Get("DomainDetect"))
 	{
 		$d = $_SERVER['HTTP_HOST'];
 	}
 	else
 	  $d = $g_Domain;
 	  
 	return $d;
 }
 
 function GetIndexUrl($secure=0)
 {
     global $indexURL, $rootURL, $secureURL;
     
     switch($secure)
     {
     	case 0:
     		$ret = $indexURL;
     	break;
     	case 1:
     		$ret = $secureURL."index.php";    		
     	break;	
     	case 2:
     		$ret = $rootURL."index.php";
     	break;
     	default:
     		$ret = $i;    	
     }					
     return $ret;
 }
 
 function GetLimitSQL($Page,$PerPage)
 {
   if($Page<1)
     $Page=1;
 
   if(is_numeric($PerPage))
   {
   	  if($PerPage==0)  	  
   	    $PerPage = 20;
       $Start = ($Page-1)*$PerPage;
       $limit = "LIMIT ".$Start.",".$PerPage;
   }
   else
       $limit = NULL;
   return $limit;
 }
 
 function filelist ($currentdir, $startdir=NULL,$ext=NULL) 
 {
   global $pathchar;
 
   //chdir ($currentdir);
 
   // remember where we started from
   if (!$startdir) 
   {
       $startdir = $currentdir;
   }
 
   $d = @opendir($currentdir);
 
   $files = array();
   if(!$d)
     return $files;  
   //list the files in the dir
   while (false !== ($file = readdir($d))) 
   {
       if ($file != ".." && $file != ".") 
       {
           if (is_dir($currentdir."/".$file)) 
           {
               // If $file is a directory take a look inside
               $a = filelist ($currentdir."/".$file, $startdir,$ext); 
               if(is_array($a))
                 $files = array_merge($files,$a);
           } 
           else 
           {
               if($ext!=NULL)
               {
                   $extstr = stristr($file,".".$ext);
                   if(strlen($extstr))
                       $files[] = $currentdir."/".$file;
               }
               else
                 $files[] = $currentdir.'/'.$file;
           }
       }
   }
 
   closedir ($d);
 
   return $files;
 }        
 
 function DecimalToBin($dec,$WordLength=8)
 {
   $bits = array();
   
   $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
   for($i=$WordLength;$i>0;$i--)
   {
       $bits[$i-1] = (int)substr($str,$i-1,1);
   }
   return $bits;
 }
 
 function inp_escape($in, $html_enable=0)
 {
 	$out = stripslashes($in);
 	$out = str_replace("\n", "\n^br^", $out);
 	if($html_enable==0)
 	{
 		$out=ereg_replace("<","&lt;",$out);
 		$out=ereg_replace(">","&gt;",$out);
 		$out=ereg_replace("\"","&quot;",$out);
 		$out = str_replace("\n^br^", "\n<br />", $out);
 	}	
 	else
 		$out = str_replace("\n^br^", "\n", $out);
 	$out=addslashes($out);
 
 	return $out;
 }
 
 function inp_unescape($in)
 {
 	$out=stripslashes($in);
 
 	return $out;
 }
 
 function inp_textarea_unescape($in)
 {
 	$out=stripslashes($in);
 	$out = str_replace("\n<br />", "\n", $out);
 	return $out;
 }
 
 function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
 {
     global $objConfig;
 
     if(!strlen($OpenTag))
         $OpenTag = "<B>";
     if(!strlen($CloseTag))
             $CloseTag = "</B>";	
 	
    	$r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
    	
    	foreach ($Keywords as $k) {	   	
 	   	for ($i = 0; $i < count($r); $i++) {
 	       if ($r[$i] == "<") {
 	           $i++; continue;
 	       }
 	       $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
 	    }
    	}
    	return join("", $r);
 }
 
 /*
 function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
 {
     global $objConfig;
 
     if(!strlen($OpenTag))
         $OpenTag = "<B>";
     if(!strlen($CloseTag))
             $CloseTag = "</B>";
     $ret = strip_tags($html);
 
     foreach ($Keywords as $k)
     {   
         if(strlen($k))
         {        
           //$html = str_replace("<$k>", ":#:", $html);
           //$html = str_replace("</$k>", ":##:", $html);
           //$html = strip_tags($html);
           if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
           //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
             $ret = $html;
           //$ret = str_replace(":#:", "<$k>", $ret);
           //$ret = str_replace(":##:", "</$k>", $ret);
         }
     }
     return $ret;        
 }
 */
 function ExtractDatePart($part,$datestamp)
 {
     switch($part)
     {
         case "month":
             if($datestamp<=0)
             {                        
                 $ret = "";
             }
             else
               $ret = adodb_date("m",$datestamp);
         break;		
         case "day":
             if($datestamp<=0)
             {                        
                 $ret = "";
             }
             else
                 $ret = adodb_date("d", $datestamp);
         break;		
         case "year":
             if($datestamp<=0)
             {                        
                 $ret = "";
             }
             else
                 $ret = adodb_date("Y", $datestamp);
         break;
         case "time_24hr":
             if($datestamp<=0)
             {                        
                 $ret = "";
             }
             else
                 $ret = adodb_date("H:i", $datestamp);
         break;
         case "time_12hr":
             if($datestamp<=0)
             {
                 $ret = "";
             }
             else
                 $ret = adodb_date("g:i a",$datestamp);
        break;
      }
     return $ret;
 }
 
 function GetLocalTime($TimeStamp,$TargetZone=NULL)
 {
     if($TargetZone==NULL)
         $TargetZone = $objConfig->Get("Config_Site_Time");   
     $server = $objConfig->Get("Config_Server_Time");
     if($TargetZone!=$server)
     {    
       $offset = ($server - $TargetZone) * -1;
       $TimeStamp = $TimeStamp + (3600 * $offset);
     }
     return $TimeStamp;
 }
 
 function _unhtmlentities ($string)
 {
     $trans_tbl = get_html_translation_table (HTML_ENTITIES);
     $trans_tbl = array_flip ($trans_tbl);
     return strtr ($string, $trans_tbl);
 }
 
 function getLastStr($hay, $need){
   $getLastStr = 0;
   $pos = strpos($hay, $need);
   if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
    while($pos) {
      $getLastStr = $getLastStr + $pos + strlen($need);
      $hay = substr ($hay , $pos + strlen($need));
      $pos = strpos($hay, $need);
    }
    return $getLastStr - strlen($need);
   } else {
    return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
   }
 } 
 
 function ReplaceSingleTag($tag,$text)
 {
   $opentag = "[".$tag;
   $closetag = "[/".$tag."]";
   
   if(strstr($text,$opentag))
   {   
     $pos = strpos($text,$opentag." ");
     if($pos === false)
     {
         $pos = strpos($text,$opentag."]");
     }
     $endopen = strpos($text,"]",$pos);
     $closepos = strpos($text,$closetag,$pos);
     
     if($closepos)
     {
         $taglength = ($closepos - $endopen) + strlen($closetag);
         $tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos);       
         $innerText = substr($text,$endopen+1,$closepos - $endopen-1);
         if($tag=="UL")
             $innerText = str_replace("[*]","<LI>",$innerText);
         $tagText = substr($tagText,1,($endopen - $pos)-1);   
         //echo "Matched $tagText <br>\n";
         $tagText = "<".$tagText.">";
         $replace_text = $tagText.$innerText."</".$tag.">";
         $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
         return $text;
     }
     else
         return $text;
   }
   else
       return $text;
 }
 
 function ReplaceTag($tag,$text)
 {
   $new_text = ReplaceSingleTag($tag,$text);
   
   while($new_text != $text)
   {
       $text = $new_text;
       $new_text = ReplaceSingleTag($tag,$text);
   }
   return $new_text;
 }
 
 function ReplaceURL($text)
 {  
   while(strstr($text,"[URL"))
   {
     $urlpos = strpos($text,"[URL");
     $endopen = strpos($text,"]",$urlpos);
     if($endopen)
     {
         $url = "<A TARGET=\"_blank\"".substr($text,$urlpos+4,$endopen - ($urlpos+4));
         $url .= ">";
         $url = _unhtmlentities($url);
         $text = substr($text,0,$urlpos).$url.substr($text,$endopen+1);
     }
   }
   $text = str_replace("[/URL]","</A>",$text);
   return $text;
 }
 
 
 function ReplaceBBCode($text)
 {
   global $objConfig;
 
   $tags = explode(",",$objConfig->Get("BBTags"));
   for($i=0;$i<count($tags);$i++)
   {    
     $text = ReplaceTag(strtoupper($tags[$i]),$text);
   }
   $text = ReplaceURL($text);
   return $text;
 }
 
 function GetMinValue($Table,$Field, $Where=NULL)
 {
     $ret = 0;
     $sql = "SELECT min($Field) as val FROM $Table ";
     if(strlen($where))
         $sql .= "WHERE $Where";
     $ado = GetADODBConnection();
     $rs = $ado->execute($sql);
     if($rs)
         $ret = (int)$rs->fields["val"];
     return $ret;
 }
 
 function getmicrotime()
 { 
     list($usec, $sec) = explode(" ",microtime()); 
     return ((float)$usec + (float)$sec); 
 } 
 
 function SetMissingDataErrors($f)
 {
     global $FormError;
 
     $count = 0;
     if(is_array($_POST))
     {    
       if(is_array($_POST["required"]))
       {      
         foreach($_POST["required"] as $r)
         {
           $found = FALSE;
           if(is_array($_FILES))
           {
             if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
           }
         
           if(!strlen(trim($_POST[$r])) && !$found)
           {           
             $count++;
             
             if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
             	$r = "dob";            	
             	
             $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
             if(!strlen($tag))
               $tag = "lu_ferror_".$f."_".$r; 
             $FormError[$f][$r] = language($tag);
           }
         }
       }
     }
     return $count;
 }
 
 function makepassword($length=10)
 {
   $pass_length=$length; 
 
   $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
   $p2=array('a','e','i','o','u'); 
   $p3=array('1','2','3','4','5','6','7','8','9');   
   $p4=array('(','&',')',';','%');    // if you need real strong stuff 
 
   // how much elements in the array 
   // can be done with a array count but counting once here is faster 
 
   $s1=21;// this is the count of $p1    
   $s2=5; // this is the count of $p2 
   $s3=9; // this is the count of $p3 
   $s4=5; // this is the count of $p4 
 
   // possible readable combinations 
 
   $c1='121';    // will be like 'bab' 
   $c2='212';      // will be like 'aba' 
   $c3='12';      // will be like 'ab' 
   $c4='3';        // will be just a number '1 to 9'  if you dont like number delete the 3 
 // $c5='4';        // uncomment to active the strong stuff 
 
   $comb='4'; // the amount of combinations you made above (and did not comment out) 
 
 
 
   for ($p=0;$p<$pass_length;) 
   { 
     mt_srand((double)microtime()*1000000); 
     $strpart=mt_rand(1,$comb); 
     // checking if the stringpart is not the same as the previous one 
     if($strpart<>$previous) 
     { 
       $pass_structure.=${'c'.$strpart}; 
 
       // shortcutting the loop a bit 
       $p=$p+strlen(${'c'.$strpart}); 
     } 
     $previous=$strpart; 
   } 
 
 
   // generating the password from the structure defined in $pass_structure 
   for ($g=0;$g<strlen($pass_structure);$g++) 
   { 
     mt_srand((double)microtime()*1000000); 
     $sel=substr($pass_structure,$g,1); 
     $pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})]; 
 
   } 
   return $pass; 
 }
 
 function LogEntry($text,$writefile=FALSE)
 {
   global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
   
   static $last;
 
   if(strlen($g_LogFile))
   { 
     $el = str_pad(getmicrotime()- $timestart,10," "); 
     if($last>0)
       $elapsed = getmicrotime() - $last; 
       
     if(strlen($el)>10)
         $el = substr($el,0,10);      
     $indent = str_repeat("  ",$LogLevel);
     $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
     $LogData .= "$el:". round($elapsed,6).":$indent $text";
     $last = getmicrotime();
     if($writefile==TRUE && is_writable($g_LogFile))
     {
       if(!$LogFile)       
       {
          if(file_exists($g_LogFile))
             unlink($g_LogFile);
         $LogFile=@fopen($g_LogFile,"w");
       }
       if($LogFile)
       {    
         fputs($LogFile,$LogData);
       }
     }
   }
 }
 
 function ValidEmail($email) 
 {
     if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
     {
         return TRUE;
     } 
     else 
     {
         return FALSE;
     }
 } 
 
 function language($phrase,$LangId=0)
 {
     global $objSession, $objLanguageCache, $objLanguages;
 
     if($LangId==0)
         $LangId = $objSession->Get("Language");
         
 	if($LangId==0)
       $LangId = $objLanguages->GetPrimary();        
 
     $translation = $objLanguageCache->GetTranslation($phrase,$LangId);
 
     return $translation;
 }
 
 function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
 {
     global $objSession, $objLanguageCache, $objLanguages;
     
 	//echo "Language passed: $lang<br>";
 	
     if($lang==0)
        $lang = $objSession->Get("Language");
 
     //echo "Language from session: $lang<br>";
     
 	if($lang==0)
       $lang = $objLanguages->GetPrimary();   
 	
     //echo "Language after primary: $lang<br>";
     //echo "Phrase: $phrase<br>";
 	$translation = $objLanguageCache->GetTranslation($phrase,$lang);
     if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
     {    	
     	$res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
     	return $res;
     }
     else
     	return $translation;
 }
 
 function prompt_language($phrase,$lang=0)
 {
   return admin_language($phrase,$lang,TRUE);	
 }
 
 function GetPrimaryTranslation($Phrase)
 {
 	global $objLanguages;
 
 	$l = $objLanguages->GetPrimary();
 	return language($Phrase,$l);
 }
 
 function CategoryNameCount($ParentId,$Name)
 {
 	$cat_table = GetTablePrefix()."Category";
 	$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
 	$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
 
 	$ado = GetADODBConnection();
 	$rs = $ado->Execute($sql);
 	$ret = array();
 	while($rs && !$rs->EOF)
 	{
 		$ret[] = $rs->fields["Name"];
 		$rs->MoveNext();
 	}
    	return $ret;
 }	
 
 function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
 {
 	$cat_table = GetTablePrefix()."CategoryItems";
 	$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
 	$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
 	//echo $sql."<br>\n ";
 	$ado = GetADODBConnection();
 	$rs = $ado->Execute($sql);
 	$ret = array();
 	while($rs && !$rs->EOF)
 	{
 		$ret[] = $rs->fields[$Field];
 		$rs->MoveNext();
 	}
    	return $ret;   	
 }
 
 function &GetItemCollection($ItemName)
 {
   global $objItemTypes;
 
   if(is_numeric($ItemName))
   {
   	$item = $objItemTypes->GetItem($ItemName);
   }
   else
     $item = $objItemTypes->GetTypeByName($ItemName);
   if(is_object($item))
   {
   	$module = $item->Get("Module");
   	$prefix = ModuleTagPrefix($module);
   	$func = $prefix."_ItemCollection";
   	if(function_exists($func))
   	{
   	  $var =& $func();
   	}
   }
   return $var;
 }
 
 	  
 function UpdateCategoryCount($ItemTypeName=0,$ListType=NULL)
 {
 	global $objCountCache, $objItemTypes;
 
   	if(is_numeric($ItemTypeName))
   		$item = $objItemTypes->GetItem($ItemTypeName);
   	else
     	$item = $objItemTypes->GetTypeByName($ItemTypeName);
   
   	if(is_object($item))
   	{	
   		$ItemType  = $item->Get("ItemType");
   	
 		$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
 		if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
 		$objCountCache->adodbConnection->Execute($sql);
   	}  
 }
 
 function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
 {
 }
 
 function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
 {
 }
 
 function GetTagCache($module,$tag,$attribs,$env)
 {
     global $objSystemCache, $objSession, $objConfig;
 
     if($objConfig->Get("SystemTagCache"))
     { 
         $name = $tag;
         if(is_array($attribs))
         {    
             foreach($attribs as $n => $val)
             {    
                 $name .= "-".$val;
             }
         }
         $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
     }
     else
         $CachedValue="";
     return $CachedValue;
 }
 
 function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
 {
     global $objSystemCache, $objSession, $objConfig;
 
     if($objConfig->Get("SystemTagCache"))
     {
         $name = $tag;
         if(is_array($attribs))
         {    
             foreach($attribs as $a => $val)
             {    
                 $name .= "-".$val;
             }
         }
         $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
     }
 }
 
 function DeleteTagCache($name,$extraparams, $env="")
 {
     global $objSystemCache, $objConfig;
 
     if($objConfig->Get("SystemTagCache"))
     { 
         $where = "Name LIKE '$name%".$extraparams."'";
         if(strlen($env))
             $where .= " AND Context LIKE $env";
         $objSystemCache->DeleteCachedItem($where);
     }
 }
 
 function ParseTagLibrary()
 {
 	$objTagList = new clsTagList();
 	$objTagList->ParseInportalTags();
 	unset($objTagList);
 }
 
 function GetDateFormat($LangId=0)
 {
   global $objLanguages;	
   
   if(!$LangId)
     $LangId= $objLanguages->GetPrimary();
   $l = $objLanguages->GetItem($LangId);	
   if(is_object($l))
   {
   	$fmt = $l->Get("DateFormat");
   }
   else
     $fmt = "m-d-Y";
   return $fmt;	
 }
 
 function GetTimeFormat($LangId=0)
 {
   global $objLanguages;	
   
   if(!$LangId)
     $LangId= $objLanguages->GetPrimary();
   $l = $objLanguages->GetItem($LangId);	
   if(is_object($l))
   {
   	$fmt = $l->Get("TimeFormat");
   }
   else
     $fmt = "H:i:s";
   return $fmt;	
 }
 
 function LangDate($TimeStamp=NULL,$LangId=0)
 {  
   $fmt = GetDateFormat($LangId);
   $ret = adodb_date($fmt,$TimeStamp);
   return $ret;
 }
 
 function LangTime($TimeStamp=NULL,$LangId=0)
 { 
   $fmt = GetTimeFormat($LangId);
   $ret = adodb_date($fmt,$TimeStamp);
   return $ret;
 }
 
 function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
 {
 	global $objLanguages;
 	
   if(!$LangId)
     $LangId= $objLanguages->GetPrimary();
   $l = $objLanguages->GetItem($LangId);	
   if(is_object($l))
   {
   	$ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
   }
   else 
     $ret = $num;
     
   return $ret;	
 }
 
 function replacePngTags($x, $spacer="images/spacer.gif")
 {
 	global $rootURL,$pathtoroot;
 	
     // make sure that we are only replacing for the Windows versions of Internet
     // Explorer 5+, and not Opera identified as MSIE
     $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
     $opera='/opera\s+[0-9]+/i';
     if(!isset($_SERVER['HTTP_USER_AGENT']) ||
         !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
         preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
         return $x;
     
     // find all the png images in backgrounds
     preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
     for($i=0;$i<count($background[0]);$i++){
         // simply replace:
         //  "background-image: url('image.png');"
         // with:
         //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
         //      enabled=true, sizingMethod=scale src='image.png');"
         // haven't tested to see if background-repeat styles work...
         $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
                 'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
                 ' src=\''.$background[1][$i].'\');',$x);
     }
 
     // OK, time to find all the IMG tags with ".png" in them
     preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
     while(list($imgnum,$v)=@each($images[0])){
         $original=$v;
         $atts=''; $width=0; $height=0;
         // If the size is defined by styles, find
         preg_match_all('/style=".*(width: ([0-9]+))px.*'.
                         '(height: ([0-9]+))px.*"/Ui',$v,$arr2);
         if(is_array($arr2) && count($arr2[0])){
             // size was defined by styles, get values
             $width=$arr2[2][0];
             $height=$arr2[4][0];
         }
         // size was not defined by styles, get values
         preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
         if(is_array($arr2) && count($arr2[0])){
             $width=$arr2[1][0];
         }
         preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
         if(is_array($arr2) && count($arr2[0])){
             $height=$arr2[1][0];
         }
         preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
         if(isset($arr2[1][0]) && !empty($arr2[1][0]))
             $image=$arr2[1][0];
         else
             $image=NULL;
 
         // We do this so that we can put our spacer.gif image in the same
         // directory as the image
         $tmp=split('[\\/]',$image);
         array_pop($tmp);
         $image_path=join('/',$tmp);
            if(substr($image,0,strlen($rootURL))==$rootURL)
            {
           		$path = str_replace($rootURL,$pathtoroot,$image);
            }
           else
           {
         		$path = $pathtoroot."themes/telestial/$image";
           }	
 //        echo "Sizing $path.. <br>\n";
 //        echo "Full Tag: ".htmlentities($image)."<br>\n";        
         //if(!$height || !$width)
         //{
 
           $g = imagecreatefrompng($path);
           if($g)
           {
           	$height = imagesy($g);
           	$width = imagesx($g);
           }	
         //}
         if(strlen($image_path)) $image_path.='/';
 
         // end quote is already supplied by originial src attribute
         $replace_src_with=$spacer.'" style="width: '.$width.
             'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
             'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
             '\'scale\')';
         
         // now create the new tag from the old
         $new_tag=str_replace($image,$replace_src_with,$original);
         
         // now place the new tag into the content
         $x=str_replace($original,$new_tag,$x);
     }
     return $x;
 }
 
 function print_pre($str)
 {
 	// no comments here :)
 	echo '<pre>'.print_r($str, true).'</pre>';
 }
 
 function GetOptions($field) // by Alex
 {
 	// get dropdown values from custom field
 	$tmp =& new clsCustomField();
 	
 	$tmp->LoadFromDatabase($field, 'FieldName');
 	$tmp_values = $tmp->Get('ValueList');
 	unset($tmp);
 	$tmp_values = explode(',', $tmp_values);
 	
 	foreach($tmp_values as $mixed)
 	{
 		$elem = explode('=', trim($mixed));
 		$ret[ $elem[0] ] = $elem[1];
 	}
 	return $ret;
 }
 
 function ResetPage($module_prefix, $page_variable = 'p')
 {
 	// resets page in specific module when category is changed	
 	global $objSession;
 	if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
 	{
 		global $var_list, $SessionQueryString, $FrontEnd;
 		//if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
 		$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
 	}
 	//echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')<br>';
 	$last_cat = $objSession->GetVariable('last_category');
 	$prev_cat = $objSession->GetVariable('prev_category');
 	//echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
 	
 	if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
 }
 
 if( !function_exists('GetVar') )
 {
 	function GetVar($name, $post_priority = false)
 	{
 		if(!$post_priority) // follow gpc_order in php.ini
 			return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
 		else	// get variable from post 1stly if not found then from get
 			return isset($_POST[$name]) && $_POST[$name] ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );	
 	}
 }
 
 function PassVar(&$source)
 {
 	// source array + any count of key names in passed array	
 	$params = func_get_args();
 	array_shift($params);
 	
 	if( count($params) )
 	{
 		$ret = Array();
 		foreach($params as $var_name)
 			if( isset($source[$var_name]) )
 				$ret[] = $var_name.'='.$source[$var_name];
 		$ret = '&'.implode('&', $ret);
 	}
 	return $ret;
 }
 
 function GetSubmitVariable(&$array, $postfix)
 {
 	// gets edit status of module
 	// used in case if some modules share
 	// common action parsed by kernel parser,
 	// but each module uses own EditStatus variable
 	
 	$modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic');
 	foreach($modules as $module => $prefix)
 		if( isset($array[$prefix.$postfix]) )
 			return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
 	return false;
 }
 
 function GetModuleByAction()
 {
 	$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
 	$action = GetVar('Action');
 	if($action)
 	{
 		$module_prefix = explode('_', $action);
 		return $prefix2module[ $module_prefix[0] ];
 	}
 	else
 		return false;
 }
 
 function dir_size($dir) {
    // calculates folder size based on filesizes inside it (recursively)
    $totalsize=0;
    if ($dirstream = @opendir($dir)) {
        while (false !== ($filename = readdir($dirstream))) {
            if ($filename!="." && $filename!="..")
            {
                if (is_file($dir."/".$filename))
                    $totalsize+=filesize($dir."/".$filename);
                
                if (is_dir($dir."/".$filename))
                    $totalsize+=dir_size($dir."/".$filename);
            }
        }
    }
    closedir($dirstream);
    return $totalsize;
 } 
 
 function size($bytes) {
   // shows formatted file/directory size
   $types =  Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
    $current = 0;
   while ($bytes > 1024) {
    $current++;
    $bytes /= 1024;
   }
   return round($bytes,2)." ".language($types[$current]);
 } 
 
 function echod($str)
 {
 	// echo debug output
 	echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';	
 }
 
 
 function PrepareParams($source, $to_lower, $mapping)
 {
 	// prepare array with form values to use with item
 	$result = Array();
 	foreach($to_lower as $field)
 		$result[ $field ] = $source[ strtolower($field) ];
 	
 	if( is_array($mapping) )
 	{
 		foreach($mapping as $field_from => $field_to)
 			$result[$field_to] = $source[$field_from];
 	}
 	
 	return $result;
 }
 
 function GetELT($field, $phrases = Array())
 {
 	// returns FieldOptions equivalent in In-Portal
 	$ret = Array();
 	foreach($phrases as $phrase)
 		$ret[] = admin_language($phrase);
 	$ret = "'".implode("','", $ret)."'";
 	return 'ELT('.$field.','.$ret.')';
 }
 
 function GetModuleImgPath($module)
 {
 	global $rootURL, $admin;
 	return $rootURL.$module.'/'.$admin.'/images';
 }
 
 function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
 {
 	// each action postprocessing stuff from admin
 	if( !isset($_REQUEST[$StatusField]) ) return false;
 	
 	$list =& $GLOBALS[$ListObjectName];
 	if( !is_object($list) ) $list = new $ListClass();
 	$SFValue = $_REQUEST[$StatusField]; // status field value
  	switch($SFValue)
 	{
  		case 1: // User hit "Save" button
     		$list->CopyFromEditTable($IDField);     
     		break;
 		case 2: // User hit "Cancel" button
 			$list->PurgeEditTable($IDField);
 			break;
  	}
 	if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
  	if($SFValue == 1 || $SFValue == 2) $list->Clear();
 }
 
 function GetElem(&$array, $index)
 {
 	// returns array element by index if
 	// such index exists
 	return isset($array[$index]) ? $array[$index] : false;
 }
 
 function MakeHTMLTag($element, $attrib_prefix)
 {
 	$result = Array();
 	$ap_length = strlen($attrib_prefix);
 	foreach($element->attributes as $attib_name => $attr_value)
 		if( substr($attib_name, $ap_length) == $ap_length )
 			$result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
 	return count($result) ? implode(' ', $result) : false;
 }
 
 function GetImportScripts()
 {
 	// return currently installed import scripts	
 	static $import_scripts = Array();
 	if( count($import_scripts) == 0 )
 	{
 		$sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id';
 		$db =& GetADODBConnection();
 		$rs = $db->Execute($sql);
 		while(!$rs->EOF)
 		{
 			$rec =& $rs->fields;
 			$import_scripts[] = Array(	'label' => $rec['is_label'], 'url' => $rec['is_script'], 
 										'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
 										'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
 										'module' => strtolower($rec['is_Module']) );
 			$rs->MoveNext();	
 		}
 	}
 	return $import_scripts;
 }
 
 function GetImportScript($id)
 {
 	$scripts = GetImportScripts();
 	return isset($scripts[$id]) ? $scripts[$id] : false;
 }
 function GetNextTemplate($current_template) 
 { 
 	// used on front, returns next template to make 
 	// redirect to 
 	$dest = GetVar('dest', true); 
 	if(!$dest) $dest = GetVar('DestTemplate', true); 
 	return $dest ? $dest : $current_template; 
 }
 
 
 // functions for dealign with enviroment variable construction
 function GenerateModuleEnv($prefix, $var_list)
 {
 	// globalize module varible arrays
 	$main =& $GLOBALS[$prefix.'_var_list'];
 	$update =& $GLOBALS[$prefix.'_var_list_update'];
 	
 	//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
 	
 	// enshure that we have no empty values in enviroment variable
 	foreach($update as $vl_key => $vl_value)
     	if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
    
     // if update var count is zero, then do nothing
     if(count($update) == 0) return '';
 
     foreach($main as $vl_key => $vl_value)
     	if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
     
 	$ret = Array();
 	foreach($var_list as $var_name)
 		$ret[] = GetEnvVar($prefix, $var_name);
 	
 	return ':'.$prefix.implode('-',$ret);
 }
 
 function GetEnvVar($prefix, $name)
 {
 	// get variable from template variable's list
 	// (used in module parsers to build env string)
 	$main =& $GLOBALS[$prefix.'_var_list'];
 	$update =& $GLOBALS[$prefix.'_var_list_update'];
 	return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
 }
 
+function IsDebugMode()
+{
+	return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0;	
+}
 
 
 ?>

Property changes on: trunk/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19
\ No newline at end of property
+1.20
\ No newline at end of property