<?php
	$ro_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
	require_login( !admin_login() && $Action, 'expired=1', true );

	// permission checking: begin
	$action_mapping =	Array(
								'bb_censorword_edit'	=>	'in-bulletin:configuration_censorship.edit',
								'bb_censorword_add'		=>	'in-bulletin:configuration_censorship.add',
								'bb_censorship_delete'	=>	'in-bulletin:configuration_censorship.delete',
								
								'bb_emoticon_add'		=>	'in-bulletin:configuration_emoticon.add',
								'bb_emoticon_edit'		=>	'in-bulletin:configuration_emoticon.edit',
								'bb_emoticon_delete'	=>	'in-bulletin:configuration_emoticon.delete',
								
								'bb_admin_edit_topic'	=>	'TOPIC.MODIFY|TOPIC.OWNER.MODIFY',
								'bb_topic_delete'		=>	'TOPIC.OWNER.DELETE|TOPIC.DELETE',
								'bb_topic_move_up'		=>	'TOPIC.ADD|TOPIC.MODIFY|TOPIC.OWNER.MODIFY',
								'bb_topic_move_down'	=>	'TOPIC.ADD|TOPIC.MODIFY|TOPIC.OWNER.MODIFY',
								'bb_topic_approve'		=>	'TOPIC.ADD|TOPIC.MODIFY|TOPIC.OWNER.MODIFY',
								'bb_topic_decline'		=>	'TOPIC.ADD|TOPIC.MODIFY|TOPIC.OWNER.MODIFY',
								
								
						);
	checkActionPermission($action_mapping, $Action);
	// permission checking: end
	
	switch($Action)
 	{
		case "m_cat_delete":
        	if($ro_perm) break;
        	if(isset($_POST["catlist"]))
        	{

        		$CatList = $_POST["catlist"];
        		if(is_array($CatList))
        		{
        			for($i=0;$i<count($CatList);$i++)
        			{
        				$c = $CatList[$i];

        				$objTopicList->ClearCategoryItems($c,"CategoryItems");
        			}
        		}
        		else
        		if(is_numeric($CatList))
        		$objTopicList->ClearCategoryItems($CatList,"CategoryItems");
        	}
        	break;

         case "m_paste": /* category paste */
         	if($ro_perm) break;
         	if($PastedCatIds)
         	{
         		foreach($PastedCatIds as $SourceCat => $DestCat)
         		{
         			$objTopicList->Clear();
         			$objTopicList->Query_Topic("CategoryId=$SourceCat");
         			if($objTopicList->NumItems()>0)
         			{
         				foreach($objTopicList->Items as $item)
         				{
         					/* fields from categoryitems table */
         					$item->UnsetField("CategoryId");
         					$item->UnsetField("ItemResourceId");
         					$item->UnsetField("PrimaryCat");
         					$item->UnsetField("CachedNavBar");
         					$item->CopyToNewResource($DestCat);
         					$item->AddToCategory($DestCat);
         				}
         			}
         		}
         	}
         	break;

     /* censorship admin action handlers */
     case "bb_censorword_edit":         
        if($ro_perm) break;
        $WordId = $_POST["CensorshipId"];
        $objCensor = new clsCensorship();
        if(strlen($_POST["badword"]))
          $objCensor->EditWord($WordId,$_POST["badword"],$_POST["replacement"]);
     break;
     case "bb_censorword_add":
        if($ro_perm) break;
        $objCensor = new clsCensorship();
        if(strlen($_POST["badword"]))
          $objCensor->AddWord($_POST["badword"],$_POST["replacement"]);
     break;
     case "bb_censorship_delete":
        if($ro_perm) break;
        $objCensor = new clsCensorship();
        foreach($_POST["itemlist"] as $wordid)
        {
          $objCensor->DeleteWord($wordid);   
        }
     break;

     /* emoticon action handlers */
     case "bb_emoticon_add":
        if($ro_perm) break;
        //$objSmileys = new clsEmoticonList();
        $file = $_FILES["EmoticonFile"];
        if(is_array($file))
        { 
          if($file["size"]>0)
          {
              $objSmileys->UploadEmoticon($file,$_POST["Name"],$_POST["KeyStroke"],(int)$_POST["Enabled"]);
          }
        }
     break;
    case "bb_emoticon_edit":
    	if($ro_perm) break;        
         //$objEmoticons = new clsEmoticonList();
         $file = $_FILES["EmoticonFile"];         
        
         $e = $objSmileys->EditEmoticon($_POST["EmoticonId"],$_POST["Name"],$_POST["KeyStroke"],-1,$_POST["Enabled"]);
         $img = $e->GetImageObject();
         if(is_array($file))
         { 
           if($file["size"]>0)
           { 
             $localpath = $img->StoreUploadedImage($file,1, "in-bulletin/images/emoticons/",0);
             $img->Set("LocalPath",$localpath);                        
             $img->Set("ThumbPath",$localpath);
             $img->Update();
           }
         }         
         $e->Update();         
     break;
    case "bb_emoticon_delete":
    	if($ro_perm) break;
        //$objEmoticons = new clsEmoticonList();
        foreach($_POST["itemlist"] as $id)
        {
          $objSmileys->DeleteEmoticon($id);   
        }
     break;

    case "bb_topic_delete":
    	if($ro_perm) break;
    	$thiscat =& $objCatList->GetItem($objCatList->CurrentCategoryID());
    	$perm = $objSession->HasCatPermission("TOPIC.DELETE");
    	if(is_array($_POST["topiclist"]))
    	{
    		$cat_ids = Array();
    		foreach($_POST["topiclist"] as $topicid)
    		{
    			$t =& $objTopicList->GetItem($topicid);
    			$cat_ids[$t->GetPrimaryCategory()] = $t->GetPrimaryCategory();
    			if (($objSession->Get("PortalUserId") == $t->Get("OwnerId"))  || ($perm==1))
    			{
    				if(is_object($t))
    				{
    					$objTopicList->Delete_Item($topicid);
    				}
    			}
    		}
    	}
    	else
    	{
    		$t = $objTopicList->GetCurrentTopic();
    		$cat_ids = $t->GetPrimaryCategory();
    		if(is_object($t))
    		{
    			$objTopicList->Delete_Item($t->Get("TopicId"));
    			unset($t);
    		}
    	}
    	
    	/*foreach($cat_ids as $cat_id)
    	{
    		$t->refreshLastUpdate($cat_id);
    	}*/
    	
    	UpdateCategoryCount('topic', $cat_ids, $objTopicList->GetListTypes());
//    	UpdateCategoryCount('posting', $cat_ids, $objPostingList->GetListTypes());
//    	$objTopicList->ResetCache( $objCatList->CurrentCategoryID() );
    	$objPostingList->ResetCache( $objCatList->CurrentCategoryID() );
		break;
		
    case "bb_topic_move_up":
    	if($ro_perm) break;
    	if (isset($_POST["topiclist"]))
    	foreach($_POST["topiclist"] as $id)
    	{
    		$a = $objTopicList->GetItem($id);
    		$a->MoveUp();
    	}
    	break;

    case "bb_topic_move_down":
    	if($ro_perm) break;
    	if (isset($_POST["topiclist"]))
    	{
    		$topiclist=array_reverse($_POST["topiclist"]);
    		foreach($topiclist as $id)
    		{
    			$a = $objTopicList->GetItem($id);
    			$a->MoveDown();
    		}
    	}
    	break;
    	
    case "bb_topic_approve":
    	if($ro_perm) break;
    	if (isset($_POST["topiclist"]))
    	{
    		foreach($_POST["topiclist"] as $id)
    		{
    			$a = $objTopicList->GetItem($id);
    			$a->Approve();
    		}
    	}
    	break;
    case "bb_topic_decline":
    	if($ro_perm) break;
        if (isset($_POST["topiclist"]))
        {         
            foreach($_POST["topiclist"] as $id)
            {
                $a = $objTopicList->GetItem($id);
                $a->Deny();
            }         
        }
    	break; 
    	
    case "bb_topic_cut":
    	if($ro_perm) break;
    	if(isset($_POST["topiclist"]))
    	{
    		$objTopicList->CopyToClipboard("CUT","ResourceId",$_POST["topiclist"]);
    	}
    	break;
    	
    case "bb_topic_copy":
    	if($ro_perm) break;
    	if(isset($_POST["topiclist"]))
    	{
    		$objTopicList->CopyToClipboard("COPY","ResourceId",$_POST["topiclist"]);
    	}
    	break;
    
    // Used from JS
    case "topic_paste":
    	if($ro_perm) break;
    	if($objTopicList->ItemsOnClipboard()>0)
    	{
    		$objTopicList->PasteFromClipboard($objCatList->CurrentCategoryID(),"TopicText");
    		UpdateCategoryCount("Topic",0);
    	}
    	break;

    case "bb_admin_edit_topic":
    	$application =& kApplication::Instance();
        $application->SetVar('bb_mode', 't');       
        $objEditItems = new clsTopicList($_POST["CategoryId"]);
        $objEditItems->SourceTable = $objSession->GetEditTable("Topic");
        $html = (int)$_POST["html_enable"];

        $Status = (int)$_POST["status"];
        $Hot=(int)$_POST["itemhot"];
        $Pop = (int)$_POST["itempop"];      
        $New = (int)$_POST["itemnew"];
        $Pick = (int)$_POST["topic_pick"];
        
        $Notify = (int)$_POST["topic_notify_owner"];
        $CreatedOn = DateTimestamp($_POST["topic_created"],GetDateFormat(0, true)); 
        $CreatedOn += SecondsSinceMidnight($_POST["topic_created_time"]);

        $ModifiedOn = DateTimestamp($_POST["topic_modified"],GetDateFormat(0, true)); 
        $ModifiedOn += SecondsSinceMidnight($_POST["topic_modified_time"]);        
        $Priority = (int)$_POST["Priority"];
        
	      $posted_hits = $_POST['topic_views_show'];
	      
	      $posted_hits_arr = explode('.', $_POST['topic_views']);
	      
	      
	      $save_hits = $_POST['topic_views'];
	      if ($posted_hits_arr[0] != $posted_hits) {
	      	$save_hits = $posted_hits;
	      }        
        
        //$TopicId,$TopicSubject,$User,$CategoryId,$Pending,$Visible,$Pick,$OwnerNotify,$CreatedOn,$ModifedOn
        $l = $objEditItems->Edit_Topic($_POST["TopicId"],inp_escape($_POST["bb_topic_subject"],$html),
                                  $objSession->Get("PortalUserId"),$Status,$Pick, $New, $Hot,
                                  $Pop, $Notify,$CreatedOn,$ModifiedOn,$_POST["topic_rating"],
                                  (int)$_POST["topic_votes"],$save_hits, $Priority,$_POST["topic_poster"], $_POST['lock_topic'],
                                  GetVar('auto_filename'), GetVar('filename') );
	
		saveCustomFields('bb', $l->Get('ResourceId'), 3);
                                  
        if($_POST["EditStatus"]==1)
        {
            $objTopicList->CopyFromEditTable("TopicId");
            $objTopicList->Clear();
        }
        /* user hit the cancel button */
        if($_POST["EditStatus"]==2)
        {
            $objTopicList->PurgeEditTable("TopicId");
            $objTopicList->Clear();
        }
    break;
     case "bb_add_category":
         $objEditItems = new clsTopicList();
         $objEditItems->SourceTable = $objSession->GetEditTable("Topic");
         $r = $_POST["ResourceId"];
         $i = $objEditItems->GetItemByField("ResourceId",$_POST["ResourceId"]);
         $Primary = $i->GetPrimaryCategory($objSession->GetEditTable("CategoryItems"));
         $objSession->SetVariable("HasChanges", 1);
         if(is_object($i))
         {
                 $table = $objSession->GetEditTable("CategoryItems");
                 $CatList = explode(",",$_POST["CatList"]);
                 
                 // Get List of currect categories article is in
                 $link_cats = $i->CategoryMemberList($table);
                 $link_cats_arr = explode(",", $link_cats); 
                 
                 if (count($CatList))
                 {             
	                 for($j=0; $j < count($CatList);$j++)
	                 {
	                    if($CatList[$j])
	                    {                    
	                      $c = $objCatList->GetByResource($CatList[$j]);
	                      $cat = $c->Get("CategoryId");
	                      
	                      if(($cat>0) && !in_array($cat, $link_cats_arr))
	                      {                  
	                        $i->AddToCategory($cat,$table);
	                      }
	                    }
	                 }   
                 }
             }
     break;            
     case "bb_cat_delete":        
     	 $objSession->SetVariable("HasChanges", 1);
         $objEditItems = new clsTopicList();
         $objEditItems->SourceTable = $objSession->GetEditTable("Topic");
         $table = $objSession->GetEditTable("CategoryItems");
         $r = $_POST["ResourceId"];
         $i = $objEditItems->GetItemByField("ResourceId",$_POST["ResourceId"]);
         if(is_object($i))
         {
             $CatCount = $i->CategoryMemberCount($table);
             $Primary = $i->GetPrimaryCategory();
             if($CatCount==count($CatList))
             {
               $sql = "DELETE FROM $table WHERE CategoryId=$cat AND ItemResourceId=$r AND PrimaryCat=0";
               $ado->Execute($sql);
             }
             else
             {             
               $CatList = $_POST["itemlist"];
               $ado = &GetADODBConnection();
               for($x=0;$x<count($CatList);$x++)
               {                 
                 $cat = $CatList[$x];
                 if(is_numeric($cat))
                 {                  
                     if($cat!=$Primary)
                     {                     
                       $sql = "DELETE FROM $table WHERE CategoryId=$cat AND ItemResourceId=$r";
                       if((int)$_GLOBALS["debuglevel"])
                           echo $sql;
                       $ado->Execute($sql);
                       $CatCount--;
                     }
                 }                 
               }

               for($x=0;$x<count($CatList);$x++)
               {                 
                 $cat = $CatList[$x];
                 if(is_numeric($cat>0))
                 {                  
                     if($cat==$Primary && $CatCount>1)
                     {                     
                       $sql = "DELETE FROM $table WHERE CategoryId=$cat AND ItemResourceId=$r";
                       if((int)$_GLOBALS["debuglevel"])
                           echo $sql;
                       $ado->Execute($sql);
                       $CatCount--;
                     }
                 }                 
               }
             }
         }
     break;

	case 'bb_primary_cat':
			// change primary category of the link
			$objEditItems = new clsTopicList();
            $objEditItems->SourceTable = $objSession->GetEditTable("Topic");
            $topic = $objEditItems->GetItemByField('ResourceId', $_REQUEST['ResourceId']);
			if( is_object($topic) )
			{
				$new_cat = array_shift($_REQUEST['itemlist']);
				$ci_table = $objSession->GetEditTable('CategoryItems');
				$topic->SetPrimaryCategory($new_cat, $ci_table);
			}
			break;

	case "pm_new":
		if($ro_perm) break;
		$ToId = $objUsers->GetUserId($_POST["pm_to"]);		
		if ($ToId != "" || $ToId != 0)
		{		
			if($sig)
			{
				//$u = new $objUsers->GetUser(PortalUser($currentUserSession->Get("UserId"));
				$sig_text = $objCurrentUser->GetCustom("Signature");
				$pm_text.="\n\n".$sig_text;
			}

			Add_PrivateMessage(inp_escape($_POST["pm_subject"]), inp_escape($_POST["pm_text"]), $ToId, $_POST["sendbody"]);
		}
		else
			Permission_Error("The User Name you specified cannot be found.  Please hit back and correct the name.");
		
	break;
	case "pm_reply":
		if($ro_perm) break;
		$TopicId = $bb_var_list["top"];
		$pmtext = $_POST["pm_text"];
		if ($TopicId)
		{		
			if($_POST["sig"])
			{
				//$u = new PortalUser($currentUserSession->Get("UserId"));
				$sig_text = $objCurrentUser->GetCustom("Signature");
				$pmtext.="\n\n".$sig_text;
			}

			Reply_PrivateMessage(inp_escape($pmtext), GetMessageId($TopicId), GetToId($TopicId), $_POST["sendbody"]);
		}
		else
			Permission_Error("Error:");
		break;
	
	case "pm_delete":
		if($ro_perm) break;		
		Delete_PrivateMessage($bb_var_list["post"]);
		break;

	case "bb_jump_forum":
		$m_var_list["cat"]=$forum;
		$m_var_list_update["cat"]=$forum;
		$env=BuildEnv();
	break;
    
	case "bb_viewsetting":
		$objSession->SetPersistantVariable($fieldname, $varvalue);
        break;
    case "bb_search_simple_topics":
        m_category_SimpleSearch($_POST["keywords"],$_POST["cat_scope"],$_POST["sortorder"]);
        bb_Search_SimpleQuery($_POST["keywords"],$_POST["cat_scope"],$_POST["sortorder"]);
        break;
    case "bb_add_review":
    	if($ro_perm) break;
    	$CreatedOn = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
    	$Pending = 0;
    	$ReviewText = inl_escape($_POST["reviewtext"]);
    	$id = $bb_var_list["top"];
    	$userid = $objSession->Get("PortalUserId");

    	$n = $objTopicList->GetItem($id);
    	$n->Reviews->Add(0,$CreatedOn,$ReviewText,$Pending,$REMOTE_ADDR,$id,3,$userid);
    	break;
    
    case "bb_rate_topic":
    	if($ro_perm) break;
    	$id = $bb_var_list["top"];
    	$vote = $_POST["form_rate_vote"];
    	$n = $objTopicList->GetItem($id);
    	$notes = $_POST["form_rate_notes"];
    	$n->SubmitVote($vote,$notes);
    	break;
 }

if( ! $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY") )
{
	if( GetVar('TopicEditStatus') == 1 )
	{
		$topic_ids = $objTopicList->CopyFromEditTable("TopicId");
		if ($topic_ids) {
			$objCustomDataList->CopyFromEditTable('bb');
		}
	     $objTopicList->Clear();
	     $objImages = new clsImageList();
	     $objImages->CopyFromEditTable("ImageId");
	     UpdateCategoryCount("Topic",0);
	}
	 /* user hit the cancel button */
	if( GetVar('TopicEditStatus') == 2 )
	{
	     $objTopicList->PurgeEditTable("TopicId");
	     $objTopicList->PurgeCatListEditTable();
	     $objCustomDataList->PurgeEditTable('bb');
	     $objTopicList->Clear();
	     $objImages = new clsImageList();
	     $objImages->PurgeEditTable("ImageId");
	}
}
?>