Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 10:51 PM

in-portal

Index: trunk/kernel/action.php
===================================================================
--- trunk/kernel/action.php (revision 406)
+++ trunk/kernel/action.php (revision 407)
@@ -1,2268 +1,2277 @@
<?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><br>';
}
unset($script, $skip_debug);
}
switch($Action)
{
case "m_save_import_config":
// Set New Import Category
- if( GetVar('categorylist', true) )
+ if( GetVar('categorylist', true) !== false )
{
$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() );
- }
+
+ if($cat_id > 0)
+ {
+ $cat = $objCatList->GetByResource($cat_id);
+ if(is_object($cat))
+ {
+ $navbar = $cat->Get('CachedNavbar');
+ $objSession->SetVariable('catnavbar', $navbar);
+ $objSession->SetVariable('import_category_id', $cat->UniqueId() );
+ }
+ }elseif($cat_id == 0)
+ {
+ global $objConfig;
+ $objSession->SetVariable('import_category_id', 0);
+ }
+
$objSession->SetVariable('categorylist', $_POST['categorylist']);
}
// Set Import Admin Group
if( GetVar('grouplist1', true) )
{
$group_id = $_POST['grouplist1'];
$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( GetVar('grouplist2', true) )
{
$group_id = $_POST['grouplist2'];
$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 = time();//DateCurrTimeTimstamp($_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], 0);
}
}
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":
$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();
$NewId = $ado->GetOne('SELECT MIN(RelationshipId) as MinValue FROM '.$RelList->SourceTable);
if($NewId > 0) $NewId = 0;
$NewId--;
$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 = GetVar('cat_pick', true);
$Status = (int)$_POST["status"];
$Hot = false; //(int)$_POST["itemhot"];
$Pop = false; //(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();
$NewId = $ado->GetOne('SELECT MIN(ImageId) as MinValue FROM '.$objImageList->SourceTable);
if($NewId > 0) $NewId = 0;
$NewId--;
$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 ParentId 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.37
\ No newline at end of property
+1.38
\ No newline at end of property
Index: trunk/kernel/admin/include/toolbar/catselect.php
===================================================================
--- trunk/kernel/admin/include/toolbar/catselect.php (revision 406)
+++ trunk/kernel/admin/include/toolbar/catselect.php (revision 407)
@@ -1,685 +1,688 @@
<?php
global $objConfig,$objSections,$section, $rootURL,$adminURL, $admin, $imagesURL,$envar,
$m_var_list_update,$objCatList, $homeURL, $upURL, $objSession,$CatScopeClause,$DefaultTab;
global $CategoryFilter,$TotalItemCount;
global $Bit_All,$Bit_Pending,$Bit_Disabled,$Bit_New,$Bit_Pop,$Bit_Hot,$Bit_Ed;
global $hideSelectAll;
/* bit place holders for category view menu */
$Bit_Active=64;
$Bit_Pending=32;
$Bit_Disabled=16;
$Bit_New=8;
$Bit_Pop=4;
$Bit_Hot=2;
$Bit_Ed=1;
if( GetVar('SetTab') )
{
if($_GET["SetTab"] != "categories")
{
$m_tab_CatTab_Hide = 1;
$DefaultTab = $_GET["SetTab"];
}
else
{
$DefaultTab="categories";
$m_tab_CatTab_Hide = 0;
}
}
else
$m_tab_CatTab_Hide = (int)$objConfig->Get("CatTab_Hide");
$CategoryView = $objConfig->Get("Category_View");
if(!is_numeric($CategoryView))
{
$CategoryView = 127;
}
$Category_Sortfield = $objConfig->Get("Category_Sortfield");
if(!strlen($Category_Sortfield))
$Category_Sortfield = "Name";
$Category_Sortorder = $objConfig->Get("Category_Sortorder");
if(!strlen($Category_Sortorder))
$Category_Sortorder = "desc";
$Perpage_Category = (int)$objConfig->Get("Perpage_Category");
if(!$Perpage_Category)
$Perpage_Category="'all'";
if($CategoryView == 127)
{
$Category_ShowAll = 1;
}
else
{
$Category_ShowAll=0;
$Status = array();
$Mod = array();
if($CategoryView & $Bit_Pending)
$Status[] = STATUS_PENDING;
if($CategoryView & $Bit_Active)
$Status[] = STATUS_ACTIVE;
if($CategoryView & $Bit_Disabled)
$Status[] = STATUS_DISABLED;
if(count($Status))
{
$CategoryFilter .= " AND (Status IN (".implode(",",$Status).") ";
}
else
$CategoryFilter .= " AND ((Status=-1) ";
if($CategoryView & $Bit_Ed)
{
$CategoryFilter .= " OR (EditorsPick=1) ";
}
if($CategoryView & $Bit_New)
{
$cutoff = adodb_date("U") - ($objConfig->Get("Category_DaysNew") * 86400);
$CategoryFilter .= " OR (CreatedOn > ".$cutoff.") ";
}
$CategoryFilter .= ")";
}
$list = $objSession->GetVariable("SearchWord");
if(strlen($list))
{
$CatScope = $objSession->GetVariable("SearchScope");
switch($CatScope)
{
case 0 :
$CatScopeClause = "";
break;
case 1:
$cat = $objCatList->CurrentCategoryID();
if($cat>0)
{
$allcats = $objCatList->AllSubCats($cat);
if(count($allcats)>0)
{
$catlist = implode(",",$allcats);
$CatScopeClause = " CategoryId IN ($catlist) ";
}
}
break;
case 2:
$CatScopeClause = "CategoryId=".$objCatList->CurrentCategoryID();
break;
}
}
else
$CatScopeClause="";
$mnuClearSearch = language("la_SearchMenu_Clear");
$mnuNewSearch = language("la_SearchMenu_New");
$mnuSearchCategory = language("la_SearchMenu_Categories");
$lang_New = language("la_Text_New");
$lang_Hot = language("la_Text_Hot");
$lang_EdPick = language("la_prompt_EditorsPick");
$lang_Pop = language("la_Text_Pop");
$lang_Rating = language("la_prompt_Rating");
$lang_Hits = language("la_prompt_Hits");
$lang_Votes = language("la_prompt_Votes");
$lang_Name = language("la_prompt_Name");
$lang_Categories = language("la_ItemTab_Categories");
$lang_Description = language("la_prompt_Description");
$lang_MetaKeywords = language("la_prompt_MetaKeywords");
$lang_SubSearch = language("la_prompt_SubSearch");
$lang_Within = language("la_Text_Within");
$lang_Current = language("la_Text_Current");
$lang_Active = language("la_Text_Active");
$lang_SubCats = language("la_Text_SubCats");
$lang_SubItems = language("la_Text_Subitems");
$destform = $_GET["destform"];
$destfield = $_GET["destfield"];
print <<<END
<script language="JavaScript">
var Category_Sortfield = '$Category_Sortfield';
var Category_Sortorder = '$Category_Sortorder';
var Category_Perpage = $Perpage_Category;
var Category_ShowAll = $Category_ShowAll;
var CategoryView = $CategoryView;
var default_tab = "$DefaultTab";
//JS Language variables
var lang_New = "$lang_New";
var lang_Hot = "$lang_Hot";
var lang_EdPick = "$lang_EdPick";
var lang_Pop = "$lang_Pop";
var lang_Rating = "$lang_Rating";
var lang_Hits = "$lang_Hits";
var lang_Votes = "$lang_Votes";
var lang_Name = "$lang_Name";
var lang_Categories = "$lang_Categories";
var lang_Description = "$lang_Description";
var lang_MetaKeywords = "$lang_MetaKeywords";
var lang_SubSearch = "$lang_SubSearch";
var lang_Within="$lang_Within";
var lang_Current = "$lang_Current";
var lang_Active = "$lang_Active";
var lang_SubCats = "$lang_SubCats";
var lang_SubItems = "$lang_SubItems";
var m_tab_CatTab_hide = $m_tab_CatTab_Hide;
var hostname = '$rootURL';
var env = '$envar';
var actionlist = new Array();
var homeURL = "$homeURL";
var upURL = "$upURL";
var Categories_Paste = false;
function InitPage()
{
addCommonActions();
initToolbar('mainToolBar', actionHandler);
initCheckBoxes();
toggleMenu();
}
function AddButtonAction(actionname,actionval)
{
var item = new Array(actionname,actionval);
actionlist[actionlist.length] = item;
}
function actionHandler(button)
{
//alert('a button has been pressed!');
for(i=0; i<actionlist.length;i++)
{
a = actionlist[i];
if(button.action==a[0])
{
//alert('Button action '+a[0]+' is '+a[1]);
eval(a[1]);
break;
}
}
}
function addCommonActions()
{
AddButtonAction('upcat',"get_to_server(upURL,'');");// UP
AddButtonAction('homecat',"get_to_server(homeURL,'');"); //home
AddButtonAction('select',"select_check_submit();"); //edit
AddButtonAction('stop',"window.close();"); //delete
AddButtonAction('print',"window.print();"); //print ?
AddButtonAction('view',"toggleMenu(); window.FW_showMenu(window.cat_menu,getRealLeft(button) - ((document.all) ? 6 : -2),getRealTop(button)+32);");
AddButtonAction('search_a',"setSearchMenu(); window.FW_showMenu(window.SearchMenu,getRealLeft(button)-134 - ((document.all) ? 8 : -1),getRealTop(button)+22);");
AddButtonAction('search_b',"search_submit();");
AddButtonAction('search_c',"new_search_submit();");
}
function AdminCatNav(url)
{
f = document.getElementById("admin_search");
if(f)
{
f.action = url;
new_search_submit();
}
}
- function CheckList(tabId)
- {
- var result="";
-
- if(toolbar)
- {
- var tab = document.getElementById(tabId);
- if (!tab) return;
- var inputs = tab.getElementsByTagName("INPUT");
- for (var j = 0; j < inputs.length; j++)
- if (((inputs[j].type == "checkbox") || (inputs[j].type == "radio")) && (inputs[j].inportalType))
- {
- if(inputs[j].checked)
- result = result + inputs[j].value+',';
- }
- return result;
- }
- }
+ function CheckList(tabId)
+ {
+ var result = "";
+ var ItemsChecked = 0;
+ if(toolbar)
+ {
+ var tab = document.getElementById(tabId);
+ if (!tab) return;
+ var inputs = tab.getElementsByTagName("INPUT");
+ for (var j = 0; j < inputs.length; j++)
+ if( ((inputs[j].type == "checkbox") || (inputs[j].type == "radio")) && (inputs[j].inportalType) )
+ {
+ if(inputs[j].checked)
+ {
+ result = result + inputs[j].value+',';
+ ItemsChecked++;
+ }
+ }
+ return (ItemsChecked == 0) ? 0 : result;
+ }
+ }
function select_check_submit()
{
var formname = '';
//var f = document.getElementById('categories_name_form');
var f = document.getElementById('categories_form');
var bf = window.opener.document.getElementById('$destform');
if(bf)
{
try{
item_id = LastCheckedItem.value;
item_type = LastCheckedItem.getAttribute('ItemType');
}
catch(err)
{
}
bf.$destfield.value = CheckList('categories');
bf.submit();
window.close();
}
} // check submit
function search_submit()
{
f = document.getElementById("admin_search");
if(f)
{
//alert('Setting SearchWord to ' + f.value);
f.Action.value = "m_SearchWord";
f.submit();
}
}
function new_search_submit()
{
var newSearchInput = document.getElementById("NewSearch");
if (newSearchInput) newSearchInput.value = 1;
search_submit();
}
function ClearSearch()
{
//alert('Clearing Search');
f = document.getElementById("admin_search");
if(f)
{
f.Action.value = "m_ClearSearch";
f.submit();
}
}
function SetSearchType(value)
{
f = document.getElementById("admin_search");
if(f)
{
f.SearchType.value = value;
}
}
function SetSearchScope(value)
{
f = document.getElementById("admin_search");
if(f)
{
f.SearchScope.value = value;
}
}
function ToggleNewSearch()
{
f = document.getElementById("admin_search");
if(f)
{
value = f.NewSearch.value;
if(value==1)
{
f.NewSearch.value=0;
}
else
f.NewSearch.value=1;
}
}
function isNewSearch()
{
f = document.getElementById("admin_search");
if(f)
{
return f.NewSearch.value;
} else return 0;
}
function get_to_server(path,attr)
{
if(attr.length>0)
path = path + '?'+attr;
//alert(path);
window.location.href=path;
return true;
}
function check_submit(page,actionValue)
{
if (actionValue.match(/delete$/)) {
if (!theMainScript.Confirm(lang_DeleteConfirm)) return;
}
var formname = '';
if ((activeTab) && (!isAnyChecked('categories')))
{
form_name = activeTab.id;
action_prefix = activeTab.ActionPrefix;
if(page.length==0)
page = activeTab.EditURL;
}
else
{
form_name = 'categories';
action_prefix = 'm_cat_';
if(page.length==0)
page="$admin" + '/category/addcategory';
}
var f = document.getElementById(form_name+'_form');
if(f)
{
f.Action.value = action_prefix + actionValue;
f.action = '$rootURL' + page + '.php?'+ env;
//alert(f.name+ ' is submitting to '+ f.action + ' action=' + f.Action.value);
f.submit();
}
} // check submit
function flip_current(field_suffix)
{
if(activeTab)
{
field = activeTab.getAttribute("tabTitle")+field_suffix;
return flip(eval(field));
}
}
function config_current(field_suffix,value)
{
if(activeTab)
{
field = activeTab.getAttribute("tabTitle")+field_suffix;
config_val(field,value);
}
}
function getSType(type,value)
{
f = document.getElementById("admin_search");
if(f)
{
if (f.SearchType.value == type) return 2; else return 0;
} else return 0;
}
function getSScope(scope)
{
f = document.getElementById("admin_search");
if(f)
{
if (f.SearchScope.value == scope) return 2; else return 0;
} else return 0;
}
function setSearchMenu()
{
window.SearchMenu = new Menu("search");
SearchMenu.addMenuItem(lang_All,"SetSearchType('all');",getSType('all'));
SearchMenu.addMenuSeparator()
SearchMenu.addMenuItem(lang_Categories, "SetSearchType('categories');",getSType('categories'));
param = "";
for (var i = 0; i < tabIDs.length; i++)
{
d = document.getElementById(tabIDs[i]);
if(d)
{
tabname = d.getAttribute("tabTitle");
param = "SetSearchType('"+tabname+"');";
SearchMenu.addMenuItem(tabname,param,getSType(tabname));
}
}
SearchMenu.addMenuSeparator();
SearchMenu.addMenuItem(lang_All+' '+lang_Categories,"SetSearchScope('0');",getSScope(0));
SearchMenu.addMenuItem(lang_SubSearch,"ToggleNewSearch();",isNewSearch());
SearchMenu.addMenuItem(lang_Current+' '+lang_Categories,"SetSearchScope('2');",getSScope(2));
SearchMenu.addMenuItem(lang_Within+' '+lang_Categories,"SetSearchScope('1');",getSScope(1));
SearchMenu.addMenuSeparator();
window.SearchMenu.addMenuItem('$mnuClearSearch',"ClearSearch();","");
window.triedToWriteMenus = false;
window.SearchMenu.writeMenus();
}
function Category_SortMenu(caption)
{
menu_sorting = new Menu(caption);
menu_sorting.addMenuItem(lang_Asc,"config_val('Category_Sortorder','asc');",RadioIsSelected(Category_Sortorder,'asc'));
menu_sorting.addMenuItem(lang_Desc,"config_val('Category_Sortorder','desc');",RadioIsSelected(Category_Sortorder,'desc'));
menu_sorting.addMenuSeparator();
menu_sorting.addMenuItem(lang_Default,"config_val('Category_Sortfield','Name');","");
menu_sorting.addMenuItem(lang_Name,"config_val('Category_Sortfield','Name');",RadioIsSelected(Category_Sortfield,'Name'));
menu_sorting.addMenuItem(lang_Description,"config_val('Category_Sortfield','Description');",RadioIsSelected(Category_Sortfield,'Description'));
menu_sorting.addMenuItem(lang_CreatedOn,"config_val('Category_Sortfield','CreatedOn');",RadioIsSelected(Category_Sortfield,'CreatedOn'));
menu_sorting.addMenuItem(lang_SubCats,"config_val('Category_Sortfield','CachedDescendantCatsQty');",RadioIsSelected(Category_Sortfield,'CachedDescendantCatsQty'));
menu_sorting.addMenuItem(lang_SubItems,"config_val('Category_Sortfield','SubItems');",RadioIsSelected(Category_Sortfield,'SubItems'));
return menu_sorting;
}
function Category_FilterMenu(caption)
{
menu_filter = new Menu(caption);
menu_filter.addMenuItem(lang_All,"config_val('Category_View', 127);",CategoryView==127);
menu_filter.addMenuSeparator();
menu_filter.addMenuItem(lang_Active,"FlipBit('Category_View',CategoryView,6);",BitStatus(CategoryView,6));
menu_filter.addMenuItem(lang_Pending,"FlipBit('Category_View',CategoryView,5);", BitStatus(CategoryView,5));
menu_filter.addMenuItem(lang_Disabled,"FlipBit('Category_View',CategoryView,4);",BitStatus(CategoryView,4));
menu_filter.addMenuSeparator();
menu_filter.addMenuItem(lang_New,"FlipBit('Category_View',CategoryView,3);",BitStatus(CategoryView,3));
menu_filter.addMenuItem(lang_EdPick,"FlipBit('Category_View',CategoryView,0);",BitStatus(CategoryView,0));
return menu_filter;
}
function toggleMenu()
{
//var tab_title = GetTabTitle(activeTab.id);
//alert(tab_title);
if ((document.getElementById('categories').active) && (activeTab))
{
filterfunc = activeTab.getAttribute("tabTitle")+'_FilterMenu();';
window.cat_menu_filter_sub = Category_FilterMenu(lang_Categories);
window.sub_menu_filter_sub = eval(filterfunc);
window.cat_menu_filter = new Menu(lang_View);
cat_menu_filter.addMenuItem(cat_menu_filter_sub);
cat_menu_filter.addMenuItem(sub_menu_filter_sub);
}
else
{
if (document.getElementById('categories').active)
{
window.cat_menu_filter = Category_FilterMenu(lang_View);
}
if (activeTab)
{
filterfunc = activeTab.getAttribute("tabTitle")+'_FilterMenu();';
window.cat_menu_filter = eval(filterfunc);
}
} // Filter
//Sorting
if ((document.getElementById('categories').active) && (activeTab))
{
//Sort->Categories
sortfunc = activeTab.getAttribute("tabTitle")+'_SortMenu();';
window.cat_menu_sorting_sub = Category_SortMenu(lang_Categories);
window.sub_menu_sorting_sub = eval(sortfunc);
window.cat_menu_sorting = new Menu(lang_Sort);
cat_menu_sorting.addMenuItem(cat_menu_sorting_sub);
cat_menu_sorting.addMenuItem(sub_menu_sorting_sub);
}
else
{
if (document.getElementById('categories').active)
{
window.cat_menu_sorting = Category_SortMenu(lang_Sort);
} // categories
if (activeTab)
{
window.cat_menu_sorting = Category_SortMenu(lang_Sort);
}
} // && Sorting
if ((document.getElementById('categories').active) && (activeTab))
{
window.cat_menu_select_sub = new Menu(lang_Categories);
cat_menu_select_sub.addMenuItem(lang_All,"javascript:selectAll('categories');","");
cat_menu_select_sub.addMenuItem(lang_Unselect,"javascript:unselectAll('categories');","");
cat_menu_select_sub.addMenuItem(lang_Invert,"javascript:invert('categories');","");
selectfunc = activeTab.getAttribute("tabTitle")+"_SelectMenu();";
window.sub_menu_select_sub = eval(selectfunc);
// sub_menu_select_sub.addMenuItem(lang_All,"javascript:selectAll('"+activeTab.id+"');","");
// sub_menu_select_sub.addMenuItem(lang_Unselect,"javascript:unselectAll('"+activeTab.id+"');","");
// sub_menu_select_sub.addMenuItem(lang_Invert,"javascript:invert('"+activeTab.id+"');","");
END;
if (!$hideSelectAll) {
echo "
window.cat_menu_select = new Menu(lang_Select);
cat_menu_select.addMenuItem(cat_menu_select_sub);
cat_menu_select.addMenuItem(sub_menu_select_sub);";
}
print <<<END
}
else
{
if (document.getElementById('categories').active)
{
window.cat_menu_select = new Menu(lang_Select);
cat_menu_select.addMenuItem(lang_All,"javascript:selectAll('categories');","");
cat_menu_select.addMenuItem(lang_Unselect,"javascript:unselectAll('categories');","");
cat_menu_select.addMenuItem(lang_Invert,"javascript:invert('categories');","");
}
END;
if (!$hideSelectAll) {
echo ' if (activeTab)
{
window.cat_menu_select = new Menu(lang_Select);
cat_menu_select.addMenuItem(lang_All,"javascript:selectAllC(\'"+activeTab.id+"\');","");
cat_menu_select.addMenuItem(lang_Unselect,"javascript:unselectAll(\'"+activeTab.id+"\');","");
cat_menu_select.addMenuItem(lang_Invert,"javascript:invert(\'"+activeTab.id+"\');","");
} ';
}
print <<<END
}
if(activeTab)
{
pagefunc = activeTab.getAttribute("tabTitle")+"_PerPageMenu();";
window.PerPageMenu = eval(pagefunc);
}
window.cat_menu = new Menu("root");
if ((document.getElementById('categories').active) || (activeTab)) window.cat_menu.addMenuItem(cat_menu_filter);
if ((document.getElementById('categories').active) || (activeTab)) window.cat_menu.addMenuItem(cat_menu_sorting);
if(activeTab) window.cat_menu.addMenuItem(PerPageMenu);
if ((document.getElementById('categories').active) || (activeTab)) window.cat_menu.addMenuItem(cat_menu_select);
window.triedToWriteMenus = false;
window.cat_menu.writeMenus();
}
function toggleCategoriesA(tabHeader)
{
var categories = document.getElementById('categories');
if (!categories) return;
toggleCategories();
tabHeader.setAttribute("background", '$imagesURL'+'/itemtabs/' + ((categories.active) ? "tab_active" : "tab_inactive") + ".gif")
var images = tabHeader.getElementsByTagName("IMG");
if (images.length < 1) return;
images[0].src = '$imagesURL'+'/itemtabs/' + ((categories.active) ? "divider_up" : "divider_dn") + ".gif";
}
function toggleTabA(tabId, atm)
{
var hl = document.getElementById("hidden_line");
var activeTabId;
if (activeTab) activeTabId = activeTab.id;
if (activeTabId == tabId)
{
var devider = document.getElementById("tabsDevider");
devider.style.display = "";
unselectAll(tabId);
var tab = document.getElementById(tabId);
tab.active = false;
activeTab = null;
collapseTab = tab;
toolbar.setTab(null);
showTab();
}
else
{
if (activeTab) toggleTab(tabId, true)
else toggleTab(tabId, atm)
if (hl) hl.style.display = "none";
}
tab_hdr = document.getElementById('tab_headers');
if (!tab_hdr) return;
for (var i = 0; i < tabIDs.length; i++)
{
var tabHeader;
TDs = tab_hdr.getElementsByTagName("TD");
for (var j = 0; j < TDs.length; j++)
if (TDs[j].getAttribute("tabHeaderOf") == tabIDs[i])
{
tabHeader = TDs[j];
break;
}
if (!tabHeader) continue;
var tab = document.getElementById(tabIDs[i]);
if (!tab) continue;
tabHeader.setAttribute("background", "$imagesURL/itemtabs/" + ((tab.active) ? "tab_active" : "tab_inactive") + ".gif")
var images = tabHeader.getElementsByTagName("IMG");
if (images.length < 1) continue;
images[0].src = "$imagesURL/itemtabs/" + ((tab.active) ? "divider_up" : "divider_empty") + ".gif";
}
}
</script>
END;
?>
\ No newline at end of file
Property changes on: trunk/kernel/admin/include/toolbar/catselect.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 406)
+++ trunk/globals.php (revision 407)
@@ -1,1417 +1,1417 @@
<?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;
}
/**
* @return object
* @desc Returns reference to database connection
*/
function &GetADODBConnection()
{
static $DB = null;
global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;
if( !isset($DB) && strlen($g_DBType) > 0 )
{
$DB = ADONewConnection($g_DBType);
$connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
if(!$connected) die("Error connecting to database $g_DBHost <br>\n");
$ADODB_CACHE_DIR = $pathtoroot."cache";
$ADODB_FETCH_MODE = 2;
$ADODB_COUNTRECS = false;
$DB->debug = defined('ADODB_OUTP') ? 1 : 0;
$DB->cacheSecs = 3600;
$DB->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();
exit;
}
return $DB;
}
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);
}
/**
* @return string
* @desc Returns database table prefix entered while installation
*/
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 );
+ return isset($_POST[$name]) && $_POST[$name] !== false ? $_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.24
\ No newline at end of property
+1.25
\ No newline at end of property

Event Timeline