Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 11:58 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: trunk/kernel/action.php
===================================================================
--- trunk/kernel/action.php (revision 414)
+++ trunk/kernel/action.php (revision 415)
@@ -1,2277 +1,2278 @@
<?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) !== false )
{
$cat_id = $_POST['categorylist'];
$objSession->SetVariable('categoryid', $cat_id);
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>";
+//print_pre($objSession);
//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.38
\ No newline at end of property
+1.39
\ No newline at end of property
Index: trunk/kernel/include/modules.php
===================================================================
--- trunk/kernel/include/modules.php (revision 414)
+++ trunk/kernel/include/modules.php (revision 415)
@@ -1,906 +1,908 @@
<?php
/* List of installed modules and module-specific variables
Copyright 2002, Intechnic Corporation, All rights reserved
*/
setcookie("CookiesTest", "1");
// if branches that uses if($mod_prefix) or like that will never be executed
// due global variable $mod_prefix is never defined
$ExtraVars = array();
function ParseEnv()
{
global $env, $var_list, $mod_prefix,$objSession, $SessionQueryString;
/* parse individual sections */
$env = isset($_GET['env']) ? $_GET['env'] : '';
if ($env == "")
{
$var_list["t"] = "index";
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $value)
{
if(strlen($key))
{
$parser_name = $key . "_ParseEnv";
if(function_exists($parser_name))
{
@$parser_name();
}
}
}
}
}
else
{
$envsections = explode(":", $env);
foreach($mod_prefix as $key => $value)
{
if(strlen($key))
{
$parsed=FALSE;
$parser_name = $key . "_ParseEnv";
for($i=1; $i<sizeof($envsections); $i++)
{
$pieces = explode("-", $envsections[$i]);
if(substr($pieces[0],0,strlen($key))==$key)
{
$parsed=TRUE;
if(function_exists($parser_name))
{
$parser_name($envsections[$i]);
}
}
}
if(!$parsed)
{
if(function_exists($parser_name))
{
@$parser_name();
}
}
}
}
$req_vars = explode("-", $envsections[0]);
$sid = $req_vars[0];
if(!$SessionQueryString)
{
if(!strlen($sid) || $sid=="_")
{
if($sid != "_")
$sid = $_COOKIE["sid"];
}
else
$SessionQueryString = TRUE;
}
$var_list["sid"] = $sid;
$var_list["t"] = $req_vars[1];
if( isset($_GET['dest']) )
$var_list['dest'] = $_GET['dest'];
}
}
function LoadEnv()
{
global $env, $var_list, $mod_prefix,$objSession;
$env = $_GET["env"];
// echo "Loading Variables..<br>\n";
if ($env != "")
{
$envsections = explode(":", $env);
foreach($mod_prefix as $key => $value)
{
if(strlen($key))
{
$parsed=FALSE;
for($i=1; $i<sizeof($envsections); $i++)
{
$pieces = explode("-", $envsections[$i]);
if(substr($pieces[0],0,strlen($key))==$key)
{
$parsed=TRUE;
break;
}
}
if(!$parsed)
{
$parser_name = $key . "_LoadEnv";
//echo $parser_name;
if(function_exists($parser_name))
{
$parser_name();
}
}
else
{
$parser_name = $key . "_SaveEnv";
//echo $parser_name;
if(function_exists($parser_name))
{
$parser_name($envsections[$i]);
}
}
}
}
}
}
function BuildEnv($mod_prefix = false)
{
global $var_list,$m_var_list, $var_list_update, $mod_prefix, $objSession, $objConfig,
$ExtraVars, $objThemes, $CurrentTheme, $SessionQueryString, $FrontEnd;
static $theme;
$env = "";
//echo "Query String: $SessionQueryString<br>\n";
if(($objConfig->Get("CookieSessions")==0 || !$FrontEnd || ($objConfig->Get("CookieSessions")==2 && $SessionQueryString==TRUE)))
{
if(!$objSession->UseTempKeys)
{
$sessionkey = $objSession->GetSessionKey();
}
else
$sessionkey = $objSession->Get("CurrentTempKey");
$env = $sessionkey;
}
$env .= "-";
+
if (isset($var_list_update["t"]))
{
if($var_list_update["t"]=="_referer_")
{
$var_list_update["t"] =$objSession->GetVariable("Template_Referer");
}
$t = $var_list_update["t"];
if(!is_numeric($t))
{
if(!is_object($theme))
$theme = $objThemes->GetItem($m_var_list["theme"]);
$id = $theme->GetTemplateId($t);
$var_list_update["t"] = $id;
}
$env .= $var_list_update["t"];
}
else
{
$t = isset($var_list['t']) ? $var_list['t'] : '';
if(!is_numeric($t))
{
if(!is_object($theme))
$theme = $objThemes->GetItem($m_var_list["theme"]);
$id = $theme->GetTemplateId($t);
$t = $id;
}
$env .= $t;
}
+
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $value)
{
$builder_name = $key . "_BuildEnv";
if(function_exists($builder_name))
{
$GLOBALS[$key.'_var_list_update']['test'] = 'test';
$env .= $builder_name();
}
}
}
$extra = "";
$keys = array_keys($ExtraVars);
if(is_array($keys))
{
for($i=0;$i<count($keys);$i++)
{
$key = $keys[$i];
$e = "&".$key."=".$ExtraVars[$key];
$extra .= $e;
$e = "";
}
}
$env .= $extra;
return $env;
}
function CategoryActionFunc($basename,$CatList)
{
global $mod_prefix;
foreach($mod_prefix as $key => $value)
{
$function_name = $key."_".$basename;
if(function_exists($function_name))
{
$function_name($CatList);
}
}
}
function RegisterEnv($Var,$Value)
{
global $ExtraVars;
$ExtraVars[$Var] = $Value;
}
function UnregisterEnv($Var)
{
global $ExtraVars;
unset($ExtraVars[$Var]);
}
function ModuleTagPrefix($name)
{
global $modules_loaded;
$ret = "";
foreach($modules_loaded as $prefix=>$mod_name)
{
if($name==$mod_name)
{
$ret = $prefix;
break;
}
}
return $ret;
}
function ModuleEnabled($name)
{
global $template_path;
$a = array_keys($template_path);
if(in_array($name,$a))
return TRUE;
return FALSE;
}
function GetModuleArray($array_name="mod_prefix")
{
switch($array_name)
{
case "mod_prefix":
global $mod_prefix;
return $mod_prefix;
break;
case "admin":
global $mod_prefix, $modules_loaded;
$mod = array();
if(is_array($mod_prefix) && is_array($modules_loaded))
{
foreach ($mod_prefix as $key=>$value)
{
if(_ModuleLicensed($modules_loaded[$key]) || $key=="m")
{
$mod[$key] = $value;
}
}
}
return $mod;
break;
case "loaded":
global $modules_loaded;
return $modules_loaded;
break;
case "template":
global $template_path;
return $template_path;
case "rootcat":
global $mod_root_cats;
return $mod_root_cats;
break;
}
}
function admin_login()
{
global $objSession,$login_error, $objConfig,$g_Allow,$g_Deny;
//echo "<pre>"; print_r($objSession); echo "</pre>";
if( GetVar('help_usage') == 'install' ) return true;
$env_arr = explode('-', $_GET['env']);
$get_session_key = $env_arr[0];
$admin_login = isset($_POST['adminlogin']) && $_POST['adminlogin']; // $_POST['adminlogin'] != 1
if(!$objSession->ValidSession() || ($objSession->GetSessionKey() != $get_session_key && !$admin_login)) {
if( isset($_GET['expired']) && ($_GET['expired'] == 1) )
$login_error = admin_language("la_text_sess_expired");
return FALSE;
//echo "Expired<br>";
}
if ($objSession->HasSystemPermission("ADMIN") == 1)
return TRUE;
if(count($_POST)==0 || $_POST["adminlogin"]!=1)
return FALSE;
$login=$_POST["login"];
$password = $_POST["password"];
if (strlen($login) && strlen($password))
{
if(!_IpAccess($_SERVER['REMOTE_ADDR'],$g_Allow,$g_Deny))
{
$login_error = admin_language("la_text_address_denied");
return FALSE;
}
$valid = $objSession->Login($login, md5($password));
$hasperm = ($objSession->HasSystemPermission("ADMIN") == 1);
if (($login=="root" || $hasperm) && $valid)
{
if(_ValidateModules())
{
return TRUE;
}
else
$login_error = "Missing or invalid In-Portal License";
}
else
{
if(!$hasperm && $valid)
{
$login_error = admin_language("la_text_nopermissions");
}
else
{
$login_error = admin_language("la_Text_Access_Denied");
}
return FALSE;
}
}
else
{
if(!strlen($login))
{
$login_error = admin_language("la_Text_Missing_Username");
}
else
if(!strlen($password))
$login_error = admin_language("la_Text_Missing_Password");
return FALSE;
}
}
#---------------------------------------------------------------------------
function _EnableCookieSID()
{
global $var_list, $objConfig;
if((!$_COOKIE["sid"] && $objConfig->Get("CookieSessions")>0 && strlen($var_list["sid"])<2 && !headers_sent())
|| strlen($_COOKIE["sid"])>0)
{
return TRUE;
}
else
return FALSE;
}
function _IsSpider($UserAgent)
{
global $robots, $pathtoroot;
$lines = file($pathtoroot."robots_list.txt");
if(!is_array($robots))
{
$robots = array();
for($i=0;$i<count($lines);$i++)
{
$l = $lines[$i];
$p = explode("\t",$l,3);
$robots[] = $p[2];
}
}
return in_array($UserAgent,$robots);
}
function _StripDomainHost($d)
{
$dotcount = substr_count($d,".");
if($dotcount==3)
{
$IsIp = TRUE;
for($x=0;$x<strlen($d);$x++)
{
if(!is_numeric(substr($d,$x,1)) && substr($d,$x,1)!=".")
{
$IsIp = FALSE;
break;
}
}
}
if($dotcount>1 && !$IsIp)
{
$p = explode(".",$d);
$ret = $p[count($p)-2].".".$p[count($p)-1];
}
else
$ret = $d;
return $ret;
}
function _MatchIp($ip1,$ip2)
{
$matched = TRUE;
$ip = explode(".",$ip1);
$MatchIp = explode(".",$ip2);
for($i=0;$i<count($ip);$i++)
{
if($i==count($MatchIp))
break;
if(trim($ip[$i]) != trim($MatchIp[$i]) || trim($ip[$i])=="*")
{
$matched=FALSE;
break;
}
}
return $matched;
}
function _IpAccess($IpAddress,$AllowList,$DenyList)
{
$allowed = explode(",",$AllowList);
$denied = explode(",",$DenyList);
$MatchAllowed = FALSE;
for($x=0;$x<count($allowed);$x++)
{
$ip = explode(".",$allowed[$x]);
$MatchAllowed = _MatchIp($IpAddress,$allowed[$x]);
if($MatchAllowed)
break;
}
$MatchDenied = FALSE;
for($x=0;$x<count($denied);$x++)
{
$ip = explode(".",$denied[$x]);
$MatchDenied = _MatchIp($IpAddress,$denied[$x]);
if($MatchDenied)
break;
}
$Result = (($MatchAllowed && !$MatchDenied) || (!$MatchAllowed && !$MatchDenied) ||
($MatchAllowed && $MatchDenied));
return $Result;
}
function _ValidateModules()
{
global $i_Keys, $objConfig, $g_License;
$lic = base64_decode($g_License);
_ParseLicense($lic);
$modules = array();
//echo "License: ".$lic."<br>";
$domain = _GetDomain();
//echo "Domain: ".$domain."<br>";
if(!_IsLocalSite($domain))
{
$domain = _StripDomainHost($domain);
//echo "New domain: $domain<br>";
// echo "<pre>"; print_r($i_Keys); echo "</pre>";
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if(strlen(stristr($key["domain"],$domain)))
{
$modules = explode(",",$key["mod"]);
//echo "Modules: $modules";
}
}
if(count($modules)>0)
{
return TRUE;
}
}
else
return TRUE;
return FALSE;
}
function _ModuleLicensed($name)
{
global $i_Keys, $objConfig, $pathtoroot;
$vars = parse_portal_ini($pathtoroot."config.php");
// globalize vars from config
while($key = key($vars))
{
$GLOBALS["g_".$key] = current($vars);
next($vars);
}
$lic = base64_decode($GLOBALS['g_License']); // this works in all cases
_ParseLicense($lic);
$modules = array();
if(!_IsLocalSite(_GetDomain()))
{
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if(strlen(stristr(_GetDomain(),$key["domain"])))
{
//echo "ok<br>";
$modules = explode(",",$key["mod"]);
}
}
if(in_array($name,$modules)) {
//echo "ok<br>";
return TRUE;
}
}
else {
return TRUE;
}
return FALSE;
}
function _GetDomain()
{
global $objConfig, $g_Domain;
if($objConfig->Get("DomainDetect"))
{
$d = $_SERVER['HTTP_HOST'];
}
else
$d = $g_Domain;
return $d;
}
function _keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function _decrypt($txt,$key)
{
$txt = _keyED($txt,$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
function LoadFromRemote()
{
return "";
}
function DLid()
{
global $lid;
echo $lid."\n";
die();
}
function _LoadLicense($LoadRemote=FALSE)
{
global $pathtoroot, $objConfig;
$f = $pathtoroot."intechnic.php";
if(file_exists($f))
{
$contents = file($f);
$data = base64_decode($contents[1]);
}
else
if($LoadRemote)
return $LoadFromRemote;
return $data;
}
function _VerifyKey($domain,$k)
{
$key = md5($domain);
$lkey = substr($key,0,strlen($key)/2);
$rkey = substr($key,strlen($key)/2);
$r = $rkey.$lkey;
if($k==$r)
return TRUE;
return FALSE;
}
function _ParseLicense($txt)
{
global $i_User, $i_Pswd, $i_Keys;
$data = _decrypt($txt,"beagle");
$i_Keys = array();
$lines = explode("\n",$data);
for($x=0;$x<count($lines);$x++)
{
$l = $lines[$x];
$p = explode("=",$l,2);
switch($p[0])
{
case "Username":
$i_User = $p[1];
break;
case "UserPass":
$i_Pswd = $p[1];
break;
default:
if(substr($p[0],0,3)=="key")
{
$parts = explode("|",$p[1]);
if(_VerifyKey($parts[0],$parts[1]))
{
unset($K);
$k["domain"]=$parts[0];
$k["key"]=$parts[1];
$k["desc"]=$parts[2];
$k["mod"]=$parts[3];
$i_Keys[] = $k;
}
}
break;
}
}
}
function _IsLocalSite($domain)
{
$localb = FALSE;
if(substr($domain,0,3)=="172")
{
$b = substr($domain,0,6);
$p = explode(".",$domain);
$subnet = $p[1];
if($p[1]>15 && $p[1]<32)
$localb=TRUE;
}
if($domain=="localhost" || $domain=="127.0.0.1" || substr($domain,0,7)=="192.168" ||
substr($domain,0,3)=="10." || $localb || strpos($domain,".")==0)
{
return TRUE;
}
return FALSE;
}
//echo "Before Stuff<br>";
LogEntry("Loading Modules\n");
/* get the module list from the database */
$adodbConnection = GetADODBConnection();
$sql = "SELECT Name, Path, Var,TemplatePath, RootCat from ".GetTablePrefix()."Modules where Loaded=1 ORDER BY LoadOrder";
$rs = $adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$key = $rs->fields["Var"];
$mod_prefix[$key] = $rs->fields["Path"];
$modules_loaded[$key] = $rs->fields["Name"];
$name = $rs->fields["Name"];
$template_path[$name] = $rs->fields["TemplatePath"];
$mod_root_cats[$name] = $rs->fields["RootCat"];
// echo $key . "=". $modules_loaded[$key]."<br>\n";
$rs->MoveNext();
}
LogEntry("Loading Module Parser scripts\n");
/* for each module enabled, load up parser.php */
//foreach($mod_prefix as $key => $value)
$LogLevel++;
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $value)
{
$mod = $pathtoroot . $value . "parser.php";
// LogEntry("Loading parser $mod \n");
require_once($mod);
}
}
$LogLevel--;
LogEntry("Finished Loading Module Parser scripts\n");
/*now each module gets a look at the environment string */
$SessionQueryString = FALSE;
if(!isset($FrontEnd)) $FrontEnd = false;
if($FrontEnd != 1)
$SessionQueryString = TRUE;
if(is_array($mod_prefix))
ParseEnv();
/* create the session object */
$ip = $_SERVER["REMOTE_ADDR"];
if ( !isset($var_list['sid']) ) $var_list['sid'] = '';
if ( !isset($_GET['env']) ) $_GET['env'] = '';
if(strlen($var_list["sid"])==0 && strlen($_GET["env"])>0 && $objConfig->Get("CookieSessions")==2)
{
if(_IsSpider($_SERVER["HTTP_USER_AGENT"]))
{
$UseSession = FALSE;
}
else
{
/* switch user to GET session var */
if (!$_COOKIE['sid']) {
$SessionQueryString = TRUE;
}
//else {
//$SessionQueryString = FALSE;
//}
$UseSession = TRUE;
}
}
else {
$UseSession = TRUE;
}
if($var_list["sid"]=="_")
$var_list["sid"]="";
/*setup action variable*/
$Action = isset($_REQUEST['Action']) ? $_REQUEST['Action'] : '';
if($Action=="m_logout")
{
$u = new clsUserSession($var_list["sid"] ,($SessionQueryString && $FrontEnd==1));
$u->Logout();
unset($u);
$var_list_update["t"] = "index";
$var_list["t"] = "";
$var_list["sid"]="";
setcookie("login","",time()-3600);
setcookie("sid","",time()-3600);
}
$CookieTest = isset($_COOKIE["CookiesTest"]) ? $_COOKIE["CookiesTest"] : '';
$HTTP_REFERER = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if ( ($CookieTest == 1) || !strstr($HTTP_REFERER, $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path"))) {
$SessionQueryString = FALSE;
}
if ($FrontEnd != 1) {
$SessionQueryString = TRUE;
}
$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
if($UseSession)
{
if(!$objSession->ValidSession())
{
/* Get rid of Invalid Session and make a brand new one*/
// echo "Dumping Session ".$var_list["sid"]."<br>";
unset($var_list["sid"]);
$objSession->GetNewSession();
$var_list["sid"] = $objSession->GetSessionKey();
$var_list_update["sid"]=$objSession->GetSessionKey();
if(is_numeric($m_var_list["theme"]))
$objSession->SetThemeName($m_var_list["theme"]);
if($objConfig->Get("CookieSessions")>0 && !$SessionQueryString && !headers_sent())
setcookie("sid",$var_list["sid"]);
//echo "New Session: ".$objSession->GetSessionKey()."<br>\n";
if(isset($_COOKIE["login"]) && $Action != "m_logout" && $FrontEnd==1)
{
$parts = explode("|",$_COOKIE["login"]);
$username = $parts[0];
$pass = $parts[1];
$objSession->Login($username,$pass);
}
}
else
{ //echo "Update Session<br>";
if($objSession->Get("Language")!=$m_var_list["lang"])
{
$objSession->Set("Language",$m_var_list["lang"]);
}
$objSession->LoadSessionData();
$objSession->UpdateAccessTime();
$objSession->Update();
LoadEnv();
}
}
if( isset($var_list['t']) && is_numeric($var_list['t']))
{
if( !isset($CurrentTheme) ) $CurrentTheme = null;
if(!is_object($CurrentTheme))
$CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
$var_list["t"] = $CurrentTheme->GetTemplateById($var_list["t"]);
$objSession->Set("Theme",$CurrentTheme->Get("Name"));
}
/*create the global current user object */
$UserID=$objSession->Get("PortalUserId");
$objCurrentUser = new clsPortalUser($UserID);
$objLanguageCache = new clsLanguageCache($m_var_list["lang"]);
/* include each module's action.php script */
LogEntry("Loading Module action scripts\n");
## Global Referer Template
$_local_t = isset($var_list['t']) ? $var_list['t'] : '';
if(is_array($mod_prefix))
{
foreach($mod_prefix as $key => $folder_name)
{
if($FrontEnd==0 || !is_numeric($FrontEnd) || $FrontEnd==2)
{
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if( !strlen($admin) ) $admin = "admin";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
if(_ModuleLicensed($modules_loaded[$key]))
{
$mod = $pathtoroot.$folder_name."module_init.php";
if( file_exists($mod) ) require_once($mod);
$mod = $pathtoroot.$folder_name."action.php";
if( file_exists($mod) ) require_once($mod);
$mod = $pathtoroot.$folder_name."searchaction.php";
if( file_exists($mod) ) require_once($mod);
}
}
if($FrontEnd==1 || $FrontEnd==2)
{
$mod = $pathtoroot.$folder_name."module_init.php";
if(file_exists($mod))
require_once($mod);
$mod = $pathtoroot.$folder_name."frontaction.php";
if(file_exists($mod))
require_once($mod);
}
}
}
if (strstr($_SERVER['SCRIPT_NAME'], 'install') && $objSession->Get("PortalUserId") == 0) {
$objSession->Delete();
}
if( !isset($SearchPerformed) ) $SearchPerformed = false;
if($SearchPerformed == true) $objSearch->BuildIndexes();
LogEntry("Finished Loading Module action scripts\n");
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/modules.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.15
\ No newline at end of property
+1.16
\ No newline at end of property
Index: trunk/kernel/include/portaluser.php
===================================================================
--- trunk/kernel/include/portaluser.php (revision 414)
+++ trunk/kernel/include/portaluser.php (revision 415)
@@ -1,1001 +1,1001 @@
<?php
RegisterPrefix("clsPortalUser","user","kernel/include/portaluser.php");
class clsPortalUser extends clsItem
{
var $Vars; //contains the PersistantSessionData for the user
var $VarsLoaded;
var $PrimeGroup;
function clsPortalUser($UserId=NULL)
{
$this->clsParsedItem();
$this->tablename=GetTablePrefix()."PortalUser";
$this->type=6;
$this->BasePermission="USER";
$this->id_field = "PortalUserId";
$this->TagPrefix="user";
$this->Vars = array();
$VarsLoaded = FALSE;
$this->debuglevel = 0;
if(isset($UserId))
$this->LoadFromDatabase($UserId);
}
function Delete()
{
global $objGroups, $objFavorites;
$g = $objGroups->GetPersonalGroup($this->Get("Login"));
if(is_object($g))
$g->Delete();
$objFavorites->DeleteUser($this->Get("PortalUserId")); //delete favorites
parent::Delete();
}
function RemoveFromAllGroups()
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
}
function RemoveFromGroup($GroupId)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
$sql .= " AND GroupId=$GroupId";
$this->adodbConnection->Execute($sql);
}
function PrimaryGroup($ReturnField = "GroupId")
{
global $objGroups;
$ret = "";
if(!is_object($this->PrimeGroup))
{
if((int)$this->Get("GroupId")>0)
{
$this->PrimeGroup =& $objGroups->GetItem($this->Get("GroupId"));
}
else
{
$this->PrimeGroup = new clsPortalGroup();
$sql = "SELECT * FROM ".GetTablePrefix()."UserGroup INNER JOIN ".GetTablePrefix()."PortalGroup ON (".GetTablePrefix()."UserGroup.GroupId=".GetTablePrefix()."PortalGroup.GroupId) WHERE PrimaryGroup = 1 AND PortalUserId=".$this->Get("PortalUserId");
//echo $sql;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$this->PrimeGroup->SetFromArray($rs->fields);
}
}
$ret = $this->PrimeGroup->Get($ReturnField);
return $ret;
}
function SetPrimaryGroup($GroupId)
{
if($this->IsInGroup($GroupId))
{
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=0 WHERE PortalUserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=1 WHERE GroupId=$GroupId AND PortalUserId=".$this->Get("PortalUserId");
$this->adodbConnection->Execute($sql);
}
}
function GetGroupList()
{
$ret = array();
$sql = "SELECT GroupId FROM %sUserGroup WHERE PortalUserId = %s ORDER BY PrimaryGroup";
$sql = sprintf($sql, GetTablePrefix(), $this->Get("PortalUserId"));
$ret = $this->adodbConnection->GetCol($sql);
return $ret;
}
function IsInGroup($GroupId)
{
$groups = $this->GetGroupList();
if( $groups === false ) return false;
return in_array($GroupId, $groups) ? true : false;
}
function GetPersonalGroup($CreateIfMissing = FALSE)
{
global $objGroups;
$n = "_".$this->Get("Login");
$g = $objGroups->GetItemByField("Name",$n);
if(!is_object($g) && $CreateIfMissing)
$g = $this->CreatePersonalGroup();
return $g;
}
function CreatePersonalGroup()
{
global $objGroups;
$Description = $this->Get("FirstName")." ".$this->Get("LastName");
$CreatedOn=time();
$n = "_".$this->Get("Login");
$g = $objGroups->Add_Group($n, $Description, $CreatedOn, 1, 0);
$g->Set("Personal",1);
$g->Set("System",0);
$g->Set("Enabled",1);
$g->Update();
if(is_object($g))
$g->AddUser($this->Get("PortalUserId"));
return $g;
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!strlen($this->Get("Login")))
{
$Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!strlen($this->Get("Email")))
{
$Errors->AddError("error.fieldIsRequired",'Email',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function Approve()
{
$this->Set("Status", 1);
$this->Update();
$this->SendUserEventMail("USER.APPROVE",$this->Get("PortalUserId"));
$this->SendAdminEventMail("USER.APPROVE");
}
function Deny($IsBanned = 0)
{
$this->Set( Array('Status','IsBanned'), Array(0,$IsBanned) );
$this->Update();
$this->SendUserEventMail("USER.DENY",$this->Get("PortalUserId"));
$this->SendAdminEventMail("USER.DENY");
}
function HasSystemPermission($PermissionName)
{
global $objGroups;
- $GroupList = $this->GetGroupList();
+ $GroupList = $this->GetGroupList();
for($i=0;$i<count($GroupList);$i++)
{
$g = $objGroups->GetItem($GroupList[$i]);
$value = $g->HasSystemPermission($PermissionName);
if($value != -1)
break;
}
return $value;
}
function LoadPersistantVars()
{
global $objConfig;
unset($this->Vars);
$this->Vars = array();
$user_id = $this->HasField('PortalUserId') ? $this->Get('PortalUserId') : 0;
$sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."PersistantSessionData WHERE PortalUserId = 0 OR PortalUserId = ".$user_id." ORDER BY PortalUserId ASC";
$result = $this->adodbConnection->Execute($sql);
while ($result && !$result->EOF)
{
$data = $result->fields;
$this->Vars[$data["VariableName"]] = $data["VariableValue"];
$objConfig->Set($data["VariableName"], $data["VariableValue"], 1, 1);
$result->MoveNext();
}
$this->VarsLoaded=TRUE;
}
function SetPersistantVariable($variableName, $variableValue)
{
global $objConfig;
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
$userid = $this->Get("PortalUserId");
$objConfig->Set($variableName,$variableValue,1);
$fields = array_keys($this->Vars);
if(strlen($variableValue)>0)
{
if(in_array($variableName,$fields))
{
$sql = "UPDATE ".GetTablePrefix()."PersistantSessionData SET VariableValue='$variableValue' WHERE VariableName='$variableName' AND PortalUserId=$userid";
}
else
$sql = "INSERT INTO ".GetTablePrefix()."PersistantSessionData (VariableName,VariableValue,PortalUserId) VALUES ('$variableName','$variableValue',$userid)";
}
else
$sql = "DELETE FROM ".GetTablePrefix()."PersistantSessionData WHERE VariableName='$variableName' AND PortalUserId=$userid";
$this->Vars[$variableName] = $variableValue;
// echo "<BR>SQL: $sql<BR>";
$this->adodbConnection->Execute($sql);
}
function GetPersistantVariable($variableName)
{
global $objConfig;
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
$fields = array_keys($this->Vars);
if(in_array($variableName,$fields))
{
$val = $this->Vars[$variableName];
}
else
$val = $objConfig->Get($variableName);
return $val;
}
function GetAllPersistantVars()
{
if(!$this->VarsLoaded)
$this->LoadPersistantVars();
return $this->Vars;
}
function GetIcon()
{
}
function StatusIcon()
{
global $imagesURL;
$url = $imagesURL."/itemicons/icon16_user";
if($this->Get("Status")==0)
{
$url .= "_disabled";
}
else
if($this->Get("Status")==2)
{
$url .= "_pending";
}
$url .= ".gif";
return $url;
}
function IsFriend($UserId)
{
$ftable = GetTablePrefix()."Favorites";
$sql = "SELECT count(*) as FriendCount FROM $ftable WHERE PortalUserId=$UserId AND ResourceId=";
$sql .=$this->Get("ResourceId")." AND ItemTypeId=6";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
return ($rs->fields["FriendCount"]>0);
return FALSE;
}
function GetUserTime($timestamp)
{
if(is_numeric($this->Get("tz")))
{
return GetLocalTime($timestamp,$this->Get("tz"));
}
else
return GetLocalTime($timestamp);
}
function ParseObject($element)
{
global $objConfig, $objUsers, $objCatList,$objSession, $var_list_update, $var_list, $m_var_list_update;
//echo "<PRE>"; print_r($element); echo "</pre>";
if (strtolower($element->name) == 'touser') {
$this->TagPrefix = "touser";
}
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
if(substr($field,0,3)=="pp_")
{
$perm = $objSession->GetPersistantVariable($field);
if($perm)
{
$field = substr($field,3);
}
else
$field = "";
}
switch($field)
{
/*
@field:user.login
@description:User's login name
*/
case "username":
case "login":
$ret = $this->Get("Login");
break;
case "firstname":
$ret = $this->Get("FirstName");
break;
case "lastname":
$ret = $this->Get("LastName");
break;
case "password":
/*
@field:user.password
@description:User password
*/
$ret = $objSession->Get("password");
$objSession->Set("password", '');
break;
case "email":
$ret = $this->Get("Email");
break;
case "street":
$ret = $this->Get("Street");
break;
case "city":
$ret = $this->Get("City");
break;
case "state":
$ret = $this->Get("State");
break;
case "zip":
$ret = $this->Get("Zip");
break;
case "phone":
$ret = $this->Get("Phone");
break;
case "country":
$ret = $this->Get("Country");
break;
case "primarygroup":
/*
@field:user.primarygroup
@description:Parses a field from the user's primary group
@attrib:_groupfield::group field name to parse, defaults to group name
*/
$groupfield = $element->attributes["_groupfield"];
if(!strlen($groupfield))
$groupfield="Name";
$ret = $this->PrimaryGroup($groupfield);
break;
case "date":
/*
@field:user.date
@description:Returns the date/time the user was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "dob":
/*
@field:user.dob
@description:Returns the date/time of the users date of birth
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("dob");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "modified":
/*
@field:user.modified
@description:Returns the date/time the user was last modified
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("Modified");
if($d<=0)
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "profile_link":
/*
@field:user.profile_link
@description:Create a link to the user's profile
@attrib:_template:tpl:template the link should point to
*/
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$ret = GetIndexURL()."?env=" . BuildEnv()."&UserId=".$this->Get("PortalUserId");
break;
case "add_friend_link":
/*
@field:user.add_friend_link
@description:link to add a user to the friends list
@attrib:_template:tpl:Template link shoukd point to
*/
if($element->attributes["_force"] || !$this->IsFriend($objSession->Get("PortalUserId")) &&
$this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
{
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$action = "m_add_friend";
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
}
else
$ret = "";
break;
case "del_friend_link":
/*
@field:user.del_friend_link
@description:link to remove a user from the friends list
@attrib:_template:tpl:Template link shoukd point to
*/
if($element->attributes["_force"] || $this->IsFriend($objSession->Get("PortalUserId")) &&
$this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
{
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$action = "m_del_friend";
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
}
else
$ret = "";
break;
case "icon":
$ret = $this->GetIcon();
break;
case "image":
/*
@field:user.image
@description:Return an image associated with the user
@attrib:_default:bool:If true, will return the default image if the requested image does not exist
@attrib:_name::Return the image with this name
@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
*/
$default = $element->attributes["_primary"];
$name = $element->attributes["_name"];
if(strlen($name))
{
$img = $this->GetImageByName($name);
// echo "<PRE>";print_r($img); echo "</PRE>";
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if($img)
{
if($element->attributes["_thumbnail"])
{
$url = $img->parsetag("thumb_url");
}
else
$url = $img->parsetag("image_url");
}
else
{
$url = $element->attributes["_defaulturl"];
}
if($element->attributes["_imagetag"])
{
if(strlen($url))
{
$ret = "<IMG src=\"$url\" $extra_attribs >";
}
else
$ret = "";
}
else
$ret = $url;
break;
case "custom":
/*
@field:cat.custom
@description:Returns a custom field
@attrib:_customfield::field name to return
@attrib:_default::default value
*/
$field = $element->attributes["_customfield"];
$default = $element->attributes["
"];
$ret = $this->GetPersistantVariable($field);
if(!strlen($ret))
$ret = $this->GetCustomFieldValue($field,$default);
break;
}
}
else
{
$ret = $this->parsetag($element->name);
}
return $ret;
}
function parsetag($tag)
{
global $m_var_list_update, $var_list_update, $var_list, $objConfig;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "user_id":
return $this->Get("ResourceId");
break;
case "user_login":
return $this->Get("Login");
break;
case "user_group":
return $this->Get("PrimaryGroupName");
break;
case "user_firstname":
return $this->Get("FirstName");
break;
case "user_lastname":
return $this->Get("LastName");
break;
case "user_email":
return $this->Get("Email");
break;
case "user_date":
return LangDate($this->Get("CreatedOn"));
break;
case "user_datetime":
return LangDate($this->Get("CreatedOn"))." ".LangTime($this->Get("CreatedOn"));
break;
case "user_dob":
return LangDate($this->Get("dob"));
break;
case "user_password":
return $this->Get("Password");
break;
case "user_phone":
return $this->Get("Phone");
break;
case "user_street":
return $this->Get("Street");
break;
case "user_city":
return $this->Get("City");
break;
case "user_state":
return $this->Get("State");
break;
case "user_zip":
return $this->Get("Zip");
break;
case "user_country":
return $this->Get("Country");
break;
case "user_resourceid":
return $this->Get("ResourceId");
break;
case "user_icon":
return $this->GetIcon();
break;
case "user_profile_link":
$var_list_update["t"] = "user_profile";
$m_var_list_update["action"] = $this->Get("UserId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["action"], $var_list_update["t"]);
return $ret;
break;
case "user_messages":
return $this->NewMessages();
break;
case "user_messages_link":
$var_list_update["t"] = "inbulletin/bb_private_msg_list";
return GetIndexURL()."?env=" . BuildEnv();
unset($var_list_update);
break;
default:
return "Undefined:$tagname";
break;
}
}
} /* class clsPortalUser*/
class clsUserManager extends clsItemList //clsItemCollection
{
/*this class wraps common user-related functions */
// var $Page;
function clsUserManager()
{
$this->clsItemCollection(); // clsItemList() // need to use this, but double limit clause being created (normal+default 0,100)
$this->classname = "clsPortalUser";
$this->SetTable('live', GetTablePrefix().'PortalUser');
$this->Page = isset($_GET['lpn']) ? $_GET['lpn'] : 1;
$this->EnablePaging = true;
$this->PerPageVar = "Perpage_User";
$this->AdminSearchFields = array("Login","FirstName","LastName","Email","Street","City", "State","Zip","Country","Phone");
}
function GetPageLinkList($dest_template=NULL,$link_template=NULL,$page = "")
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$NumPages = $this->GetNumPages($objConfig->Get("Perpage_Topics"));
if(strlen($dest_template)>0)
{
$var_list_update["t"]=$dest_template;
}
else
{
$var_list_update["t"] = $var_list["t"];
}
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $page."?env=".BuildEnv();
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $page."?env=".BuildEnv();
}
for($p=1;$p<=$NumPages;$p++)
{
$t = template($link_template);
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = $page."?env=".BuildEnv();
$t = str_replace("<%page_link%>", $href, $t);
$t = str_replace("<%page_number%>",$p,$t);
$t = str_replace("<%prev_url%>",$prev_url,$t);
$t = str_replace("<%next_url%>",$next_url,$t);
$o .= $t;
}
else
{
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
}
return $o;
}
function GetUser($ID)
{
$u = $this->GetItem($ID);
return $u;
}
function GetUserName($Id)
{
$rs = $this->adodbConnection->Execute("SELECT Login from ".$this->SourceTable." where PortalUserId=$Id");
return $rs->fields["Login"];
}
function GetUserId($Login)
{
$rs = $this->adodbConnection->Execute("SELECT PortalUserId from ".$this->SourceTable." where Login LIKE '$Login'");
return $rs->fields["PortalUserId"];
}
function GetTotalUsers()
{
return $this->UserCount("1");
}
function GetLatestUser()
{
global $Errors;
$sql = "SELECT max(CreatedOn) as LastDate FROM ".$this->SourceTable;
$result = $this->adodbConnection->Execute($sql);
if ($result === false || !is_object($result))
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$sql = "SELECT PortalUserId FROM ".$this->SourceTable." WHERE CreatedOn >= ".$result->fields["LastDate"];
$result = $this->adodbConnection->Execute($sql);
if (!rs || $rs->EOF)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$u = $this->GetUser($result->fields["PortalUserId"]);
return $u;
}
function &Add_User($Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="", $Status=2,
$Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0, $ip="", $CheckBanned=FALSE)
{
$u = new clsPortalUser(NULL);
$u->tablename = $this->SourceTable;
//echo "Creating User..<br>\n";
$u->Set(array("Login", "Password", "FirstName", "LastName", "Email", "Status",
"Phone","Street", "City", "State", "Zip", "Country", "CreatedOn","dob"),
array($Login, $Password, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn, $dob));
$BrokenRule = $CheckBanned ? $u->CheckBanned() : false;
if(!$BrokenRule)
{
$u->Create();
return $u;
}
return $BrokenRule;
/*md5($Password)*/
}
function &Edit_User($UserId, $Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="",
$Status=2, $Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0)
{
//echo "<font color=\"red\">Editing User: [$UserId]</font><br>";
$u =& $this->GetItem($UserId);
if(!$CreatedOn)
$CreatedOn = $u->Get("CreatedOn");
// $u->debuglevel=1;
if (is_object($u))
{
$IsBanned = $u->Get('IsBanned');
if($Status == 1) $IsBanned = 0;
$u->Set(array("Login", "FirstName", "LastName", "Email", "Status",
"Phone", "Street", "City", "State", "Zip", "Country", "CreatedOn","dob","IsBanned"),
array($Login, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn,$dob,$IsBanned));
if(strlen($Password))
$u->Set("Password",$Password);
$u->Update();
}
return $u;
}
function Delete_User($UserId)
{
$u = $this->GetItemByField("ResourceId",$UserId);
if(is_object($u))
{
$u->RemoveFromAllGroups();
$u->Delete();
}
}
function LoadUsers($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Users")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Users");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Users");
}
else
$limit = NULL;
$where = trim($where);
$orderBy = trim($orderBy);
if(!strlen($where))
$where = "1";
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
if($this->QueryItemCount>0)
{
if ($orderBy!="")
{
$this->Query_PortalUser($where,$orderBy,$limit);
}
else
{
$this->Query_PortalUser($where,"Login DESC",$limit);
}
}
}
function Query_PortalUser($whereClause,$orderByClause="", $limitClause="")
{
global $m_var_list,$Errors, $objSession;
$resultSet = array();
$utable = $this->SourceTable;
$gtable = GetTablePrefix()."UserGroup";
$sql = "SELECT * FROM $utable LEFT JOIN $gtable ON ($utable.PortalUserId=$gtable.PortalUserId)";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
if(strlen(trim($orderByClause))>0)
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if(isset($limitClause))
$sql = sprintf('%s %s',$sql,$limitClause);
return $this->Query_Item($sql);
}
function Query_GroupPortalUser($whereClause,$orderByClause)
{
global $m_var_list,$objSession,$Errors;
$resultSet = array();
$table = $this->SourceTable;
$sql = "SELECT * FROM $table LEFT JOIN ".GetTablePrefix()."UserGroup USING (PortalUserId) ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
return $this->query_item($sql);
}
function UserCount($whereClause)
{
$count = TableCount($this->SourceTable,$whereClause,0);
return $count;
}
function CountActive()
{
return $this->UserCount("Status=1");
}
function CountPending()
{
return $this->UserCount("Status=2");
}
function CountDisabled()
{
return $this->UserCount("Status=0");
}
function CopyFromEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
// echo $sql."<BR>";
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->idfield = $idfield;
$c->Dirty();
if($c->Get($idfield)<1)
{
$old_id = $c->Get($idfield);
$c->UnsetIdField();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PortalUserId=".$c->Get("PortalUserId");
$sql .=" WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
else
$c->Update();
unset($c);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function PurgeEditTable()
{
parent::PurgeEditTable();
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
} /*clsUserManager*/
?>
Property changes on: trunk/kernel/include/portaluser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.12
\ No newline at end of property
Index: trunk/kernel/include/portalgroup.php
===================================================================
--- trunk/kernel/include/portalgroup.php (revision 414)
+++ trunk/kernel/include/portalgroup.php (revision 415)
@@ -1,500 +1,500 @@
<?php
class clsPortalGroup extends clsParsedItem
{
var $UserCount;
function clsPortalGroup($GroupId=NULL)
{
$this->clsParsedItem($GroupId);
$this->tablename=GetTablePrefix()."PortalGroup";
$this->type=7;
$this->BasePermission="GROUP";
$this->id_field = "GroupId";
if($GroupId)
$this->LoadFromDatabase($GroupId);
}
function Validate()
{
global $objSession, $Errors;
$dataValid = true;
if(!isset($this->m_Name) || $this->m_Name == "")
{
$Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function HasSystemPermission($PermissionName)
- {
+ {
$GroupId = $this->Get("GroupId");
$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE GroupId=$GroupId AND Permission='$PermissionName' AND type=1";
$result = $this->adodbConnection->Execute($sql);
if($result && !$result->EOF)
{
$this->SysPermCache[$PermissionName] = (int)$result->fields["PermissionValue"];
return (int)$result->fields["PermissionValue"];
}
else
return -1;
}
/* set $Value to -1 to delete the permission row from the DB */
function SetSystemPermission($PermName,$Value)
{
//echo "Setting $PermName to $Value<br>\n";
$oldval = $this->HasSystemPermission($PermName);
if($Value != $oldval)
{
if($Value>-1)
{
if($oldval>-1)
{
$sql = "UPDATE ".GetTablePrefix()."Permissions SET PermissionValue=$Value ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
//echo "UPDATE SQL: $sql<br>";
}
else
{
$sql = "INSERT INTO ".GetTablePrefix()."Permissions (Permission, GroupId, PermissionValue, Type, CatId) ";
$sql .="VALUES ('$PermName',".$this->Get("GroupId").",$Value,1,0)";
//echo "INSERT SQL: $sql<br>";
}
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
}
else
{
$sql = "DELETE FROM ".GetTablePrefix()."Permissions ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
//echo "DELETE SQL: $sql<br>";
$this->adodbConnection->Execute($sql);
}
}
}
function CheckPermission($permissionName)
{
//Check permission and if needs approval set approval
global $objSession, $Errors;
if(!$objSession->HasSystemPermission($permissionName))
{
//$Errors->AddError("error.AccessDenied","","","",get_class($this),"CheckPermission");
return false;
}
return true;
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = "SELECT * FROM ".$this->tablename." WHERE GroupId = $Id";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
function AddUser($UserId,$PrimaryGroup=0)
{
// add user to group OR just updates it's status there
$db =& $this->adodbConnection;
$table = GetTablePrefix().'UserGroup';
$group_id = $this->Get('GroupId');
$sql_patterns['check'] = 'SELECT PortalUserId FROM %s WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['reset_primary'] = 'UPDATE %s SET PrimaryGroup = 0 WHERE PortalUserId = %s';
$sql_patterns['set_primary'] = 'UPDATE %s SET PrimaryGroup = 1 WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['add_to_group'] = 'INSERT INTO %s (PortalUserId,GroupId,PrimaryGroup) VALUES (%s, %s, %s)';
$tmp_sql = sprintf($sql_patterns['check'], $table, $group_id, $UserId);
$check_result = $db->GetOne($tmp_sql);
if(!$check_result)
{
// user is not a memeber of this group
$GroupCount = TableCount($table,"PortalUserId = $UserId", 0);
if(!$PrimaryGroup) $PrimaryGroup = ($GroupCount == 0) ? 1 : 0; // reset primary status if not already
$tmp_sql = sprintf($sql_patterns['add_to_group'], $table, $UserId, $group_id, $PrimaryGroup);
$db->Execute($tmp_sql);
}
if($PrimaryGroup)
{
$tmp_sql = sprintf($sql_patterns['reset_primary'], $table, $UserId);
$db->Execute($tmp_sql);
$tmp_sql = sprintf($sql_patterns['set_primary'], $table, $group_id, $UserId);
$db->Execute($tmp_sql);
}
}
function DeleteUser($UserId)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=$UserId AND GroupId=".$this->Get("GroupId");
$this->adodbConnection->Execute($sql);
}
function GetCustomField( $fieldName)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Get field is required in order to set custom field values","","clsPortalGroup","GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_UserId,"portaluser",$fieldName);
}
function SetCustomField( $fieldName, $value)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Set field is required in order to set custom field values","","clsPortalGroup","SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_UserId,"portaluser",$fieldName,$value);
}
function GetUserCount()
{
if(!is_numeric($this->UserCount))
{
$sql = "SELECT count(*) as UserCount FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$users = $rs->fields["UserCount"];
$this->UserCount = (int)$users;
}
return $this->UserCount;
}
function GetUserList()
{
$sql = "SELECT * FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
$res = array();
while($rs && !$rs->EOF)
{
$res[] = $rs->fields["PortalUserId"];
$rs->MoveNext();
}
return $res;
}
function parsetag($tag)
{
global $var_list_update, $objConfig;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "group_id":
return $this->Get("GroupId");
break;
case "group_name":
return $this->Get("Name");
break;
case "group_desc":
return $this->Get("Description");
break;
case "group_date":
return LangDate($this->Get("CreatedOn"));
break;
case "group_name":
return $this->Get("Name");
break;
case "group_enabled":
return $this->Get("Enabled");
break;
case "group_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "group_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "group_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
case "group_system":
if ($this->Get("System") == 1)
return "System";
else
return "User Defined";
break;
case "group_status":
if ($this->Get("Enabled") == 1)
return "Enabled";
else
return "Disabled";
break;
default:
if (substr($tag, 0, 6) == "custom")
return Users_Custom($this->Get("ResourceId"), $tag);
else
return "Undefined:$tagname";
break;
}
}
}
class clsGroupList extends clsItemCollection
{
var $Page;
function clsGroupList()
{
$this->clsItemCollection();
$this->classname = "clsPortalGroup";
$this->SetTable('live', GetTablePrefix()."PortalGroup");
$this->AdminSearchFields = array("name");
$this->id_field = "GroupId";
}
function NumGroups()
{
return $this->NumItems();
}
function GetGroup($GroupID)
{
return $this->GetItem($GroupID);
}
function GetPersonalGroup($UserLogin)
{
$n = "_".$UserLogin;
$g = $this->GetItemByField("Name",$n);
return $g;
}
function LoadGroups($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Groups")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Groups");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Groups");
}
else
$limit = NULL;
if(strlen($where) == 0) $where = '1';
$this->QueryItemCount=TableCount($this->SourceTable, $where, 0);
//echo $this->QueryItemCount."<br>\n";
if ($orderBy!="")
{
$this->Query_PortalGroup($where,$orderBy,$limit);
}
else
{
$this->Query_PortalGroup($where,"Name DESC",$limit);
}
}
function Query_PortalGroup($whereClause=NULL,$orderByClause=NULL,$limit=null)
{
global $m_var_list,$objSession,$Errors;
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(strlen($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(strlen($orderByClause))
if(strlen(trim($orderByClause)))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if( isset($limit) ) $sql .= ' '.$limit;
return $this->Query_Item($sql);
}
function Query_UserPortalGroup($whereClause,$orderByClause)
{
global $m_var_list,$objSession,$Errors;
if ($m_var_list["action"] == "m_group_search")
$table = $userSession->Get("SessionKey") . "_search";
else
$table = $this->SourceTable;
$sql = "SELECT * FROM $table LEFT JOIN UserGroup USING (GroupId) ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
if (strlen(trim($orderByClause)))
{
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
}
$result = $this->adodbConnection->Execute($sql);
return $this->Query_Item($sql);
}
function GetAllGroupList()
{
static $GroupListCache;
if(!is_array($GroupListCache))
{
$GroupListCache = array();
$sql = "SELECT GroupId FROM ".$this->SourceTable." WHERE Enabled=1";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$GroupListCache[] = $rs->fields["GroupId"];
$rs->MoveNext();
}
}
return $GroupListCache;
}
function Group_Custom($ResourceId, $tag)
{
$fieldname= substr($tag, 7);
$sql = "SELECT Value FROM ".GetTablePrefix()."CustomMetaData LEFT JOIN ".GetTablePrefix()."CustomField USING (CustomFieldId) where ".GetTablePrefix()."CustomMetaData.ResourceId=$ResourceId AND ".GetTablePrefix()."CustomField.FieldName='$fieldname'";
$result = $this->adodbConnection->Execute($sql);
if ($result->EOF)
return "";
else
return $result->fields["Value"];
}
function Add_Users_To_Group($groupid)
{
global $g_usergroup_status;
$userids = explode("-", $g_usergroup_status);
$g = $this->GetItem($groupid);
foreach($userids as $userid)
$g->AddUser($userid);
}
function Delete_Group($GroupId)
{
$g = $this->GetItem($GroupId);
if(is_object($g))
{
$g->Delete();
}
}
function Edit_Group($GroupId, $Name, $Description)
{
$g = $this->GetItem($GroupId);
$g->Set(array("Name", "Description"), array($Name, $Description));
$g->Update();
return $g;
}
function Add_Group($Name, $Description, $System=1)
{
$g = new clsPortalGroup(NULL);
$g->tablename = $this->SourceTable;
$g->Set(array("Name", "Description", "System"),array($Name, $Description,$System));
$g->Set("CreatedOn",adodb_date("U"));
$g->Create();
return $g;
}
function CopyFromEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->idfield = $idfield;
$c->Dirty();
if($c->Get($idfield)<1)
{
$old_id = $c->Get($idfield);
$c->UnsetIdField();
if(!is_numeric($c->Get("OrgId")))
$c->Clean(array("OrgId"));
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
$this->adodbConnection->Execute($sql);
$sql = "UPDATE ".GetTablePrefix()."Permissions SET GroupId=".$c->Get("GroupId")." WHERE GroupId=$old_id";
$this->adodbConnection->Execute($sql);
}
$c->Update();
unset($c);
unset($r);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function PurgeEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE GroupId<1";
$this->adodbConnection->Execute($sql);
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE GroupId<1";
$this->adodbConnection->Execute($sql);
}
}
/*
class clsUserGroupList extends clsItemCollection
{
function clsUserGroupList()
{
$this->clsItemCollection();
$this->classname = "clsPortalGroup";
$this->SetTable('live', GetTablePrefix()."UserGroup");
$this->id_field = "PortalUserId"; // don't try to insert by this ID :)
}
}
*/
?>
Property changes on: trunk/kernel/include/portalgroup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.6
\ No newline at end of property
Index: trunk/kernel/include/usersession.php
===================================================================
--- trunk/kernel/include/usersession.php (revision 414)
+++ trunk/kernel/include/usersession.php (revision 415)
@@ -1,1130 +1,1130 @@
<?php
class clsUserSession
{
//Common DB operation class variables
var $m_dirtyFieldsMap = array();
//Identity
var $m_SessionKey;
var $m_CurrentTempKey;
var $m_PrevTempKey;
//Required attributes
var $m_LastAccessed;
var $m_PortalUserId;
var $m_Language;
var $m_Theme;
var $m_GroupId;
var $adodbConnection;
var $m_Errors;
var $m_GroupList;
var $PermCache;
var $SysPermCache;
var $PermCacheGroups;
var $CurrentUser;
var $UseTempKeys;
function clsUserSession($id=NULL, $TempKeys=FALSE)
{
global $objConfig, $objLanguages, $objThemes, $m_var_list;
$this->m_Errors = new clsErrorManager();
$this->adodbConnection = GetADODBConnection();
$this->PermCache = array();
$this->PermCacheGroups ="";
$this->UseTempKeys = $TempKeys;
if( GetVar('help_usage') == 'install' ) return;
if(!$this->UseTempKeys || strlen($id)==0)
{
//echo "with cookies";
if( !isset($_SERVER['HTTP_REFERER']) ) $_SERVER['HTTP_REFERER'] = '';
if(!isset($_GET['destform'])) $_GET['destform'] = null;
if(!isset($_GET['continue_sess'])) $_GET['continue_sess'] = null;
if( strlen($id) && (strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path")) || $_GET['destform'] == 'popup' || $_GET['continue_sess'] == 1))
{
$this->Set("SessionKey",$id);
return $this->LoadFromDatabase($id);
}
else
{
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
}
else
{
//echo "without cookies";
return $this->LoadFromTempKey($id);
}
}
function CopyToNewSession()
{
$OldKey = $this->GetSessionKey();
$this->GetNewSession();
if($OldKey != $this->GetSessionKey())
{
$this->Set("PortalUserId",$this->Get("PortalUserId"));
$this->Set("GroupId",$this->Get("GroupId"));
$this->Set("GroupList",$this->Get("GroupList"));
$this->Set("Language",$this->Get("Language"));
$this->Set("tz",$this->Get("tz"));
$this->Set("LastAccessed",date("U"));
$this->Update();
}
}
function Get($name)
{
$var = "m_" . $name;
return isset($this->$var) ? $this->$var : '';
}
function Set($name, $value)
{
if (is_array($name))
{
for ($i=0; $i<sizeof($name); $i++)
{ $var = "m_" . $name[$i];
$this->$var = $value[$i];
$this->m_dirtyFieldsMap[$name[$i]] = $value[$i];
}
}
else
{
$var = "m_" . $name;
$this->$var = $value;
$this->m_dirtyFieldsMap[$name] = $value;
//echo "Set: $var = $value <br>\n";
}
}
function Validate()
{
$dataValid = true;
if(!isset($this->m_LastAccessed))
{
$this->m_Errors->AddError("error.fieldIsRequired",'LastAccessed',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_PortalUserId))
{
$this->m_Errors->AddError("error.fieldIsRequired",'PortalUserId',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Language))
{
$this->m_Errors->AddError("error.fieldIsRequired",'Language',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Theme))
{
$this->m_Errors->AddError("error.fieldIsRequired",'Theme',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function Delete()
{
if(!isset($this->m_SessionKey))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: Delete requires set id',"",get_class($this),"Delete");
return false;
}
//Delete associated adata first
$sql = sprintf("DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey = '%s'", $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
$sql = sprintf("DROP TABLE IF EXISTS %s%s_search",GetTablePrefix(), $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
$sql = sprintf("DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'", $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Delete");
return false;
}
$this->Set("SessionKey","");
$this->Set("SessionDataLoaded",false);
return true;
}
function Update()
{
global $objConfig;
//$this->Set("LastAccessed",date("U"));
$this->Set("IpAddress",$_SERVER["REMOTE_ADDR"]);
if(!isset($this->m_SessionKey))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: Update requires set id',"",get_class($this),"Update");
return false;
}
if(!is_numeric($this->Get("PortalUserId")))
{
$this->Set("PortalUserId",0);
}
if(!strlen($this->Get("GroupList")))
{
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
if(count($this->m_dirtyFieldsMap) == 0)
return true;
$sql = "UPDATE ".GetTablePrefix()."UserSession SET ";
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr($value));
$first = 0;
}
else
{
$sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr($value));
}
}
$sql = sprintf("%s WHERE SessionKey = '%s'",$sql, $this->Get("SessionKey"));
//echo $sql;
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update");
return false;
}
return true;
}
function Create()
{
global $objConfig;
$this->Set("LastAccessed", time());
if(!is_numeric($this->Get("PortalUserId")))
{
$this->Set("PortalUserId",0);
}
if(!strlen($this->Get("GroupList")))
{
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
$sql = "INSERT INTO ".GetTablePrefix()."UserSession (";
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$key);
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$key);
}
}
$sql = sprintf('%s ) VALUES (',$sql);
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr($value));
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr($value));
}
}
$sql = sprintf('%s)',$sql);
//echo $sql."<br>\n";
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Create");
return false;
}
return true;
}
function LoadFromTempKey($id=NULL)
{
global $objLanguages, $objConfig,$m_var_list;
$referer = $_SERVER["HTTP_REFERER"];
//echo "Referer: $referer <br>\n";
if(strlen($referer) && strpos($referer,"env="))
{
$keystart = strpos($referer,"env=")+4;
$referer = substr($referer,$keystart);
$keyend = strpos($referer,"-");
$LastKey = substr($referer,0,$keyend);
if(strlen($LastKey))
{
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE (CurrentTempKey = '$id' OR PrevTempKey='$id' OR CurrentTempKey='$LastKey' OR PrevTempKey='$LastKey') ";
}
else
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL";
}
else
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if (is_array($data))
{
foreach($data as $field => $value)
{
$mname = "m_" . $field;
$this->$mname = $data[$field];
}
if($this->Get("CurrentTempKey")) {
$this->Set("PrevTempKey",$this->Get("CurrentTempKey"));
$this->UseTempKeys=TRUE;
}
if (!$this->Get("CurrentTempKey") || !strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path"))) {
//$this->Set("PrevTempKey",$this->Get("CurrentTempKey"));
//$this->Set("CurrentTempKey",$this->GetUniqueKey());
$this->UseTempKeys=FALSE;
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
//$this->UseTempKeys=TRUE;
$this->Update();
return true;
}
else
{
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
$this->Set("CurrentTempKey",$this->GetUniqueKey());
return false;
}
}
function LoadFromDatabase($id)
{
if(!isset($id))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'",$id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if (is_array($data))
{
foreach($data as $field => $value)
{
$mname = "m_" . $field;
$this->$mname = $data[$field];
}
return true;
}
else
{
return false;
}
}
function Login($userLogin, $userPassword)
{
global $expired, $objConfig;
if($userLogin == "root")
{
// logging in "root" (admin only)
$rootpass = $objConfig->Get("RootPass");
if($rootpass!=$userPassword)
{
return FALSE;
}
else
{
if(!strlen($this->GetSessionKey()))
$this->GetNewSession();
$this->Set("PortalUserId",-1);
$this->Update();
return TRUE;
}
}
else
{
// logging in any user (admin & front)
$pre = GetTablePrefix();
$sql = "SELECT *,MD5(".$pre."PortalUser.Password) as md5pw FROM ".$pre."PortalUser LEFT JOIN ".$pre."UserGroup USING (PortalUserId) "
."LEFT JOIN ".$pre."PortalGroup ON (".$pre."UserGroup.GroupId=".$pre."PortalGroup.GroupId)
WHERE
".$pre."PortalUser.Login='$userLogin' AND ".$pre."PortalUser.Status=1
AND (".$pre."PortalUser.Password='$userPassword' OR MD5(".$pre."PortalUser.Password)='$userPassword' OR ".$pre."PortalUser.Password='".md5($userPassword)."')
ORDER BY ".$pre."UserGroup.PrimaryGroup DESC, ".$pre."PortalGroup.Personal DESC";
//echo $sql."<br>\n";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Login");
return false;
}
if($result->EOF)
return false;
}
if(!strlen($this->GetSessionKey()))
{
$this->GetNewSession();
}
$this->Set("PortalUserId", $result->fields["PortalUserId"]);
if(strlen($result->fields["tz"])>0)
$this->Set("tz",$result->fields["tz"]);
$PrimaryGroup=0;
$PersonalGroup=0;
$GroupList = array();
while($result && !$result->EOF)
{
$skipadd=0;
$g = $result->fields["GroupId"];
if($result->fields["PrimaryGroup"]==1)
{
$PrimaryGroup = $g;
$skipadd=1;
}
if($result->fields["Personal"]==1)
{
$PersonalGroup=$g;
$skipadd=0;
}
if(!$skipadd)
$GroupList[] = $g;
$result->MoveNext();
}
$extra_groups = implode(",",$GroupList);
if($PrimaryGroup)
$extra_groups = $PrimaryGroup.",".$extra_groups;
if($PersonalGroup)
{
$this->Set("GroupId",$PersonalGroup);
//$extra_groups .= ",".$PersonalGroup;
}
else
{
$this->Set("GroupId",$PrimaryGroup);
}
$this->Set("GroupList", $extra_groups);
$this->Set("LastAccessed",date("U"));
$this_login = $this->GetPersistantVariable("ThisLogin");
$this->SetPersistantVariable("LastLogin", $this_login);
$this->SetPersistantVariable("ThisLogin", time());
$this->ResetSysPermCache();
$this->PermCache = array();
$this->Update();
if($userLogin != 'root')
{
if( ! $this->HasSystemPermission('LOGIN') )
{
$this->Logout();
return false;
}
}
return true;
}
function Logout()
{
global $objConfig;
$this->Set("PortalUserId", 0);
$this->Set("GroupId", $objConfig->Get("User_GuestGroup"));
#$this->SetPersistantVariable("LastLogin", time());
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
$this->Set("IpAddress",$_SERVER['REMOTE_ADDR']);
$this->DeleteSessionData($this->GetSessionKey());
$this->Update();
$this->Delete();
$this->ResetSysPermCache();
$this->PermCache = array();
}
function SetVariable( $variableName, $variableValue)
{
global $objConfig, $FrontEnd;
$objConfig->Set($variableName,$variableValue,2);
//if(!(int)$FrontEnd==1)
//{
$sessionkey = $this->GetSessionKey();
$sql = "SELECT * FROM ".GetTablePrefix()."SessionData WHERE VariableName='$variableName' AND SessionKey='$sessionkey'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$sql = "UPDATE ".GetTablePrefix()."SessionData SET VariableValue='$variableValue' WHERE VariableName='$variableName' AND SessionKey='$sessionkey'";
}
else
$sql = "INSERT INTO ".GetTablePrefix()."SessionData (VariableName,VariableValue,SessionKey) VALUES ('$variableName','$variableValue','$sessionkey')";
$this->adodbConnection->Execute($sql);
// echo "<BR>UPDATE: $sql<BR>";
//}
}
function SetPersistantVariable($variableName, $variableValue)
{
global $objConfig, $objUsers;
$userid = (int)$this->Get("PortalUserId");
if($userid > 0)
{
if(!is_object($this->CurrentUser))
$this->CurrentUser = $objUsers->GetItem($this->Get("PortalUserId"));
if(!$this->CurrentUser->VarsLoaded)
$this->CurrentUser->LoadPersistantVars();
//echo "setting current user' $variableName, $variableValue<br>";
$this->CurrentUser->SetPersistantVariable($variableName, $variableValue);
//$this->SetVariable($variableName,$variableValue);
}
else
$this->SetVariable($variableName,$variableValue);
}
function GetPersistantVariable($variableName)
{
global $objConfig, $objUsers;
if(is_numeric($this->Get("PortalUserId")))
{
if(!is_object($this->CurrentUser))
$this->CurrentUser = $objUsers->GetItem($this->Get("PortalUserId"));
if(!$this->CurrentUser->VarsLoaded)
$this->CurrentUser->LoadPersistantVars();
$val = $this->CurrentUser->GetPersistantVariable($variableName);
}
if(!strlen($val))
$val = $objConfig->Get($variableName);
return $val;
}
function GetVariable($variableName)
{
global $objConfig;
return $objConfig->Get($variableName);
}
function LoadSessionData()
{
global $objConfig, $objUsers;
if(is_numeric($this->Get("PortalUserId")))
{
$sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."SessionData where SessionKey='" . $this->Get("SessionKey") . "'";
//echo $sql."<br>\n";
$result = $this->adodbConnection->Execute($sql);
while ($result && !$result->EOF)
{
$data = $result->fields;
//echo "<PRE>"; print_r($data); echo "</PRE>";
$objConfig->Set($data["VariableName"],$data["VariableValue"],FALSE);
$result->MoveNext();
}
if(!is_object($this->CurrentUser))
$this->CurrentUser = $objUsers->GetItem($this->Get("PortalUserId"));
if(!$this->CurrentUser->VarsLoaded)
$this->CurrentUser->LoadPersistantVars();
}
if((int)$this->GetPersistantVariable("Language"))
$this->Set("Language",$objConfig->Get("Language"));
$this->DeleteExpiredSessions();
return true;
}
function DeleteSessionData($key)
{
$sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey='$key'";
$this->adodbConnection->Execute($sql);
}
function SaveSessionData()
{
global $objConfig;
//echo "Saving Session Data..<br>\n";
if($this->SessionEnabled())
{
$data = $objConfig->GetDirtySessionValues(2); //session data
//echo "<PRE>"; print_r($data); echo "</PRE>";
$sessionkey = $this->GetSessionKey();
foreach($data as $field=>$value)
{
$sql = "UPDATE ".GetTablePrefix()."SessionData SET VariableValue='$value' WHERE VariableName='$field' AND SessionKey='$sessionkey'";
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
if($this->adodbConnection->Affected_Rows()==0)
{
$sql = "INSERT INTO ".GetTablePrefix()."SessionData (VariableName,VariableValue,SessionKey) VALUES ('$field','$value','$sessionkey')";
$this->adodbConnection->Execute($sql);
}
// echo $sql."<br>\n";
}
}
}
function DeleteEditTables()
{
$tables = $this->adodbConnection->MetaTables();
$sql = "SHOW TABLES";
//echo "<PRE>";print_r($tables); echo "</PRE>";
for($i=0;$i<count($tables);$i++)
{
$t = strtoupper($tables[$i]);
$p = strtoupper(GetTablePrefix()."ses_ad");
$k = substr($t,0,strlen($p));
if($k == $p && strpos($t,"FD_")>0)
{
$key = "AD".strtoupper(substr($t,strlen($p),strpos($t,"FD_")-strlen($p)))."FD";
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE SessionKey='$key'";
//echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
if(!$rs || $rs->EOF)
{
//echo "Dropping Table $tables[$i] <br>\n";
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$tables[$i]);
}
}
}
}
function DeleteExpiredSessions()
{
global $objConfig;
$cutoff = time()-$objConfig->Get("SessionTimeout");
$thiskey = $this->GetSessionKey();
$sql = "SELECT SessionKey from ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff AND SessionKey != '$thiskey'";
$result = $this->adodbConnection->Execute($sql);
$keys = array();
while ($result && !$result->EOF)
{
$keys[] = "SessionKey='" . $result->fields["SessionKey"] . "'";
$result->MoveNext();
}
if(count($keys)>0)
{
$keywhere = implode(" OR ", $keys);
$sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE $keywhere";
//echo $sql;
$this->adodbConnection->Execute($sql);
$this->adodbConnection->Execute("DELETE FROM ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff");
$this->DeleteEditTables();
}
}
function SetSysPermCache()
{
unset($this->SysPermCache);
$GroupList = $this->Get("GroupList");
if(strlen($GroupList) && $GroupList !="0")
{
$this->SysPermCache = array();
- $sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Type=1 AND PermissionValue=1 AND GroupId IN (".$GroupList.")";
+ $sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Type=1 AND GroupId IN (".$GroupList.")";
//echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$val = $rs->fields["PermissionValue"];
- if($val==1)
- $this->SysPermCache[$rs->fields["Permission"]] = 1;
+ //if($val==1)
+ $this->SysPermCache[$rs->fields["Permission"]] = $val;
$PermList[] = $rs->fields["Permission"];
$rs->MoveNext();
}
if( isset($PermList) && count($PermList) > 0) // I think this is never issued (comment by Alex)
$this->SetVariable("SysPerm",implode(",",$PermList));
}
}
function GetSysPermCache()
{
$perms = trim($this->GetVariable("SysPerm"));
if(!strlen($perms))
{
$this->SetSysPermCache();
}
else
{
$p = explode(",",$perms);
$this->SysPermCache = array();
for($i=0;$i<count($p);$i++)
{
$n = $p[$i];
$this->SysPermCache[$n]=1;
}
}
}
function SysPermCacheLoaded()
{
return (isset($this->SysPermCache));
}
function ResetSysPermCache()
{
// echo "Resetting Perm Cache<br>\n";
$this->SetVariable("SysPerm","");
unset($this->SysPermCache);
//$this->SysPermCache=array();
}
function HasSystemPermission($PermissionName)
{
global $objGroups;
if($this->Get("PortalUserId")==-1 && ($PermissionName=="ADMIN" || $PermissionName=="LOGIN"))
return TRUE;
//echo "Looking up $PermissionName:".$this->Get("GroupList")."<br>\n";
//echo $this->Get("GroupList")." - ".$this->PermCacheGroups;
$GroupList = $this->Get("GroupList");
if(substr($GroupList,-1)==",")
{
$GroupList = substr($GroupList,0,-1);
$this->Set("GroupList",$GroupList);
}
//print_pre( $GroupList);
if($this->Get("GroupList")!=$this->PermCacheGroups)
$this->ResetSysPermCache();
if(!$this->SysPermCacheLoaded())
{
//echo "Loading Perm Cache<br>\n";
$this->GetSysPermCache();
$this->PermCacheGroups = $this->Get("GroupList");
}
//echo "SysPerm $PermissionName: [". $this->SysPermCache[$PermissionName]."]<br>\n";
return isset($this->SysPermCache[$PermissionName]) ? $this->SysPermCache[$PermissionName] == 1 : false;
}
function HasCatPermission($PermissionName,$CatId=NULL)
{
global $objCatList, $objUsers;
$PermSet =FALSE;
$Value = 0;
if($this->Get("PortalUserId")==-1)
return TRUE;
if(!strlen($PermissionName))
return FALSE;
$GroupList = $this->Get("GroupList");
if(substr($GroupList,-1)==",")
{
$GroupList = substr($GroupList,0,-1);
$this->Set("GroupList",$GroupList);
}
if(!strlen($this->Get("SessionKey")))
$this->Set("GroupId",0);
if(strlen(trim($GroupList)))
{
if(strlen($this->Get("GroupId")))
{
$GroupList = $this->Get("GroupId").",".$GroupList;
}
}
else
{
$GroupList = $this->Get("GroupId");
}
if($CatId == NULL)
{
$CatId = $objCatList->CurrentCategoryID();
}
$Cat = &$objCatList->GetCategory($CatId);
$Value="";
for($p=0;$p<count($this->PermCache);$p++)
{
$pItem = $this->PermCache[$p];
if($pItem["perm"]==$PermissionName && $pItem["cat"]==$CatId)
{
$Value=$pItem["value"];
break;
}
}
if(is_object($Cat) && !is_numeric($Value))
{
$Value = 0;
$CatList = $Cat->Get("ParentPath");
$CatList = substr($CatList,1,-1);
$CatList = str_replace("|",",",$CatList);
if(strlen($CatList))
{
$CatList ="0,".$CatList;
}
else
$CatList = "0";
$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Permission LIKE '$PermissionName' AND CatId IN ($CatList) AND GroupId IN ($GroupList)";
// echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
$PermValue = array();
while($rs && !$rs->EOF)
{
$index = $rs->fields["CatId"];
if(!is_numeric($PermValue[$index]))
$PermValue[$index] = $rs->fields["PermissionValue"];
$rs->MoveNext();
}
$cats = array_reverse(explode(",",$CatList));
for($c=0;$c<count($cats);$c++)
{
$index = $cats[$c];
if( isset($PermValue[$index]) && is_numeric($PermValue[$index]) )
{
$Value = $PermValue[$index];
break;
}
}
$perm = array();
$perm["perm"] = $PermissionName;
$perm["cat"] = $CatId;
$perm["value"] = $Value;
array_push($this->PermCache, $perm);
}
//echo $GroupList." Has Permission $PermissionName = $Value<br>\n";
return $Value;
}
function HasCatPermInList($PermList,$CatId=NULL, $System=FALSE)
{
$value = 0;
if(strlen($PermList))
{
$plist = explode(",",$PermList);
$value=0;
for($p=0;$p<count($plist);$p++)
{
if($this->HasCatPermission($plist[$p]))
{
$value = 1;
break;
}
else
{
if($System)
{
if($this->HasSystemPermission($plist[$p]))
{
$value = 1;
break;
}
}
}
}
}
return $value;
}
function GetACLClause()
{
$GroupList = $this->Get("GroupList");
if(strlen($GroupList))
$Groups = explode(",",$GroupList);
$acl_where = "";
if(@count($Groups)>0 && is_array($Groups))
{
$acl_where = array();
for($i=0;$i<count($Groups);$i++)
{
$g = $Groups[$i];
if(strlen($g)>0)
$acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) ";
}
if(count($acl_where))
{
$acl_where = "(".implode(" OR ",$acl_where).")";
}
else
$acl_where = "(FIND_IN_SET(0,acl))";
}
else
$acl_where = "(FIND_IN_SET(0,acl))";
return $acl_where;
}
function GetEditTable($base_table)
{
$prefix = GetTablePrefix();
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_edit_".$base_table;
//echo "Table: $table <br>\n";
return $table;
}
function GetSessionTable($base_table,$name)
{
$prefix = GetTablePrefix();
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_".$name.$base_table;
//echo "Table: $table <br>\n";
return $table;
}
function GetSearchTable($base_table="")
{
$prefix = GetTablePrefix();
if(strlen($base_table))
{
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_search_".$base_table;
}
else
$table = $this->GetSessionTable('Search',''); //$prefix."ses_".$this->GetSessionKey()."_search";
return $table;
}
function GetTotalSessions()
{
# $time = time() - 900;
$sql = "SELECT count(*) as SesCount FROM ".GetTablePrefix()."UserSession";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"GetTotalSessions");
return false;
}
return $result->fields["SesCount"];
}
function Query_UserSession($whereClause,$orderByClause)
{
$resultSet = array();
$sql = "SELECT ".GetTablePrefix()."* FROM ".GetTablePrefix()."UserSession ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_UserSession");
return false;
}
while (!$result->EOF)
{
$item = new clsUserSession(NULL);
$item->Set("SessionKey",$result->fields["SessionKey"]);
$item->Set("LastAccessed", $result->fields["LastAccessed"]);
$item->Set("PortalUserId", $result->fields["PortalUserId"]);
$item->Set("Language", $result->fields["Language"]);
$item->Set("Theme" , $result->fields["Theme"]);
array_push($resultSet,$item);
$result->MoveNext();
}
return $resultSet;
}
function GetUniqueKey()
{
while(true)
{
/* create the new session key here */
mt_srand(100000000*(double)microtime());
$sessionId=strtoupper(sprintf("AD%xFD",mt_rand(100000000,999999999))); //9 digit hex session id
$query = "select SessionKey from ".GetTablePrefix()."UserSession ";
$query .= "where SessionKey='$sessionId' OR CurrentTempKey='$sessionId' OR PrevTempKey='$sessionId'";
$rs = $this->adodbConnection->Execute($query);
if($rs->EOF)
break;
if($i>100)
{
return "";
}
$i++;
}
//echo "Getting Unique Key: $sessionId<br>";
return $sessionId;
}
function GetNewSession()
{
global $sessionId, $objConfig, $objLanguages, $m_var_list;
$i=0;
if($this->Get("PortalUserId")>0 || $objConfig->Get("GuestSessions")==1)
{
//echo "Creating Session<br>\n";
$sessionId = $this->GetUniqueKey();
$this->Set("SessionKey", $sessionId);
$this->Set("CurrentTempKey",$sessionId);
if($m_var_list["lang"])
{
$this->Set("Language",$m_var_list["lang"]);
}
else
$this->Set("Language", $objLanguages->GetPrimary());
$this->SetThemeName();
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->UpdateAccessTime();
$this->Set("IpAddress", $_SERVER['REMOTE_ADDR'] );
$this->Create();
}
else
$this->Set("SessionKey","");
}
function SessionEnabled()
{
//trace();
$res = FALSE;
$key = $this->GetSessionKey();
if(strlen($key)>0)
$res = TRUE;
return $res;
}
function GetSessionKey()
{
return $this->Get("SessionKey");
}
function SetThemeName($id=0)
{
global $objThemes;
if($id==0)
$id = $objThemes->GetPrimaryTheme();
$Theme = $objThemes->GetItem($id);
$name = $Theme->Get("Name");
$this->Set("Theme",$name);
//$this->Update();
}
function ValidSession($SessionKey=NULL)
{
global $objConfig;
$a = $this->Get("LastAccessed");
$cutoff = time()-$objConfig->Get("SessionTimeout");
//echo $a." ".$cutoff."<br>";
//$ip = ($_SERVER['REMOTE_ADDR'] == $this->Get("IpAddress"));
//echo $this->Get("IpAddress");
//$ip = TRUE;
if ($a < $cutoff) {
//$this->UpdateAccessTime();
}
return ($a >= $cutoff);
}
function UpdateAccessTime()
{
$now = time();
$this->Set("LastAccessed",$now);
}
function InSpamControl($ResourceId,$DataType=NULL)
{
static $ClearStat;
if(!$ClearStat)
$this->PurgeSpamControl();
$ClearStat=1;
if(strlen($DataType))
$DataType="'".$DataType."'";
$sql = "SELECT count(*) as SpamCount FROM ".GetTablePrefix()."SpamControl WHERE ItemResourceId=$ResourceId AND DataType=$DataType";
if($this->Get("PortalUserId")==0)
{
$sql .= " AND PortalUserId=0 AND IPaddress='".$_SERVER["REMOTE_ADDR"]."'";
}
else
{
$sql .= " AND PortalUserId=".$this->Get("PortalUserId");
}
$rs = $this->adodbConnection->Execute($sql);
$value = (int)$rs->fields["SpamCount"];
if($value>0)
{
return TRUE;
}
else
return FALSE;
}
function AddToSpamControl($ResourceId,$secstoexpire,$DataType=NULL)
{
$expire = adodb_date("U") + $secstoexpire;
if(strlen($DataType))
$DataType = "'".$DataType."'";
$sql = "INSERT INTO ".GetTablePrefix()."SpamControl (ItemResourceId,IPaddress,Expire,PortalUserId,DataType) VALUES (";
$sql .= $ResourceId.",'".$_SERVER["REMOTE_ADDR"]."',$expire,".$this->Get("PortalUserId").",$DataType)";
//echo $sql;
$this->adodbConnection->Execute($sql);
}
function PurgeSpamControl()
{
$sql = "DELETE FROM ".GetTablePrefix()."SpamControl WHERE Expire<".adodb_date("U");
$this->adodbConnection->Execute($sql);
}
}/* clsUserSession */
?>
Property changes on: trunk/kernel/include/usersession.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13
\ No newline at end of property
+1.14
\ No newline at end of property
Index: trunk/admin/images/toolbar/tool_import_language_f3.gif
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes on: trunk/admin/images/toolbar/tool_import_language_f3.gif
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/admin/images/toolbar/tool_import_language.gif
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes on: trunk/admin/images/toolbar/tool_import_language.gif
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/admin/images/toolbar/tool_import_language_f2.gif
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes on: trunk/admin/images/toolbar/tool_import_language_f2.gif
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/admin/install.php
===================================================================
--- trunk/admin/install.php (revision 414)
+++ trunk/admin/install.php (revision 415)
@@ -1,1881 +1,1894 @@
<?php
error_reporting(0);
define("GET_LICENSE_URL", "http://www.intechnic.com/myaccount/license.php");
define('BACKUP_NAME', 'dump(.*).txt'); // how backup dump files are named
$general_error = '';
$pathtoroot = "";
if(!strlen($pathtoroot))
{
$path=dirname(realpath(__FILE__));
//$path=dirname(realpath(__FILE__));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$path_char = GetPathChar();
//phpinfo(INFO_VARIABLES);
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
$is_install = TRUE;
$admin = substr($path,strlen($pathtoroot));
$state = isset($_GET["state"]) ? $_GET["state"] : '';
if(!strlen($state))
{
$state = isset($_POST['state']) ? $_POST['state'] : '';
}
include($pathtoroot.$admin."/install/install_lib.php");
$install_type = GetVar('install_type', true);
$force_finish = isset($_REQUEST['ff']) ? true : false;
$ini_file = $pathtoroot."config.php";
if(file_exists($ini_file))
{
$write_access = is_writable($ini_file);
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace('-', '', $key);
global $$key;
$$key = $value;
}
}
}
else
{
$state="";
$write_access = is_writable($pathtoroot);
if($write_access)
{
set_ini_value("Database", "DBType", "");
set_ini_value("Database", "DBHost", "");
set_ini_value("Database", "DBUser", "");
set_ini_value("Database", "DBUserPassword", "");
set_ini_value("Database", "DBName", "");
set_ini_value("Module Versions", "In-Portal", "");
save_values();
}
}
$titles[1] = "General Site Setup";
$configs[1] = "in-portal:configure_general";
$mods[1] = "In-Portal";
$titles[2] = "User Setup";
$configs[2] = "in-portal:configure_users";
$mods[2] = "In-Portal:Users";
$titles[3] = "Category Display Setup";
$configs[3] = "in-portal:configure_categories";
$mods[3] = "In-Portal";
// simulate rootURL variable: begin
$rootURL = 'http://'.dirname($_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
$tmp = explode('/', $rootURL);
if( $tmp[ count($tmp) - 1 ] == $admin) unset( $tmp[ count($tmp) - 1 ] );
$rootURL = implode('/', $tmp).'/';
unset($tmp);
//echo "RU: $rootURL<br>";
// simulate rootURL variable: end
$db_savings = Array('dbinfo', 'db_config_save', 'db_reconfig_save'); //, 'reinstall_process'
if( isset($g_DBType) && $g_DBType && strlen($state)>0 && !in_array($state, $db_savings) )
{
require_once($pathtoroot."kernel/startup.php");
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
//admin only util
$pathtolocal = $pathtoroot."kernel/";
require_once ($pathtoroot.$admin."/include/elements.php");
//require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once ($pathtolocal."admin/include/navmenu.php");
require_once($pathtoroot.$admin."/toolbar.php");
}
function GetPathChar($path = null)
{
if( !isset($path) ) $path = $GLOBALS['pathtoroot'];
$pos = strpos($path, ':');
return ($pos === false) ? "/" : "\\";
}
function SuperStrip($str, $inverse = false)
{
$str = $inverse ? str_replace("%5C","\\",$str) : str_replace("\\","%5C",$str);
return stripslashes($str);
}
require_once($pathtoroot.$admin."/install/inst_ado.php");
$helpURL = $rootURL.$admin.'/help/install_help.php?destform=popup&help_usage=install';
?>
<html>
<head>
<title>In-Portal Installation</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<meta name="generator" content="Notepad">
<link rel="stylesheet" type="text/css" href="include/style.css">
<LINK REL="stylesheet" TYPE="text/css" href="install/2col.css">
<SCRIPT LANGUAGE="JavaScript1.2">
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function swap(imgid, src){
var ob = document.getElementById(imgid);
ob.src = 'images/' + src;
}
function Continue() {
document.iform1.submit();
}
function CreatePopup(window_name, url, width, height)
{
// creates a popup window & returns it
if(url == null && typeof(url) == 'undefined' ) url = '';
if(width == null && typeof(width) == 'undefined' ) width = 750;
if(height == null && typeof(height) == 'undefined' ) height = 400;
return window.open(url,window_name,'width='+width+',height='+height+',status=yes,resizable=yes,menubar=no,scrollbars=yes,toolbar=no');
}
function ShowHelp(section)
{
var frm = document.getElementById('help_form');
frm.section.value = section;
frm.method = 'POST';
CreatePopup('HelpPopup','<?php echo $rootURL.$admin; ?>/help/blank.html'); // , null, 600);
frm.target = 'HelpPopup';
frm.submit();
}
</SCRIPT>
</head>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" style="height: 100%">
<form name="help_form" id="help_form" action="<?php echo $helpURL; ?>" method="post"><input type="hidden" id="section" name="section" value=""></form>
<form enctype="multipart/form-data" name="iform1" id="iform1" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
<tr>
<td height="90">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="90">
<tr>
<td rowspan="3" valign="top"><a href="http://www.in-portal.net" target="_top"><img alt="In-portal" src="images/globe.gif" width="84" height="91" border="0"></a></td>
<td rowspan="3" valign="top"><a href="http://www.in-portal.net" target="_top"><img alt="In-portal" src="images/logo.gif" width="150" height="91" border="0"></a></td>
<td rowspan="3" width="100000" align="right">&nbsp;</td>
<td width="400"><img alt="" src="images/blocks.gif" width="400" height="73"></td>
</tr>
<tr><td align="right" background="images/version_bg.gif" class="head_version" valign="top"><img alt="" src="images/spacer.gif" width="1" height="14">In-Portal Version <?php echo GetMaxPortalVersion($pathtoroot.$admin)?>: English US</td></tr>
<tr><td><img alt="" src="images/blocks2.gif" width="400" height="2"><br></td></tr>
<tr><td bgcolor="black" colspan="4"><img alt="" src="images/spacer.gif" width="1" height="1"><br></td></tr>
</table>
</td>
</tr>
<?php
require_once($pathtoroot."kernel/include/adodb/adodb.inc.php");
if(!strlen($state))
$state = @$_POST["state"];
//echo $state;
if(strlen($state)==0)
{
$ado =& inst_GetADODBConnection();
$installed = $ado ? TableExists($ado,"ConfigurationAdmin,Category,Permissions") : false;
if(!minimum_php_version("4.1.2"))
{
$general_error = "You have version ".phpversion()." - please upgrade!";
//die();
}
if(!$write_access)
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "Install cannot write to config.php in the root directory of your in-portal installation ($pathtoroot).";
//die();
}
if(!is_writable($pathtoroot."themes/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Theme directory must be writable (".$pathtoroot."themes/).";
//die();
}
if(!is_writable($pathtoroot."kernel/images/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Image Upload directory must be writable (".$pathtoroot."kernel/images/).";
//die();
}
if(!is_writable($pathtoroot."admin/backupdata/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Backup directory must be writable (".$pathtoroot."admin/backupdata/).";
//die();
}
if(!is_writable($pathtoroot."admin/export/"))
{
if ($general_error != '') {
$general_error .= '<br /><br />';
}
$general_error .= "In-portal's Exportd directory must be writable (".$pathtoroot."admin/export/).";
//die();
}
if($installed)
{
$state="reinstall";
}
else {
$state="dbinfo";
}
}
if($state=="reinstall_process")
{
$login_err_mesg = ''; // always init vars before use
if( !isset($g_License) ) $g_License = '';
$lic = base64_decode($g_License);
if(strlen($lic))
{
inst_ParseLicense($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
$LoggedIn = FALSE;
if($_POST["UserName"]=="root")
{
$ado =& inst_GetADODBConnection();
$sql = "SELECT * FROM ".$g_TablePrefix."ConfigurationValues WHERE VariableName='RootPass'";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
{
$RootPass = $rs->fields["VariableValue"];
if(strlen($RootPass)>0)
$LoggedIn = ($RootPass==md5($_POST["UserPass"]));
}
}
else
{
$act = '';
if (ConvertVersion($g_InPortal) >= ConvertVersion("1.0.5")) {
$act = 'check';
}
$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['UserName'])."&password=".md5($_POST['UserPass'])."&action=$act&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
$login_err_mesg = "Unable to connect to the Intechnic server!";
$LoggedIn = false;
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$login_err_mesg = substr($rcontents, 6);
$LoggedIn = false;
}
else {
$LoggedIn = true;
}
}
//$LoggedIn = ($i_User == $_POST["UserName"] && ($i_Pswd == $_POST["UserPass"]) && strlen($i_User)>0) || strlen($i_User)==0;
}
if($LoggedIn)
{
if (!(int)$_POST["inp_opt"]) {
$state="reinstall";
$inst_error = "Please select one of the options above!";
}
else {
switch((int)$_POST["inp_opt"])
{
case 0:
$inst_error = "Please select an option above";
break;
case 1:
/* clean out all tables */
$install_type = 4;
$ado =& inst_GetADODBConnection();
$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
RunSchemaFile($ado,$filename);
/* run install again */
$state="license";
break;
case 2:
$install_type = 3;
$state="dbinfo";
break;
case 3:
$install_type = 5;
$state="license";
break;
case 4:
$install_type = 6;
/* clean out all tables */
$ado =& inst_GetADODBConnection();
//$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
//RunSchemaFile($ado,$filename);
/* run install again */
$state="restore_select";
break;
case 5:
$install_type = 7;
/* change DB config */
$state="db_reconfig";
break;
case 6:
$install_type = 8;
$state = "upgrade";
break;
}
}
}
else
{
$state="reinstall";
$login_error = $login_err_mesg;//"Invalid Username or Password - Try Again";
}
}
if ($state == "upgrade") {
$ado =& inst_GetADODBConnection();
$Modules = array();
$Texts = array();
- if (str_replace('.', '', GetMaxPortalVersion($pathtoroot.$admin)) >= 105 && ($g_LicenseCode == '' && $g_License != '')) {
+ if (ConvertVersion(GetMaxPortalVersion($pathtoroot.$admin)) >= ConvertVersion("1.0.5") && ($g_LicenseCode == '' && $g_License != '')) {
$state = 'reinstall';
$inst_error = "Your license must be updated before you can upgrade. Please don't use 'Existing License' option, instead either Download from Intechnic or Upload a new license file!";
}
else {
- $sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules";
+ $sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules ORDER BY LoadOrder asc";
$rs = $ado->Execute($sql);
$i = 0;
while ($rs && !$rs->EOF) {
$p = strtolower($rs->fields['Name']);
if ($p == 'in-portal') {
$p = '';
}
$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
$dir = @dir($dir_name);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
if (strstr($file, 'inportal_upgrade_v')) {
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
$sql = "SELECT count(*) AS count FROM ".$g_TablePrefix."Modules WHERE Name = '".$rs->fields['Name']."' AND Version = '$file'";
$rs1 = $ado->Execute($sql);
if ($rs1->fields['count'] == 0 && ConvertVersion($file) > ConvertVersion($rs->fields['Version'])) {
if ($Modules[$i-1] == $rs->fields['Name']) {
$Texts[$i-1] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
$i--;
}
else {
$Texts[$i] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
$Modules[$i] = $rs->fields['Name'];
}
$i++;
}
}
}
}
$rs->MoveNext();
}
$include_file = $pathtoroot.$admin."/install/upgrade.php";
}
}
if ($state == "upgrade_process") {
$ado =& inst_GetADODBConnection();
- $mod_arr = $_POST['modules'];
-
+ $mod_arr = $_POST['modules'];
+
foreach($mod_arr as $p)
{
$mod_name = strtolower($p);
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '$p'";
$rs = $ado->Execute($sql);
$current_version = $rs->fields['Version'];
if ($mod_name == 'in-portal') {
$mod_name = '';
}
$dir_name = $pathtoroot.$mod_name."/admin/install/upgrades/";
$dir = @dir($dir_name);
+ $upgrades_arr = Array();
+
$new_version = '';
- $tmp1 = 0;
- $tmp2 = 0;
while ($file = $dir->read()) {
- if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) {
+ if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) {
if (strstr($file, 'inportal_upgrade_v')) {
- $file_tmp = str_replace("inportal_upgrade_v", "", $file);
- $file_tmp = str_replace(".sql", "", $file_tmp);
-
- if (ConvertVersion($file_tmp) > ConvertVersion($current_version)) {
- $filename = $pathtoroot.$mod_name."/admin/install/upgrades/$file";
- //echo "Running: $filename<br>";
- if(file_exists($filename))
- {
- RunSQLFile($ado, $filename);
- set_ini_value("Module Versions", $p, $try_version);
- save_values();
- }
+ $upgrades_arr[] = $file;
}
- }
- //$tmp2 = $tmp1;
- }
+ }
+ }
+
+ usort($upgrades_arr, "VersionSort");
+
+ foreach($upgrades_arr as $file) {
+ $file_tmp = str_replace("inportal_upgrade_v", "", $file);
+ $file_tmp = str_replace(".sql", "", $file_tmp);
+
+ if (ConvertVersion($file_tmp) > ConvertVersion($current_version)) {
+ $filename = $pathtoroot.$mod_name."/admin/install/upgrades/$file";
+ //echo "Running: $filename<br>";
+ if(file_exists($filename))
+ {
+ RunSQLFile($ado, $filename);
+ }
+ }
}
+
+ set_ini_value("Module Versions", $p, GetMaxPortalVersion($pathtoroot.$mod_name."/admin/"));
+ save_values();
}
- $state = 'languagepack_upgrade';
+
+ $state = 'languagepack_upgrade';
}
// upgrade language pack
if($state=='languagepack_upgrade')
{
$state = 'lang_install_init';
$_POST['lang'][] = 'english.lang';
$force_finish = true;
}
if($state=="db_reconfig_save")
{
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace("-", "", $key);
global $$key;
$$key = $value;
}
}
unset($ado);
$ado = VerifyDB('db_reconfig', 'finish', 'SaveDBConfig', true);
}
if($state=="db_reconfig")
{
$include_file = $pathtoroot.$admin."/install/db_reconfig.php";
}
if($state=="restore_file")
{
if($_POST["submit"]=="Update")
{
$filepath = $_POST["backupdir"];
$state="restore_select";
}
else
{
$filepath = stripslashes($_POST['backupdir']);
$backupfile = $filepath.$path_char.str_replace('(.*)', $_POST['backupdate'], BACKUP_NAME);
if(file_exists($backupfile) && is_readable($backupfile))
{
$ado =& inst_GetADODBConnection();
$show_warning = false;
if (!$_POST['warning_ok']) {
// Here we comapre versions between backup and config
$file_contents = file_get_contents($backupfile);
$file_tmp_cont = explode("#------------------------------------------", $file_contents);
$tmp_vers = $file_tmp_cont[0];
$vers_arr = explode(";", $tmp_vers);
$ini_values = inst_parse_portal_ini($ini_file);
foreach ($ini_values as $key => $value) {
foreach ($vers_arr as $k) {
if (strstr($k, $key)) {
if (!strstr($k, $value)) {
$show_warning = true;
}
}
}
}
//$show_warning = true;
}
if (!$show_warning) {
$filename = $pathtoroot.$admin.$path_char.'install'.$path_char.'inportal_remove.sql';
RunSchemaFile($ado,$filename);
$state="restore_run";
}
else {
$state = "warning";
$include_file = $pathtoroot.$admin."/install/warning.php";
}
}
else {
if ($_POST['backupdate'] != '') {
$include_file = $pathtoroot.$admin."/install/restore_select.php";
$restore_error = "$backupfile not found or could not be read";
}
else {
$include_file = $pathtoroot.$admin."/install/restore_select.php";
$restore_error = "No backup selected!!!";
}
}
}
//echo $restore_error;
}
if($state=="restore_select")
{
if( isset($_POST['backupdir']) ) $filepath = stripslashes($_POST['backupdir']);
$include_file = $pathtoroot.$admin."/install/restore_select.php";
}
if($state=="restore_run")
{
$ado =& inst_GetADODBConnection();
$FileOffset = (int)$_GET["Offset"];
if(!strlen($backupfile))
$backupfile = SuperStrip($_GET['File'], true);
$include_file = $pathtoroot.$admin."/install/restore_run.php";
}
if($state=="db_config_save")
{
set_ini_value("Database", "DBType",$_POST["ServerType"]);
set_ini_value("Database", "DBHost",$_POST["ServerHost"]);
set_ini_value("Database", "DBName",$_POST["ServerDB"]);
set_ini_value("Database", "DBUser",$_POST["ServerUser"]);
set_ini_value("Database", "DBUserPassword",$_POST["ServerPass"]);
set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);
save_values();
$ini_vars = inst_parse_portal_ini($ini_file,TRUE);
foreach($ini_vars as $secname => $section)
{
foreach($section as $key => $value)
{
$key = "g_".str_replace("-", "", $key);
global $$key;
$$key = $value;
}
}
unset($ado);
$ado = VerifyDB('dbinfo', 'license');
}
if($state=="dbinfo")
{
if ($install_type == '') {
$install_type = 1;
}
$include_file = $pathtoroot.$admin."/install/dbinfo.php";
}
if ($state == "download_license") {
$ValidLicense = FALSE;
$lic_login = isset($_POST['login']) ? $_POST['login'] : '';
$lic_password = isset($_POST['password']) ? $_POST['password'] : '';
if ($lic_login != '' && $lic_password != '') {
// Here we determine weather login is ok & check available licenses
$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['login'])."&password=".md5($_POST['password'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$get_license_error = substr($rcontents, 6);
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
if (substr($rcontents, 0, 3) == "SEL") {
$state = "download_license";
$license_select = substr($rcontents, 4);
$include_file = $pathtoroot.$admin."/install/download_license.php";
}
else {
// Here we get one license
$tmp_data = explode('Code==:', $rcontents);
$data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));
inst_ParseLicense($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
$got_license = 1;
}
else {
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
}
}
}
}
else if ($_POST['licenses'] == '') {
$state = "get_license";
$get_license_error = "Username and / or password not specified!!!";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
// Here we download license
$rfile = @fopen(GET_LICENSE_URL."?license_id=".md5($_POST['licenses'])."&dlog=".md5($_POST['dlog'])."&dpass=".md5($_POST['dpass'])."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".base64_encode($_POST['domain']), "r");
if (!$rfile) {
$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
$state = "get_license";
$include_file = $pathtoroot.$admin."/install/get_license.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
if (substr($rcontents, 0, 5) == 'Error') {
$download_license_error = substr($rcontents, 6);
$state = "download_license";
$include_file = $pathtoroot.$admin."/install/download_license.php";
}
else {
$tmp_data = explode('Code==:', $rcontents);
$data = base64_decode(str_replace("In-Portal License File - do not edit!\n", "", $tmp_data[0]));
inst_ParseLicense($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
// old licensing script doen't return 2nd parameter (licanse code)
if( isset($tmp_data[1]) ) set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
}
else {
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
}
}
}
}
if($state=="license_process")
{
$ValidLicense = FALSE;
$tmp_lic_opt = GetVar('lic_opt', true);
switch($tmp_lic_opt)
{
case 1: /* download from intechnic */
$include_file = $pathtoroot.$admin."/install/get_license.php";
$state = "get_license";
//if(!$ValidLicense)
//{
// $state="license";
//}
break;
case 2: /* upload file */
$file = $_FILES["licfile"];
if(is_array($file))
{
move_uploaded_file($file["tmp_name"],$pathtoroot."themes/tmp.lic");
$fp = @fopen($pathtoroot."themes/tmp.lic","rb");
if($fp)
{
$lic = fread($fp,filesize($pathtoroot."themes/tmp.lic"));
fclose($fp);
}
$tmp_data = inst_LoadLicense(FALSE,$pathtoroot."themes/tmp.lic");
$data = $tmp_data[0];
@unlink($pathtoroot."themes/tmp.lic");
inst_ParseLicense($data);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
set_ini_value("Intechnic","License",base64_encode($data));
set_ini_value("Intechnic","LicenseCode",$tmp_data[1]);
save_values();
$state="domain_select";
}
else
$license_error="Invalid License File";
}
if(!$ValidLicense)
{
$state="license";
}
break;
case 3: /* existing */
if(strlen($g_License))
{
$lic = base64_decode($g_License);
inst_ParseLicense($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
if($ValidLicense)
{
$state="domain_select";
}
else
{
$state="license";
$license_error="Invalid or corrupt license detected";
}
}
else
{
$state="license";
$license_error="Missing License File";
}
if(!$ValidLicense)
{
$state="license";
}
break;
case 4:
//set_ini_value("Intechnic","License",base64_encode("local"));
//set_ini_value("Intechnic","LicenseCode",base64_encode("local"));
//save_values();
$state="domain_select";
break;
}
if($ValidLicense)
$state="domain_select";
}
if($state=="license")
{
$include_file = $pathtoroot.$admin."/install/sel_license.php";
}
if($state=="reinstall")
{
$ado =& inst_GetADODBConnection();
$show_upgrade = false;
$sql = "SELECT Name FROM ".$g_TablePrefix."Modules";
$rs = $ado->Execute($sql);
$modules = '';
while ($rs && !$rs->EOF) {
$modules .= strtolower($rs->fields['Name']).',';
$rs->MoveNext();
}
$mod_arr = explode(",", substr($modules, 0, strlen($modules) - 1));
foreach($mod_arr as $p)
{
if ($p == 'in-portal') {
$p = '';
}
$dir_name = $pathtoroot.$p."/admin/install/upgrades/";
$dir = @dir($dir_name);
//echo "<pre>"; print_r($dir); echo "</pre>";
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
if (strstr($file, 'inportal_upgrade_v')) {
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
if ($p == '') {
$p = 'in-portal';
}
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
$rs = $ado->Execute($sql);
if (ConvertVersion($rs->fields['Version']) < ConvertVersion($file)) {
$show_upgrade = true;
}
}
}
}
}
if ( !isset($install_type) || $install_type == '') {
$install_type = 2;
}
$include_file = $pathtoroot.$admin."/install/reinstall.php";
}
if($state=="login")
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
inst_ParseLicense($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
if(!$ValidLicense)
{
$state="license";
}
else
if($i_User == $_POST["UserName"] || $i_Pswd == $_POST["UserPass"])
{
$state = "domain_select";
}
else
{
$state="getuser";
$login_error = "Invalid User Name or Password. If you don't know your username or password, contact Intechnic Support";
}
//die();
}
if($state=="getuser")
{
$include_file = $pathtoroot.$admin."/install/login.php";
}
if($state=="set_domain")
{
if( !is_array($i_Keys) || !count($i_Keys) )
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
inst_ParseLicense($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
}
if($_POST["domain"]==1)
{
$domain = $_SERVER['HTTP_HOST'];
if (strstr($domain, $i_Keys[0]['domain']) || inst_IsLocalSite($domain)) {
set_ini_value("Intechnic","Domain",$domain);
save_values();
$state="runsql";
}
else {
$DomainError = 'Domain name selected does not match domain name in the license!';
$state = "domain_select";
}
}
else
{
$domain = str_replace(" ", "", $_POST["other"]);
if ($domain != '') {
if (strstr($domain, $i_Keys[0]['domain']) || inst_IsLocalSite($domain)) {
set_ini_value("Intechnic","Domain",$domain);
save_values();
$state="runsql";
}
else {
$DomainError = 'Domain name entered does not match domain name in the license!';
$state = "domain_select";
}
}
else {
$DomainError = 'Please enter valid domain!';
$state = "domain_select";
}
}
}
if($state=="domain_select")
{
if(!is_array($i_Keys))
{
$lic = base64_decode($g_License);
if(strlen($lic))
{
inst_ParseLicense($lic);
$ValidLicense = ((strlen($i_User)>0) && (strlen($i_Pswd)>0));
}
}
$include_file = $pathtoroot.$admin."/install/domain.php";
}
if($state=="runsql")
{
$ado =& inst_GetADODBConnection();
$installed = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
if(!$installed)
{
// create tables
$filename = $pathtoroot.$admin."/install/inportal_schema.sql";
RunSchemaFile($ado,$filename);
// insert default info
$filename = $pathtoroot.$admin."/install/inportal_data.sql";
RunSQLFile($ado,$filename);
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = 'In-Portal'";
$rs = $ado->Execute($sql);
set_ini_value("Module Versions", "In-Portal", $rs->fields['Version']);
save_values();
require_once $pathtoroot.'kernel/include/tag-class.php';
if( !is_object($objTagList) ) $objTagList = new clsTagList();
// install kernel specific tags
$objTagList->DeleteTags(); // delete all existing tags in db
// create 3 predifined tags (because there no functions with such names
$t = new clsTagFunction();
$t->Set("name","include");
$t->Set("description","insert template output into the current template");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert","",TRUE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
unset($t);
$t = new clsTagFunction();
$t->Set("name","perm_include");
$t->Set("description","insert template output into the current template if permissions are set");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert","",TRUE);
$t->AddAttribute("_noaccess","tpl","Template to insert if access is denied","",FALSE);
$t->AddAttribute("_permission","","Comma-separated list of permissions, any of which will grant access","",FALSE);
$t->AddAttribute("_module","","Used in place of the _permission attribute, this attribute verifies the module listed is enabled","",FALSE);
$t->AddAttribute("_system","bool","Must be set to true if any permissions in _permission list is a system permission","",FALSE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
unset($t);
$t = new clsTagFunction();
$t->Set("name","mod_include");
$t->Set("description","insert templates from all enabled modules. No error occurs if the template does not exist.");
$t->Create();
$t->AddAttribute("_template","tpl","Template to insert. This template path should be relative to the module template root directory","",TRUE);
$t->AddAttribute("_modules","","Comma-separated list of modules. Defaults to all enabled modules if not set","",FALSE);
$t->AddAttribute("_supresserror","bool","Supress missing template errors","",FALSE);
$t->AddAttribute("_dataexists","bool","Only include template output if content exists (content is defined by the tags in the template)","",FALSE);
$t->AddAttribute("_nodatatemplate","tpl","Template to include if the nodataexists condition is true","",FALSE);
$objTagList->ParseFile($pathtoroot.'kernel/parser.php'); // insert module tags
if( is_array($ItemTagFiles) )
foreach($ItemTagFiles as $file)
$objTagList->ParseItemFile($pathtoroot.$file);
$state="RootPass";
}
else {
$include_file = $pathtoroot.$admin."/install/install_finish.php";
$state="finish";
}
}
if ($state == "finish") {
+ $ado =& inst_GetADODBConnection();
+ $PhraseTable = GetTablePrefix()."ImportPhrases";
+ $EventTable = GetTablePrefix()."ImportEvents";
+ $ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+ $ado->Execute("DROP TABLE IF EXISTS $EventTable");
+
$include_file = $pathtoroot.$admin."/install/install_finish.php";
}
if($state=="RootSetPass")
{
$pass = $_POST["RootPass"];
if(strlen($pass)<4)
{
$PassError = "Root Password must be at least 4 characters";
$state = "RootPass";
}
else if ($pass != $_POST["RootPassConfirm"]) {
$PassError = "Passwords does not match";
$state = "RootPass";
}
else
{
$pass = md5($pass);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$pass' WHERE VariableName='RootPass' OR VariableName='RootPassVerify'";
$ado =& inst_GetADODBConnection();
$ado->Execute($sql);
$state="modselect";
}
}
if($state=="RootPass")
{
$include_file = $pathtoroot.$admin."/install/rootpass.php";
}
if($state=="lang_install_init")
{
include_once($pathtoroot."kernel/include/xml.php");
$ado =& inst_GetADODBConnection();
if (TableExists($ado, "Language,Phrase")) {
$MaxInserts = 200;
$PhraseTable = GetTablePrefix()."ImportPhrases";
$EventTable = GetTablePrefix()."ImportEvents";
$sql = "CREATE TABLE $PhraseTable SELECT Phrase,Translation,PhraseType,LanguageId FROM ".GetTablePrefix()."Phrase WHERE PhraseId=-1";
$ado->Execute($sql);
$sql = "CREATE TABLE $EventTable SELECT Template,MessageType,EventId,LanguageId FROM ".GetTablePrefix()."EmailMessage WHERE EmailMessageId=-1";
$ado->Execute($sql);
$sql = "SELECT EventId,Event,Type FROM ".GetTablePrefix()."Events";
$rs = $ado->Execute($sql);
$Events = array();
while($rs && !$rs->EOF)
{
$Events[$rs->fields["Event"]."_".$rs->fields["Type"]] = $rs->fields["EventId"];
$rs->MoveNext();
}
if(count($_POST["lang"])>0)
{
$Langs = $_POST["lang"];
for($x=0;$x<count($Langs);$x++)
{
$lang = $Langs[$x];
$p = $pathtoroot.$admin."/install/langpacks/".$lang;
/* parse xml file */
$fp = fopen($p,"r");
$xml = fread($fp,filesize($p));
fclose($fp);
unset($objInXML);
$objInXML = new xml_doc($xml);
$objInXML->parse();
$objInXML->getTag(0,$name,$attribs,$contents,$tags);
if(is_array($tags))
{
foreach($tags as $t)
{
$LangRoot =& $objInXML->getTagByID($t);
$PackName = $LangRoot->attributes["PACKNAME"];
$l = $objLanguages->GetItemByField("PackName",$PackName);
if(is_object($l))
{
$LangId = $l->Get("LanguageId");
$NewLang = false;
}
else
{
$l = new clsLanguage();
$l->Set("Enabled",1);
$l->Create();
$NewLang = true;
$LangId = $l->Get("LanguageId");
}
foreach($LangRoot->children as $tag)
{
switch($tag->name)
{
case "PHRASES":
foreach($tag->children as $PhraseTag)
{
$Phrase = $ado->qstr($PhraseTag->attributes["LABEL"]);
$Translation = $ado->qstr(base64_decode($PhraseTag->contents));
$PhraseType = $PhraseTag->attributes["TYPE"];
$psql = "INSERT INTO $PhraseTable (Phrase,Translation,PhraseType,LanguageId) VALUES ($Phrase,$Translation,$PhraseType,$LangId)";
$ado->Execute($psql);
//echo "$psql <br>\n";
}
break;
case "DATEFORMAT":
$DateFormat = $tag->contents;
break;
case "TIMEFORMAT":
$TimeFormat = $tag->contents;
break;
case "DECIMAL":
$Decimal = $tag->contents;
break;
case "THOUSANDS":
$Thousands = $tag->contents;
break;
case "EVENTS":
foreach($tag->children as $EventTag)
{
$event = $EventTag->attributes["EVENT"];
$MsgType = strtolower($EventTag->attributes["MESSAGETYPE"]);
$template = base64_decode($EventTag->contents);
$Type = $EventTag->attributes["TYPE"];
$EventId = $Events[$event."_".$Type];
$esql = "INSERT INTO $EventTable (Template,MessageType,EventId,LanguageId) VALUES ('$template','$MsgType',$EventId,$LangId)";
$ado->Execute($esql);
//echo htmlentities($esql)."<br>\n";
}
break;
}
if($NewLang)
{
$l->Set("PackName",$PackName);
$l->Set("LocalName",$PackName);
$l->Set("DateFormat",$DateFormat);
$l->Set("TimeFormat",$TimeFormat);
$l->Set("DecimalPoint",$Decimal);
$l->Set("ThousandSep",$Thousands);
$l->Update();
}
}
}
}
}
$state="lang_install";
}
else {
$state="lang_select";
}
}
else {
$general_error = 'Database error! No language tables found!';
}
}
if($state=="lang_install")
{
/* do pack install */
$Offset = (int)$_GET["Offset"];
$Status = (int)$_GET["Status"];
$PhraseTable = GetTablePrefix()."ImportPhrases";
$EventTable = GetTablePrefix()."ImportEvents";
if($Status==0)
{
$Total = TableCount($PhraseTable,"",0);
}
else
{
$Total = TableCount($EventTable,"",0);
}
if($Status==0)
{
$Offset = $objLanguages->ReadImportTable($PhraseTable, 1,"0,1,2", $force_finish ? false : true, 200,$Offset);
if($Offset>=$Total)
{
$Offset=0;
$Status=1;
}
$next_step = GetVar('next_step', true);
if($force_finish == true) $next_step = 3;
$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&state=lang_install&next_step=$next_step&install_type=$install_type";
if($force_finish == true) $NextUrl .= '&ff=1';
$include_file = $pathtoroot.$admin."/install/lang_run.php";
}
else
{
if(!is_object($objMessageList))
$objMessageList = new clsEmailMessageList();
$Offset = $objMessageList->ReadImportTable($EventTable, $force_finish ? false : true,100,$Offset);
if($Offset>$Total)
{
$next_step = GetVar('next_step', true);
if($force_finish == true) $next_step = 3;
$NextUrl = $_SERVER['PHP_SELF']."?Offset=$Offset&Status=$Status&State=lang_install&next_step=$next_step&install_type=$install_type";
if($force_finish == true) $NextUrl .= '&ff=1';
$include_file = $pathtoroot.$admin."/install/lang_run.php";
}
else
{
if( !$force_finish )
{
$state = 'lang_default';
}
else
{
$_POST['next_step'] = 4;
$state = 'finish';
$include_file = $pathtoroot.$admin."/install/install_finish.php";
}
}
}
}
if($state=="lang_default_set")
{
// phpinfo(INFO_VARIABLES);
$ado =& inst_GetADODBConnection();
$PhraseTable = GetTablePrefix()."ImportPhrases";
$EventTable = GetTablePrefix()."ImportEvents";
$ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
$ado->Execute("DROP TABLE IF EXISTS $EventTable");
$Id = $_POST["lang"];
$objLanguages->SetPrimary($Id);
$state="postconfig_1";
}
if($state=="lang_default")
{
$Packs = Array();
$objLanguages->Clear();
$objLanguages->LoadAllLanguages();
foreach($objLanguages->Items as $l)
{
$Packs[$l->Get("LanguageId")] = $l->Get("PackName");
}
$include_file = $pathtoroot.$admin."/install/lang_default.php";
}
if($state=="modinstall")
{
$doms = $_POST["domain"];
if(is_array($doms))
{
$ado =& inst_GetADODBConnection();
require_once $pathtoroot.'kernel/include/tag-class.php';
if( !isset($objTagList) || !is_object($objTagList) ) $objTagList = new clsTagList();
foreach($doms as $p)
{
$filename = $pathtoroot.$p."/admin/install.php";
if(file_exists($filename))
{
include($filename);
}
}
}
/* $sql = "SELECT Name FROM ".GetTablePrefix()."Modules";
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$p = $rs->fields['Name'];
$mod_name = strtolower($p);
if ($mod_name == 'in-portal') {
$mod_name = '';
}
$dir_name = $pathtoroot.$mod_name."/admin/install/upgrades/";
$dir = @dir($dir_name);
$new_version = '';
$tmp1 = 0;
$tmp2 = 0;
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && !is_dir($dir_name.$file))
{
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
if ($file != '' && !strstr($file, 'changelog') && !strstr($file, 'readme')) {
$tmp1 = str_replace(".", "", $file);
if ($tmp1 > $tmp2) {
$new_version = $file;
}
}
}
$tmp2 = $tmp1;
}
$version_nrs = explode(".", $new_version);
for ($i = 0; $i < $version_nrs[0] + 1; $i++) {
for ($j = 0; $j < $version_nrs[1] + 1; $j++) {
for ($k = 0; $k < $version_nrs[2] + 1; $k++) {
$try_version = "$i.$j.$k";
$filename = $pathtoroot.$mod_name."/admin/install/upgrades/inportal_upgrade_v$try_version.sql";
if(file_exists($filename))
{
RunSQLFile($ado, $filename);
set_ini_value("Module Versions", $p, $try_version);
save_values();
}
}
}
}
$rs->MoveNext();
}
*/
$state="lang_select";
}
if($state=="lang_select")
{
$Packs = GetLanguageList();
$include_file = $pathtoroot.$admin."/install/lang_select.php";
}
if($state=="modselect")
{
/* /admin/install.php */
$UrlLen = (strlen($admin) + 12)*-1;
$pathguess =substr($_SERVER["SCRIPT_NAME"],0,$UrlLen);
$sitepath = $pathguess;
$esc_path = str_replace("\\","/",$pathtoroot);
$esc_path = str_replace("/","\\",$esc_path);
//set_ini_value("Site","DomainName",$_SERVER["HTTP_HOST"]);
//$g_DomainName= $_SERVER["HTTP_HOST"];
save_values();
$ado =& inst_GetADODBConnection();
if(substr($sitepath,0,1)!="/")
$sitepath="/".$sitepath;
if(substr($sitepath,-1)!="/")
$sitepath .= "/";
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$sitepath' WHERE VariableName='Site_Path'";
$ado->Execute($sql);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$g_Domain' WHERE VariableName='Server_Name'";
$ado->Execute($sql);
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '".$_SERVER['DOCUMENT_ROOT'].$sitepath."admin/backupdata' WHERE VariableName='Backup_Path'";
$ado->Execute($sql);
$Modules = inst_GetModuleList();
$include_file = $pathtoroot.$admin."/install/modselect.php";
}
if(substr($state,0,10)=="postconfig")
{
$p = explode("_",$state);
$step = $p[1];
if ($_POST['Site_Path'] != '') {
$sql = "SELECT Name, Version FROM ".$g_TablePrefix."Modules";
$rs = $ado->Execute($sql);
$modules_str = '';
while ($rs && !$rs->EOF) {
$modules_str .= $rs->fields['Name'].' ('.$rs->fields['Version'].'),';
$rs->MoveNext();
}
$modules_str = substr($modules_str, 0, strlen($modules_str) - 1);
$rfile = @fopen(GET_LICENSE_URL."?url=".base64_encode($_SERVER['HTTP_HOST'].$_POST['Site_Path'])."&modules=".base64_encode($modules_str)."&license_code=".base64_encode($g_LicenseCode)."&version=".GetMaxPortalVersion($pathtoroot.$admin)."&domain=".md5($_SERVER['HTTP_HOST']), "r");
if (!$rfile) {
//$get_license_error = "Unable to connect to the Intechnic server! Please try again later!";
//$state = "postconfig_1";
//$include_file = $pathtoroot.$admin."/install/postconfig.php";
}
else {
$rcontents = '';
while (!feof($rfile)) {
$line = fgets($rfile, 10000);
$rcontents .= $line;
}
@fclose($rfile);
}
}
if(strlen($_POST["oldstate"])>0)
{
$s = explode("_",$_POST["oldstate"]);
$oldstep = $s[1];
if($oldstep<count($configs))
{
$section = $configs[$oldstep];
$module = $mods[$oldstep];
$title = $titles[$oldstep];
$objAdmin = new clsConfigAdmin($module,$section,TRUE);
$objAdmin->SaveItems($_POST,TRUE);
}
}
$section = $configs[$step];
$module = $mods[$step];
$title = $titles[$step];
$step++;
if($step <= count($configs)+1)
{
$include_file = $pathtoroot.$admin."/install/postconfig.php";
}
else
$state = "theme_sel";
}
if($state=="theme_sel")
{
$objThemes->CreateMissingThemes();
$include_file = $pathtoroot.$admin."/install/theme_select.php";
}
if($state=="theme_set")
{
## get & define Non-Blocking & Blocking versions ##
$blocking_sockets = minimum_php_version("4.3.0")? 0 : 1;
$ado =& inst_GetADODBConnection();
$sql = "UPDATE ".$g_TablePrefix."ConfigurationValues SET VariableValue = '$blocking_sockets' WHERE VariableName='SocketBlockingMode'";
$ado->Execute($sql);
## get & define Non-Blocking & Blocking versions ##
$theme_id = $_POST["theme"];
$pathchar="/";
//$objThemes->SetPrimaryTheme($theme_id);
$t = $objThemes->GetItem($theme_id);
$t->Set("Enabled",1);
$t->Set("PrimaryTheme",1);
$t->Update();
$t->VerifyTemplates();
$include_file = $pathtoroot.$admin."/install/install_finish.php";
$state="finish";
}
if ($state == "adm_login") {
echo "<script>window.location='index.php';</script>";
}
// init variables
$vars = Array('db_error','restore_error','PassError','DomainError','login_error','inst_error');
foreach($vars as $var_name) ReSetVar($var_name);
switch($state)
{
case "modselect":
$title = "Select Modules";
$help = "<p>Select the In-Portal modules you wish to install. The modules listed to the right ";
$help .="are all modules included in this installation that are licensed to run on this server. </p>";
break;
case "reinstall":
$title = "Installation Maintenance";
$help = "<p>A Configuration file has been detected on your system and it appears In-Portal is correctly installed. ";
$help .="In order to work with the maintenance functions provided to the left you must provide the Intechnic ";
$help .="Username and Password you used when obtaining the license file residing on the server, or your admin Root password. ";
$help .=" <i>(Use Username 'root' if using your root password)</i></p>";
$help .= "<p>To removing your existing database and start with a fresh installation, select the first option ";
$help .= "provided. Note that this operation cannot be undone and no backups are made! Use at your own risk.</p>";
$help .="<p>If you wish to scrap your current installation and install to a new location, choose the second option. ";
$help .="If this option is selected you will be prompted for new database configuration information.</p>";
$help .="<p>The <i>Update License Information</i> option is used to update your In-Portal license data. Select this option if you have ";
$help .="modified your licensing status with Intechnic, or you have received new license data via email</p>";
break;
case "RootPass":
$title = "Set Admin Root Password";
$help = "<p>The Root Password is initially required to access the admin sections of In-Portal. ";
$help .="The root user cannot be used to access the front-end of the system, so it is recommended that you ";
$help .="create additional users with admin privlidges.</p>";
break;
case "finish":
$title = "Thank You!";
$help ="<P>Thanks for using In-Portal! Be sure to visit <A TARGET=\"_new\" HREF=\"http://www.in-portal.net\">www.in-portal.net</A> ";
$help.=" for the latest news, module releases and support. </p>";
break;
case "license":
$title = "License Configuration";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN. ";
$help.="If Intechnic has provided you with a license file, upload it here. Otherwise select the first ";
$help.="option to allow Install to download your license for you.</p>";
$help.="<p>If a valid license has been detected on your server, you can choose the <i>Use Existing License</i> ";
$help.="and continue the installation process</p>";
break;
case "domain_select":
$title="Select Licensed Domain";
$help ="<p>Select the domain you wish to configure In-Portal for. The <i>Other</i> option ";
$help.=" can be used to configure In-Portal for use on a local domain.</p>";
$help.="<p>For local domains, enter the hostname or LAN IP Address of the machine running In-Portal.</p>";
break;
case "db_reconfig":
case "dbinfo":
$title="Database Configuration";
$help = "<p>In-Portal needs to connect to your Database Server. Please provide the database server type*, ";
$help .="host name (<i>normally \"localhost\"</i>), Database user name, and database Password. ";
$help .="These fields are required to connect to the database.</p><p>If you would like In-Portal ";
$help .="to use a table prefix, enter it in the field provided. This prefix can be any ";
$help .=" text which can be used in the names of tables on your system. The characters entered in this field ";
$help .=" are placed <i>before</i> the names of the tables used by In-Portal. For example, if you enter \"inp_\"";
$help .=" into the prefix field, the table named Category will be named inp_Category.</p>";
break;
case "lang_select":
$title="Language Pack Installation";
$help = "<p>Select the language packs you wish to install. Each language pack contains all the phrases ";
$help .="used by the In-Portal administration and the default template set. Note that at least one ";
$help .="pack <b>must</b> be installed.</p>";
break;
case "lang_default":
$title="Select Default Language";
$help = "<p>Select which language should be considered the \"default\" language. This is the language ";
$help .="used by In-Portal when a language has not been selected by the user. This selection is applicable ";
$help .="to both the administration and front-end.</p>";
break;
case "lang_install":
$title="Installing Language Packs";
$help = "<p>The language packs you have selected are being installed. You may install more languages at a ";
$help.="later time from the Regional admin section.</p>";
break;
case "postconfig_1":
$help = "<P>These options define the general operation of In-Portal. Items listed here are ";
$help .="required for In-Portal's operation.</p><p>When you have finished, click <i>save</i> to continue.</p>";
break;
case "postconfig_2":
$help = "<P>User Management configuration options determine how In-Portal manages your user base.</p>";
$help .="<p>The groups listed to the right are pre-defined by the installation process and may be changed ";
$help .="through the Groups section of admin.</p>";
break;
case "postconfig_3":
$help = "<P>The options listed here are used to control the category list display functions of In-Portal. </p>";
break;
case "theme_sel":
$title="Select Default Theme";
$help = "<P>This theme will be used whenever a front-end session is started. ";
$help .="If you intend to upload a new theme and use that as default, you can do so through the ";
$help .="admin at a later date. A default theme is required for session management.</p>";
break;
case "get_license":
$title="Download License from Intechnic";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN.</p>";
$help.="<p>Here as you have selected download license from Intechnic you have to input your username and ";
$help.="password of your In-Business account in order to download all your available licenses.</p>";
break;
case "download_license":
$title="Download License from Intechnic";
$help ="<p>A License is required to run In-Portal on a server connected to the Internet. You ";
$help.="can run In-Portal on localhost, non-routable IP addresses, or other computers on your LAN.</p>";
$help.="<p>Please choose the license from the drop down for this site! </p> ";
break;
case "restore_select":
$title="Select Restore File";
$help = "<P>Select the restore file to use to reinstall In-Portal. If your backups are not performed ";
$help .= "in the default location, you can enter the location of the backup directory and click the ";
$help .="<i>Update</i> button.</p>";
case "restore_run":
$title= "Restore in Progress";
$help = "<P>Restoration of your system is in progress. When the restore has completed, the installation ";
$help .="will continue as normal. Hitting the <i>Cancel</i> button will restart the entire installation process. ";
break;
case "warning":
$title = "Restore in Progress";
$help = "<p>Please approve that you understand that you are restoring your In-Portal data base from other version of In-Portal.</p>";
break;
case "update":
$title = "Update In-Portal";
$help = "<p>Select modules from the list, you need to update to the last downloaded version of In-Portal</p>";
break;
}
$tmp_step = GetVar('next_step', true);
if (!$tmp_step) {
$tmp_step = 1;
}
if ( isset($got_license) && $got_license == 1) {
$tmp_step++;
}
$next_step = $tmp_step + 1;
if ($general_error != '') {
$state = '';
$title = '';
$help = '';
$general_error = $general_error.'<br /><br />Installation cannot continue!';
}
if ($include_file == '' && $general_error == '' && $state == '') {
$state = '';
$title = '';
$help = '';
$filename = $pathtoroot.$admin."/install/inportal_remove.sql";
RunSQLFile($ado,$filename);
$general_error = 'Unexpected installation error! <br /><br />Installation has been stopped!';
}
if ($restore_error != '') {
$next_step = 3;
$tmp_step = 2;
}
if ($PassError != '') {
$tmp_step = 4;
$next_step = 5;
}
if ($DomainError != '') {
$tmp_step--;
$next_step = $tmp_step + 1;
}
if ($db_error != '') {
$tmp_step--;
$next_step = $tmp_step + 1;
}
if ($state == "warning") {
$tmp_step--;
$next_step = $tmp_step + 1;
}
?>
<tr height="100%">
<td valign="top">
<table cellpadding=10 cellspacing=0 border=0 width="100%" height="100%">
<tr valign="top">
<td style="width: 200px; background: #009ff0 url(images/bg_install_menu.gif) no-repeat bottom right; border-right: 1px solid #000">
<img src="images/spacer.gif" width="180" height="1" border="0" alt=""><br>
<span class="admintitle-white">Installation</span>
<!--<ol class="install">
<li class="current">Licence Verification
<li>Configuration
<li>File Permissions
<li>Security
<li>Integrity Check
</ol>
</td>-->
<?php
$lic_opt = isset($_POST['lic_opt']) ? $_POST['lic_opt'] : false;
if ($general_error == '') {
?>
<?php if ($install_type == 1) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1) { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 2 || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4 ) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 2) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<!--<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish-->
</ol>
<?php } else if ($install_type == 3) { ?>
<ol class="install">
<li>License Verification
<li <?php if ($tmp_step == 2) { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 3 || $_POST['lic_opt'] == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 4 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 9) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 4) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Set Root Password
<li <?php if ($tmp_step == 5) { ?>class="current"<?php } ?>>Select Modules to Install
<li <?php if ($tmp_step == 6) { ?>class="current"<?php } ?>>Install Language Packs
<li <?php if ($tmp_step == 7) { ?>class="current"<?php } ?>>Post-Install Configuration
<li <?php if ($tmp_step == 8) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 5) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $lic_opt == 1) { ?>class="current"<?php } ?>>Select License
<li <?php if ($tmp_step == 3 && $lic_opt != 1) { ?>class="current"<?php } ?>>Select Domain
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 6) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if (($tmp_step == 2 && $login_error == '' && $inst_error == '') || $_GET['show_prev'] == 1 || $_POST['backupdir']) { ?>class="current"<?php } ?>>Select Backup File
<li <?php if ($tmp_step == 3 && $_POST['lic_opt'] != 1 && $_GET['show_prev'] != 1 && !$_POST['backupdir']) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 7) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Database Configuration
<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } else if ($install_type == 8) { ?>
<ol class="install">
<li <?php if ($tmp_step == 1 || $login_error != '' || $inst_error != '') { ?>class="current"<?php } ?>>License Verification
<li <?php if ($tmp_step == 2 && $login_error == '' && $inst_error == '') { ?>class="current"<?php } ?>>Select Modules to Upgrade
<li <?php if ($tmp_step == 3) { ?>class="current"<?php } ?>>Language Pack Upgrade
<li <?php if ($tmp_step == 4) { ?>class="current"<?php } ?>>Finish
</ol>
<?php } ?>
<?php include($include_file); ?>
<?php } else { ?>
<?php include("install/general_error.php"); ?>
<?php } ?>
<td width="40%" style="border-left: 1px solid #000; background: #f0f0f0">
<table width="100%" border="0" cellspacing="0" cellpadding="4">
<tr>
<td class="subsectiontitle" style="border-bottom: 1px solid #000000; background-color:#999"><?php if( isset($title) ) echo $title;?></td>
</tr>
<tr>
<td class="text"><?php if( isset($help) ) echo $help;?></td>
</tr>
</table>
</td>
</tr>
</table>
<br>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td id="footer">
Powered by In-portal &copy; 1997-2004, Intechnic Corporation. All rights reserved.
<br><img src="images/spacer.gif" width="1" height="10" alt="">
</td>
</tr>
</table>
</form>
</body>
</html>
\ No newline at end of file
Property changes on: trunk/admin/install.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.48
\ No newline at end of property
+1.49
\ No newline at end of property
Index: trunk/admin/install/install_lib.php
===================================================================
--- trunk/admin/install/install_lib.php (revision 414)
+++ trunk/admin/install/install_lib.php (revision 415)
@@ -1,710 +1,734 @@
<?php
function minimum_php_version( $vercheck )
{
$minver = explode(".", $vercheck);
$curver = explode(".", phpversion());
if (($curver[0] < $minver[0])
|| (($curver[0] == $minver[0])
&& ($curver[1] < $minver[1]))
|| (($curver[0] == $minver[0]) && ($curver[1] == $minver[1])
&& ($curver[2][0] < $minver[2][0])))
return false;
else
return true;
}
+function VersionSort($a, $b)
+{
+ if ($a == $b) {
+ return 0;
+ }
+ else {
+ $tmp_a = str_replace("inportal_upgrade_v", "", $a);
+ $tmp_a = str_replace(".sql", "", $a);
+
+ $tmp_b = str_replace("inportal_upgrade_v", "", $b);
+ $tmp_b = str_replace(".sql", "", $b);
+
+ return (ConvertVersion($a) < ConvertVersion($b)) ? -1 : 1;
+ }
+}
+
function GetMaxPortalVersion($admindirname)
{
$dir = @dir($admindirname.'/install/upgrades');
+ $upgrades_arr = Array();
+
$version = '';
while ($file = $dir->read()) {
- if ($file != "." && $file != ".." && !is_dir($admindirname.$file))
- {
+ if ($file != "." && $file != ".." && !is_dir($dir_name.$file)) {
if (strstr($file, 'inportal_upgrade_v')) {
- $file = str_replace("inportal_upgrade_v", "", $file);
- $file = str_replace(".sql", "", $file);
-
- if (ConvertVersion($file) > ConvertVersion($version)) {
- $version = $file;
- }
+ $upgrades_arr[] = $file;
}
- }
+ }
+ }
+
+ usort($upgrades_arr, "VersionSort");
+
+ foreach($upgrades_arr as $file) {
+ $file_tmp = str_replace("inportal_upgrade_v", "", $file);
+ $file_tmp = str_replace(".sql", "", $file_tmp);
+
+ if (ConvertVersion($file_tmp) > ConvertVersion($current_version)) {
+ $version = $file_tmp;
+ }
}
return $version;
}
function ConvertVersion($version)
{
$parts = explode('.', $version);
$bin = '';
foreach ($parts as $part) {
$bin .= str_pad(decbin($part), 8, '0', STR_PAD_LEFT);
}
$dec = bindec($bin);
return $dec;
}
function TableExists($ado, $tables)
{
global $g_TablePrefix;
$t = explode(",",$tables);
$i = $ado->MetaTables();
for($x=0;$x<count($i);$x++)
$i[$x] = strtolower($i[$x]);
$AllFound = TRUE;
for($tIndex=0;$tIndex<count($t);$tIndex++)
{
$table = $g_TablePrefix.$t[$tIndex];
$table = strtolower($table);
if(!in_array($table,$i))
{
$AllFound = FALSE;
}
}
return $AllFound;
}
function set_ini_value($section, $key, $newvalue)
{
global $ini_vars;
$ini_vars[$section][$key] = $newvalue;
}
function save_values()
{
// Should write something to somwere, but it doesn't :(
global $ini_file,$ini_vars;
//if( file_exists($ini_file) )
//{
$fp = fopen($ini_file, "w");
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($ini_vars as $secname => $section)
{
fwrite($fp,"[".$secname."]\n");
foreach($section as $key => $value) fwrite($fp,"$key = \"$value\"\n");
fwrite($fp,"\n");
}
fclose($fp);
//}
}
function RunSchemaFile($ado,$filename)
{
if(file_exists($filename))
{
$fp = fopen($filename, "r");//open file
$sql = fread($fp, filesize($filename));
fclose($fp);
if(strlen($sql))
RunSchemaText($ado,$sql);
}
}
function RunSchemaText($ado,$sql)
{
global $g_TablePrefix;
if(strlen($g_TablePrefix))
{
$what = "CREATE TABLE ";
$replace = "CREATE TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DROP TABLE ";
- $replace = "DROP TABLE ".$g_TablePrefix;
+ $replace = "DROP TABLE IF EXISTS ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "INSERT INTO ";
$replace = "INSERT INTO ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "UPDATE ";
$replace = "UPDATE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "ALTER TABLE ";
$replace = "ALTER TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
}
$commands = explode("# --------------------------------------------------------",$sql);
if(count($commands)>0)
{
for($i=0;$i<count($commands);$i++)
{
$cmd = $commands[$i];
$cmd = trim($cmd);
if(strlen($cmd)>0)
{
$ado->Execute($cmd);
if($ado->ErrorNo()!=0)
{
$db_error = $ado->ErrorMsg()." COMMAND:<PRE>$cmd</PRE>";
//echo "<br><p class=\"error\">$db_error</p>";
//break;
}
}
}
}
}
function RunSQLText($ado,$allsql)
{
global $g_TablePrefix;
$line = 0;
while($line<count($allsql))
{
$sql = $allsql[$line];
if(strlen(trim($sql))>0 && substr($sql,0,1)!="#")
{
if(strlen($g_TablePrefix))
{
$what = "CREATE TABLE ";
$replace = "CREATE TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DELETE FROM ";
$replace = "DELETE FROM ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DROP TABLE ";
$replace = "DROP TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "INSERT INTO ";
$replace = "INSERT INTO ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "UPDATE ";
$replace = "UPDATE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "ALTER TABLE ";
$replace = "ALTER TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
}
$sql = trim($sql);
if(strlen($sql)>0)
{
$ado->Execute($sql);
if($ado->ErrorNo()!=0)
{
$db_error = $ado->ErrorMsg()." COMMAND:<PRE>$sql</PRE>";
//echo "<br><p class=\"error\">$db_error</p>";
$error = TRUE;
}
}
}
$line++;
}
}
function RunSQLFile($ado,$filename)
{
if(file_exists($filename))
{
$allsql = file($filename);
RunSQLText($ado,$allsql);
}
}
function RunRestoreFile($ado,$filename,$FileOffset,$MaxLines)
{
$size = filesize($filename);
if($FileOffset > $size)
return -2;
$fp = fopen($filename,"r");
if(!$fp)
return -1;
if($FileOffset>0)
{
fseek($fp,$FileOffset);
}
else
{
$EndOfSQL = FALSE;
$sql = "";
while(!feof($fp) && !$EndOfSQL)
{
$l = fgets($fp,16384);
if(substr($l,0,11)=="INSERT INTO")
{
$EndOfSQL = TRUE;
}
else
{
$sql .= $l;
$FileOffset = ftell($fp) - strlen($l);
}
}
if(strlen($sql))
{
RunSchemaText($ado,$sql);
}
fseek($fp,$FileOffset);
}
$LinesRead = 0;
$sql = "";
$AllSql = array();
while($LinesRead < $MaxLines && !feof($fp))
{
$sql = fgets($fp, 16384);
if(strlen($sql))
{
$AllSql[] = $sql;
$LinesRead++;
}
}
if(!feof($fp))
{
$FileOffset = ftell($fp);
}
else
{
$FileOffset = $TotalSize;
}
fclose($fp);
if(count($AllSql)>0)
RunSQLText($ado,$AllSql);
return (int)$FileOffset;
-}
+}
+
function inst_keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function inst_decrypt($txt,$key)
{
$txt = inst_keyED($txt,$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
function inst_LoadFromRemote()
{
return "";
}
function mod_DLid()
{
global $DownloadId;
echo $DownloadId."\n";
die();
}
function inst_LoadLicense($LoadRemote=FALSE,$file="")
{
global $path,$admin;
$data = Array();
if(!strlen($file))
{
$f = $path.$admin."/include/inportal.dat";
}
else
$f = $file;
if(file_exists($f))
{
$contents = file($f);
$data[0] = base64_decode($contents[1]);
$data[1] = $contents[2];
}
else
if($LoadRemote)
return $LoadFromRemote;
return $data;
}
function inst_SaveLicense($data)
{
}
function inst_VerifyKey($domain,$k)
{
$key = md5($domain);
$lkey = substr($key,0,strlen($key)/2);
$rkey = substr($key,strlen($key)/2);
$r = $rkey.$lkey;
if($k==$r)
return TRUE;
return FALSE;
}
function inst_ParseLicense($txt)
{
global $i_User, $i_Pswd, $i_Keys;
$data = inst_decrypt($txt,"beagle");
$i_Keys = array();
$lines = explode("\n",$data);
for($x=0;$x<count($lines);$x++)
{
$l = $lines[$x];
$p = explode("=",$l,2);
switch($p[0])
{
case "Username":
$i_User = $p[1];
break;
case "UserPass":
$i_Pswd = $p[1];
break;
default:
if(substr($p[0],0,3)=="key")
{
$parts = explode("|",$p[1]);
if(inst_VerifyKey($parts[0],$parts[1]))
{
unset($K);
$k["domain"]=$parts[0];
$k["key"]=$parts[1];
$k["desc"]=$parts[2];
$k["mod"]=$parts[3];
$i_Keys[] = $k;
}
}
break;
}
}
}
function inst_IsLocalSite($domain)
{
$localb = FALSE;
if(substr($domain,0,3)=="172")
{
$b = substr($domain,0,6);
$p = explode(".",$domain);
$subnet = $p[1];
if($p[1]>15 && $p[1]<32)
$localb=TRUE;
}
$localname = (strpos($domain,".")==0);
if($domain=="localhost" || $domain=="127.0.0.1" || substr($domain,0,7)=="192.168" ||
substr($domain,0,3)=="10." || $localb || $localname)
{
return TRUE;
}
return FALSE;
}
function inst_ModuleLicensed($name)
{
global $i_Keys, $objConfig, $g_License, $g_Domain;
//$lic = LoadLicense();
$lic = base64_decode($g_License);
inst_ParseLicense($lic);
// echo "Checking $g_Domain..<br>\n";
// echo "<PRE>";print_r($i_Keys); echo "</PRE><br>";
$modules = array();
if(!inst_IsLocalSite($g_Domain))
{
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if($key["domain"]==$g_Domain)
{
$modules = explode(",",strtolower($key["mod"]));
}
}
if(in_array($name,$modules))
{
// echo "Module $name is licensed<br>\n";
return TRUE;
}
else
{
// echo "Module $name is not licensed<br>\n";
return FALSE;
}
}
else
return TRUE;
return FALSE;
}
function inst_parse_portal_ini($file, $parse_section = false) {
if(!file_exists($file) && !is_readable($file))
die('Could Not Open Ini File');
$contents = file($file);
$retval = array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if ($resave) {
$fp = fopen($file, "w");
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
function inst_GetModuleList()
{
global $rootpath,$pathchar,$admin, $pathtoroot;
$path = $pathtoroot;
$new = array();
if ($dir = @opendir($path))
{
while (($file = readdir($dir)) !== false)
{
if($file !="." && $file !=".." && substr($file,0,1)!="_")
{
if(is_dir($path."/".$file))
{
$inst_file = $path.$file."/admin/install.php";
if(file_exists($inst_file))
{
// if(inst_ModuleLicensed($file))
// {
$new[$file] = $inst_file;
// }
}
}
}
}
closedir($dir);
}
return array_keys($new);
}
function GetDirList ($dirName)
{
$filedates = array();
$d = dir($dirName);
while($entry = $d->read())
{
if ($entry != "." && $entry != "..")
{
if (!is_dir($dirName."/".$entry))
{
$filedate[]=$entry;
}
}
}
$d->close();
return $filedate;
}
function GetLanguageList()
{
global $pathtoroot, $admin;
$packs = array();
$dir = $pathtoroot.$admin."/install/langpacks";
$files = GetDirList($dir);
if(is_array($files))
{
foreach($files as $f)
{
$p = pathinfo($f);
if($p["extension"]=="lang")
{
$packs[] = $f;
}
}
}
return $packs;
}
function section_header($title, $return_result = false)
{
$ret = '<table border="0" cellpadding="2" cellspacing="0" class="tableborder_full" width="100%" height="30">'.
'<tr><td class="tablenav" width="580" nowrap background="images/tabnav_left.jpg"><span class="tablenav_link">&nbsp;'.$title.'</span>'.
'</td><td align="right" class="tablenav" background="images/tabnav_back.jpg" width="100%">'.
"<a class=\"link\" onclick=\"ShowHelp('in-portal:install');\"><img src=\"images/blue_bar_help.gif\" border=\"0\"></A>".
'</td></tr></table>';
if( $return_result )
return $ret;
else
echo $ret;
}
function &VerifyDB($error_state, $next_state, $success_func = null, $db_must_exist = false)
{
// perform various check type to database specified
// 1. user is allowed to connect to database
// 2. user has all types of permissions in database
global $state, $db_error;
// enshure we use data from post & not from config
$GLOBALS['g_DBType'] = $_POST["ServerType"];
$GLOBALS['g_DBHost'] = $_POST["ServerHost"];
$GLOBALS['g_DBName'] = $_POST["ServerDB"];
$GLOBALS['g_DBUser'] = $_POST["ServerUser"];
$GLOBALS['g_DBUserPassword'] = $_POST["ServerPass"];
// connect to database
$ado =& inst_GetADODBConnection();
if($ado->ErrorNo() != 0)
{
// was error while connecting
$db_error = "Connection Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
$state = $error_state;
}
elseif( $ado->ErrorNo() == 0 )
{
// if connected, then check if all sql statements work
$test_result = 1;
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
$sql_tests[] = 'CREATE TABLE test_table(test_col mediumint(6))';
$sql_tests[] = 'INSERT INTO test_table(test_col) VALUES (5)';
$sql_tests[] = 'UPDATE test_table SET test_col = 12';
$sql_tests[] = 'ALTER TABLE test_table ADD COLUMN new_col varchar(10)';
$sql_tests[] = 'SELECT * FROM test_table';
$sql_tests[] = 'DELETE FROM test_table';
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
foreach($sql_tests as $sql_test)
{
$ado->Execute($sql_test);
if( $ado->ErrorNo()!=0 )
{
$test_result = 0;
break;
}
}
if($test_result == 1)
{
// if statements work & connection made, then check table existance
$db_exists = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
if($db_exists != $db_must_exist)
{
$state = $error_state;
$db_error = $db_must_exist ? 'An In-Portal Database already exists at this location' : 'An In-Portal Database was not found at this location';
}
else
{
$state = $next_state;
if( isset($success_func) ) $success_func();
}
}
else
{
// user has insufficient permissions in database specified
$db_error = "Permission Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
$state = $error_state;
}
}
return $ado;
}
function SaveDBConfig()
{
// save new database configuration
set_ini_value("Database", "DBType",$_POST["ServerType"]);
set_ini_value("Database", "DBHost",$_POST["ServerHost"]);
set_ini_value("Database", "DBName",$_POST["ServerDB"]);
set_ini_value("Database", "DBUser",$_POST["ServerUser"]);
set_ini_value("Database", "DBUserPassword",$_POST["ServerPass"]);
set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);
save_values();
$GLOBALS['include_file'] = 'install/install_finish.php';
}
function ReSetVar($var)
{
// define varible if not defined before
if( !isset($GLOBALS[$var]) ) $GLOBALS[$var] = '';
}
// if globals.php not yet included (1st steps of install),
// then define GetVar function
if( !function_exists('GetVar') )
{
function GetVar($name, $post_priority = false)
{
if(!$post_priority) // follow gpc_order in php.ini
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
else // get variable from post 1stly if not found then from get
return isset($_POST[$name]) && $_POST[$name] ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
}
}
function RadioChecked($name, $value)
{
// return " checked" word in case if radio is checked
$submit_value = GetVar($name);
return $submit_value == $value ? ' checked' : '';
}
?>
Property changes on: trunk/admin/install/install_lib.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.15
\ No newline at end of property
+1.16
\ No newline at end of property
Index: trunk/admin/install/inportal_remove.sql
===================================================================
--- trunk/admin/install/inportal_remove.sql (revision 414)
+++ trunk/admin/install/inportal_remove.sql (revision 415)
@@ -1,104 +1,108 @@
DROP TABLE BanRules
# --------------------------------------------------------
DROP TABLE Category
# --------------------------------------------------------
DROP TABLE CategoryItems
# --------------------------------------------------------
DROP TABLE Censorship
# --------------------------------------------------------
DROP TABLE ConfigurationAdmin
# --------------------------------------------------------
DROP TABLE ConfigurationValues
# --------------------------------------------------------
DROP TABLE CountCache
# --------------------------------------------------------
DROP TABLE CustomField
# --------------------------------------------------------
DROP TABLE CustomMetaData
# --------------------------------------------------------
DROP TABLE EmailMessage
# --------------------------------------------------------
DROP TABLE EmailQueue
# --------------------------------------------------------
DROP TABLE EmailSubscribers
# --------------------------------------------------------
DROP TABLE Emoticon
# --------------------------------------------------------
DROP TABLE Events
# --------------------------------------------------------
DROP TABLE Favorites
# --------------------------------------------------------
DROP TABLE IdGenerator
# --------------------------------------------------------
DROP TABLE IgnoreKeywords
# --------------------------------------------------------
DROP TABLE Images
# --------------------------------------------------------
DROP TABLE ItemRating
# --------------------------------------------------------
DROP TABLE ItemReview
# --------------------------------------------------------
DROP TABLE ItemTypes
# --------------------------------------------------------
DROP TABLE Language
# --------------------------------------------------------
DROP TABLE Link
# --------------------------------------------------------
DROP TABLE Modules
# --------------------------------------------------------
DROP TABLE News
# --------------------------------------------------------
DROP TABLE PermCache
# --------------------------------------------------------
DROP TABLE PermissionConfig
# --------------------------------------------------------
DROP TABLE Permissions
# --------------------------------------------------------
DROP TABLE PersistantSessionData
# --------------------------------------------------------
DROP TABLE Phrase
# --------------------------------------------------------
DROP TABLE PhraseCache
# --------------------------------------------------------
DROP TABLE PortalGroup
# --------------------------------------------------------
DROP TABLE PortalUser
# --------------------------------------------------------
DROP TABLE Posting
# --------------------------------------------------------
DROP TABLE Relationship
# --------------------------------------------------------
DROP TABLE SearchConfig
# --------------------------------------------------------
DROP TABLE SearchLog
# --------------------------------------------------------
DROP TABLE SessionData
# --------------------------------------------------------
DROP TABLE SpamControl
# --------------------------------------------------------
DROP TABLE StatItem
# --------------------------------------------------------
DROP TABLE Theme
# --------------------------------------------------------
DROP TABLE ThemeFiles
# --------------------------------------------------------
DROP TABLE Topic
# --------------------------------------------------------
DROP TABLE UserGroup
# --------------------------------------------------------
DROP TABLE UserSession
# --------------------------------------------------------
DROP TABLE SuggestMail
# --------------------------------------------------------
DROP TABLE SysCache
# --------------------------------------------------------
DROP TABLE TagLibrary
# --------------------------------------------------------
DROP TABLE TagAttributes
# --------------------------------------------------------
DROP TABLE LinkValidation
# --------------------------------------------------------
DROP TABLE ImportScripts
# --------------------------------------------------------
+DROP TABLE ImportPhrases
+# --------------------------------------------------------
+DROP TABLE ImportEvents
+# --------------------------------------------------------
DROP TABLE EmailLog
#
\ No newline at end of file
Property changes on: trunk/admin/install/inportal_remove.sql
___________________________________________________________________
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 414)
+++ trunk/globals.php (revision 415)
@@ -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] !== 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
+ // ensure 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.25
\ No newline at end of property
+1.26
\ No newline at end of property

Event Timeline