Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 8:59 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 270)
+++ trunk/kernel/action.php (revision 271)
@@ -1,2222 +1,2222 @@
<?php
$ro_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & KERNEL_ACTIONS) == KERNEL_ACTIONS )
{
if($Action) echo "Kernel Action [<b>$Action</b>]<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>';
}
unset($script, $skip_debug);
}
switch($Action)
{
case "m_add_user":
$dupe_user = '';
$user_pending = (int)$_POST["user_pending"];
$user_enabled = (int)$_POST["user_enabled"];
$CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat());
$dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
$objEditItems = new clsUserManager();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
if(strlen($_POST["user_login"]))
$id = $objUsers->GetUserId($_POST["user_login"]);
else
$dob = 0;
if($id)
{
$lvErrorString = language('la_error_duplicate_username');
$dupe_user = $_POST["user_login"];
$_POST["user_login"] = '';
}
$password = md5($_POST["password"]);
$u = $objEditItems->Add_User($_POST["user_login"], $password,
$_POST["user_email"], $CreatedOn, $_POST["user_firstname"],
$_POST["user_lastname"], $_POST["status"],
$_POST["user_phone"],
$_POST["user_street"], $_POST["user_city"],
$_POST["user_state"], $_POST["user_zip"], $_POST["user_country"], $dob);
$objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
$objCustomEdit->SetTable('edit');
$objCustomEdit->LoadResource($u->Get("ResourceId"));
$CustomFields = new clsCustomFieldList(6);
$DataChanged = FALSE;
foreach($_POST as $key=>$value)
{
if(substr($key,0,1)=="_")
{
$field = substr($key,1);
$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
if(is_object($cvalue))
{
$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
$DataChanged = TRUE;
}
}
}
if($DataChanged) $objCustomEdit->SaveData();
$objCustomEdit->SetTable('live');
break;
case "m_edit_user":
$CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat());
$dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
$objEditItems = new clsUserManager();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
$user_pending = (int)$_POST["user_pending"];
$user_enabled = (int)$_POST["user_enabled"];
$UserId=(int)$_POST["user_id"];
//echo $UserId."<br>\n";
if(!strlen($_POST["user_login"]))
$dob = 0;
if(strlen($_POST["password"]))
{
$password = md5($_POST["password"]);
}
else
$password = "";
$u = $objEditItems->Edit_User($UserId, $_POST["user_login"], $password,
$_POST["user_email"], $CreatedOn, $_POST["user_firstname"],
$_POST["user_lastname"], $_POST["status"],
$_POST["user_phone"],
$_POST["user_street"], $_POST["user_city"],
$_POST["user_state"], $_POST["user_zip"], $_POST["user_country"],
$dob);
$objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
$objCustomEdit->SetTable('edit');
$DataChanged = false;
$objCustomEdit->LoadResource($u->Get("ResourceId"));
$CustomFields = new clsCustomFieldList(6);
foreach($_POST as $key=>$value)
{
if(substr($key,0,1)=="_")
{
$field = substr($key,1);
$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
if(is_object($cvalue))
{
//echo "Saving CF: (".$cvalue->Get("CustomFieldId")." ; ".$u->Get("ResourceId")." ; $value)<br>";
$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
$DataChanged = TRUE;
}
}
}
if($DataChanged)
$objCustomEdit->SaveData();
$objCustomEdit->SetTable('live');
break;
case "m_user_primarygroup":
//print_pre($_REQUEST);
if($ro_perm) break;
$users = explode(',', $_POST["userlist"]);
$GroupResourceId = $_POST['grouplist'];
$g = $objGroups->GetItemByField("ResourceId", $GroupResourceId);
$GroupId = $g->UniqueId();
if( is_array($users) )
foreach($users as $user_id)
{
$u = $objUsers->GetItemByField("ResourceId", $user_id);
$g->AddUser($u->Get("PortalUserId"), 1);
}
break;
case "m_edit_group":
$objEditItems = new clsGroupList();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
$objEditItems->Edit_Group($_POST["group_id"], $_POST["group_name"],$_POST["group_comments"]);
break;
case "m_add_group":
$objEditItems = new clsGroupList();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
$objEditItems->Add_Group($_POST["group_name"], $_POST["group_comments"],0);
break;
case "m_group_sysperm":
if($_POST["GroupEditStatus"]==0)
{
$objSession->ResetSysPermCache();
$GroupId = $_POST["GroupId"];
if($GroupId)
{
$objEditItems = new clsGroupList();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
$g = $objEditItems->GetItemByField("ResourceId",$GroupId);
if(is_object($g))
{
$PermList = explode(",",$_POST["PermList"]);
for($i=0;$i<count($PermList);$i++)
{
if(@in_array($PermList[$i],$_POST["inherit"]))
{
$value = -1;
}
else
{
$value = 0;
if(@in_array($PermList[$i],$_POST["permvalue"]))
$value = 1;
}
$g->SetSystemPermission($PermList[$i],$value);
}
}
}
}
break;
case "m_user_sysperm":
if($ro_perm) break;
if($_POST["UserEditStatus"]==0)
{
$UserId = $_POST["ItemId"];
if($UserId)
{
$objEditItems = new clsUserManager();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
$u = $objEditItems->GetItemByField("ResourceId",$UserId);
unset($g);
if(is_object($u))
{
$objSession->ResetSysPermCache();
$g = $u->GetPersonalGroup(FALSE);
$PermList = explode(",",$_POST["PermList"]);
for($i=0;$i<count($PermList);$i++)
{
if(!@in_array($PermList[$i],$_POST["inherit"]))
{
if(!is_object($g))
$g = $u->GetPersonalGroup(TRUE);
$value = 0;
if(is_array($_POST["permvalue"]))
{
if(in_array($PermList[$i],$_POST["permvalue"]))
$value =1;
$g->SetSystemPermission($PermList[$i],$value);
}
else
$g->SetSystemPermission($PermList[$i],-1);
}
else
{
if(is_object($g))
$g->SetSystemPermission($PermList[$i],-1);
}
}
}
}
}
break;
case "m_approve_user":
if($ro_perm) break;
foreach($_POST["itemlist"] as $userid)
{
$user = $objUsers->GetItemByField("ResourceId",$userid);
$user->Approve();
}
$objUsers->Clear();
break;
case "m_deny_user":
if($ro_perm) break;
foreach($_POST["itemlist"] as $userid)
{
$user = $objUsers->GetItemByField("ResourceId",$userid);
$user->Deny();
}
$objUsers->Clear();
break;
case "m_delete_user":
if($ro_perm) break;
foreach($_POST["itemlist"] as $userid)
$objUsers->Delete_User($userid);
break;
case "m_delete_group":
if($ro_perm) break;
foreach($_POST["itemlist"] as $groupid)
{
$objGroups->Delete_Group($groupid);
}
break;
case "m_user_assign":
$useridlist = implode("-", $userlist);
$objSession->SetUserStatus($useridlist, "g_usergroup_status");
$g_usergroup_status = $useridlist;
break;
case "m_group_assign":
foreach($grouplist as $group)
$objGroups->Add_Users_To_Group($group);
break;
case "m_remove_group":
$adodbConnection = GetAdodbConnection();
$adodbConnection->Execute("DELETE FROM UserGroup where UserId='$UserId' AND GroupId='$GroupId'");
break;
case "m_SetVariable":
$objSession->SetPersistantVariable($_POST["fieldname"], $_POST["varvalue"]);
break;
case "m_SetSessionVariable":
$objSession->SetVariable($_POST["fieldname"], $_POST["varvalue"]);
//echo "Setting $fieldname to $varvalue<br>\n";
if($_POST["fieldname"]=="SearchType")
$objSession->SetVariable("SearchWord","");
break;
case "m_edit_permissions":
if($ro_perm) break;
if($_POST["CatEditStatus"] != -1)
{
$objSession->SetVariable('PermCache_UpdateRequired', 1);
$GroupId = $_POST["GroupId"];
$CatId = $_POST["CategoryId"];
$Module = $_POST["Module"];
$ado = GetADODBConnection();
$sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE ModuleId='$Module'";
$rs = $ado->Execute($sql);
$PermNames = array();
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$PermNames[] = $data["PermissionName"];
$rs->MoveNext();
}
$inherit = array();
if(is_array($_POST["inherit"]))
{
foreach($_POST["inherit"] as $perm)
{
$inherit[$perm] = 1;
}
}
$access = array();
if(is_array($_POST["permvalue"]))
{
foreach($_POST["permvalue"] as $perm)
{
$access[$perm] = 1;
}
}
$objPermList = new clsPermList($CatId,$GroupId);
$objPermList->LoadCategory($CatId);
for($i=0;$i<count($PermNames);$i++)
{
if(!array_key_exists($PermNames[$i],$inherit))
{
$PermValue = (int)$access[$PermNames[$i]];
$Perm = $objPermList->GetPermByName($PermNames[$i]);
if($Perm)
{
$Id = $Perm->Get("PermissionId");
//echo "Editing $Id<br>\n";
$objPermList->Edit_Permission($Id,$CatId,$GroupId,$PermNames[$i],$PermValue,0);
}
else
{
//echo "Adding ".$PermNames[$i];
$objPermList->Add_Permission($CatId,$GroupId,$PermNames[$i],$PermValue,0);
}
}
else
{
$Perm = $objPermList->GetPermByName($PermNames[$i]);
if($Perm)
{
$Id = $Perm->Get("PermissionId");
$objPermList->Delete_Permission($Id);
}
}
}
//$c = $objCatList->GetItem($CatId);
//$glist = $objGroups->GetAllGroupList();
//$ViewList = $objPermList->GetGroupPermList($c,"CATEGORY.VIEW",$glist );
//$c->SetViewPerms("CATEGORY.VIEW",$ViewList,$glist);
//$c->Update();
}
break;
case "m_perm_delete_group":
$ado = GetADODBConnection();
$CatId = $_POST["CategoryId"];
foreach($_POST["itemlist"] as $groupid)
{
$g = $objGroups->GetItemByField("ResourceId",$groupid);
if(is_object($g))
{
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=$CatId AND GroupId=".$g->Get("GroupId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$ado->Execute($sql);
}
}
break;
case "m_user_addto_group":
if($ro_perm) break;
$user = $_POST["UserId"];
if(is_numeric($user))
{
if(strlen($_POST["grouplist"]))
{
$groups = explode(",",$_POST["grouplist"]);
if(is_array($groups))
{
for($i=0; $i<count($groups);$i++)
{
$g = $objGroups->GetItemByField("ResourceId",$groups[$i]);
$g->AddUser($user);
}
}
else
{
$g = $objGroups->GetItem($groups);
$g->AddUser($user);
}
}
}
break;
case "m_group_add_user":
if($ro_perm) break;
$group = $_POST["GroupId"];
$EditGroups = new clsGroupList();
$EditGroups->SourceTable = $objSession->GetEditTable($objGroups->SourceTable);
$g = $EditGroups->GetItem($group);
// echo "Group: $group <br>\n";
if(is_numeric($group))
{
$users = explode(",",$_POST["userlist"]);
foreach($users as $userid)
{
$u = $objUsers->GetItemByField("ResourceId",$userid);
$g->AddUser($u->Get("PortalUserId"));
}
}
break;
case "m_group_removeuser":
if($ro_perm) break;
$group = $_POST["GroupId"];
$g = $objGroups->GetItem($group);
if($group>0)
{
foreach($_POST["itemlist"] as $user_id)
{
$u = $objUsers->GetItemByField("ResourceId",$user_id);
$g->DeleteUser($u->Get("PortalUserId"));
}
}
break;
case "m_user_removegroup":
if($ro_perm) break;
$user = $_POST["UserId"];
if($user>0)
{
foreach($_POST["itemlist"] as $groupid)
{
$g = $objGroups->GetItem($groupid);
$g->DeleteUser($user);
}
}
break;
case "m_sendmail":
$idlist = explode(",",$_POST["idlist"]);
$html = (int)$_POST["html_enable"];
$body = inp_escape($_POST["email_body"],$html);
$subject = inp_escape($_POST["email_body"],$html);
$Email = new clsEmailMessage();
$Email->Set("Subject",$subject);
$Email->Set("Template",$body);
if($html)
$Email->Set("MessageType","HTML");
if(count($idlist)>0)
{
switch($_POST["IdType"])
{
case "group":
foreach($idlist as $id)
$Email->SendToGroup($id);
break;
case "user":
foreach($idlist as $id)
$Email->SendToUser($id);
break;
}/*switch*/
}
break;
case "m_item_recount":
RunDown($m_var_list["cat"],"UpdateCacheCounts");
break;
case "m_cat_delete":
if($objSession->HasCatPermission("CATEGORY.DELETE",$objCatList->CurrentCategoryID()))
{
if(isset($_POST["catlist"]))
{
if(is_array($_POST["catlist"]))
foreach($_POST["catlist"] as $catid)
{
$objCatList->Delete_Category($catid);
}
}
}
break;
case "m_cat_cut":
if(isset($_POST["catlist"]))
{
if($objSession->HasCatPermission("CATEGORY.DELETE",$catid))
{
$objCatList->CopyToClipboard("CUT","CategoryId",$_POST["catlist"]);
}
else
$objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
}
break;
case "m_cat_copy":
if(isset($_POST["catlist"]))
{
$objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
}
break;
case "m_paste":
if($objCatList->ItemsOnClipboard()>0)
{
/* category's paste function populates a sparse array where array[old_id]=new_id */
$PastedCatIds = array();
$objCatList->PasteFromClipboard($objCatList->CurrentCategoryID(),"Name");
}
else
{
$clip = $objSession->GetVariable("ClipBoard");
if(strlen($clip))
{
$ClipBoard = ParseClipboard($clip);
$Action= strtolower($ClipBoard["table"])."_paste";
}
}
break;
case "m_cat_move_up":
if (isset($_POST["catlist"]))
{
foreach($_POST["catlist"] as $catid)
{
$cat =& $objCatList->GetCategory($catid);
$cat->MoveUp();
}
}
break;
case "m_cat_move_down":
if (isset($_POST["catlist"]))
{
$catlist=array_reverse($_POST["catlist"]);
foreach($catlist as $catid)
{
$cat =& $objCatList->GetCategory($catid);
$cat->MoveDown();
}
}
break;
case "m_cat_approve":
if (isset($_POST["catlist"]))
{
foreach($_POST["catlist"] as $catid)
{
$cat =& $objCatList->GetCategory($catid);
$cat->Approve();
}
}
break;
case "m_cat_decline":
if (isset($_POST["catlist"]))
{
foreach($_POST["catlist"] as $catid)
{
$cat =& $objCatList->GetCategory($catid);
// $cat->Deny();
RunDown($catid,"Deny");
}
}
break;
case "m_rel_delete":
$adodbConnection= GetADODBConnection();
$table = $objSession->GetEditTable("Relationship");
if(isset($_POST["itemlist"]))
{
if(is_array($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$sql = "DELETE FROM ".$table." WHERE RelationshipId=".$id;
$adodbConnection->Execute($sql);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
}
}
else
{
$sql = "DELETE FROM ".$table." WHERE RelationshipId=".$_POST["itemlist"];
$adodbConnection->Execute($sql);
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
}
}
break;
case "m_add_relation":
if($_POST["CatEditStatus"]==0)
{
$RelList = new clsRelationshipList();
$RelList->SourceTable = $objSession->GetEditTable("Relationship");
//$r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
// 0,(int)$_POST["Enabled"],$_POST["RelType"], $Rel);
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT MIN(RelationshipId) as MinValue FROM ".$RelList->SourceTable);
$NewId = $rs->fields["MinValue"]-1;
$r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
0,(int)$_POST["Enabled"],$_POST["RelType"], $NewId);
$sql = "UPDATE ".$RelList->SourceTable." SET RelationshipId=".$NewId." WHERE RelationshipId=".$r->Get("RelationshipId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$ado->Execute($sql);
}
break;
case "m_edit_relation":
if($_POST["CatEditStatus"]==0)
{
$RelList = new clsRelationshipList();
$RelList->SourceTable = $objSession->GetEditTable("Relationship");
$r = $RelList->GetItem($_POST["RelationshipId"]);
if(is_object($r))
{
$r->Set("Enabled",(int)$_POST["Enabled"]);
$r->Set("Type",(int)$_POST["RelType"]);
$r->Set("Priority",(int)$_POST["priority"]);
$r->Update();
}
}
break;
case "m_rel_move_up":
$objRelList = new clsRelationshipList();
$objRelList->SourceTable = $objSession->GetEditTable("Relationship");
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$r = $objRelList->GetItem($id);
$r->MoveUp($_POST["SourceId"]);
}
}
break;
case "m_rel_move_down":
$objRelList = new clsRelationshipList();
$objRelList->SourceTable = $objSession->GetEditTable("Relationship");
if (isset($_POST["itemlist"]))
{
$itemlist=array_reverse($_POST["itemlist"]);
foreach($itemlist as $id)
{
$r = $objRelList->GetItem($id);
$r->MoveDown($_POST["SourceId"]);
}
}
break;
case "m_add_category":
if(ValidDate($_POST["cat_date"],GetDateFormat()))
{
$CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
}
else
$CreatedOn = time();
$html = (int)$_POST["html_enable"];
$cat_pick = $_POST["cat_pick"];
$Status = (int)$_POST["status"];
$Hot=(int)$_POST["itemhot"];
$Pop = (int)$_POST["itempop"];
$New = (int)$_POST["itemnew"];
$objEditItems = new clsCatList();
$objEditItems->SourceTable = $objSession->GetEditTable("Category");
$cat = $objEditItems->Add($_POST["ParentId"], $_POST["cat_name"], inp_escape($_POST["cat_desc"],$html), $CreatedOn,
$cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"],
$_POST["meta_keywords"],$_POST["meta_desc"]);
$objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
$objCustomEdit->LoadResource($cat->Get("ResourceId"));
$CustomFields = new clsCustomFieldList(1);
$DataChanged = FALSE;
foreach($_POST as $key=>$value)
{
if(substr($key,0,1)=="_")
{
$field = substr($key,1);
$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
if(is_object($cvalue))
{
$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
$DataChanged = TRUE;
}
}
}
if($DataChanged)
$objCustomEdit->SaveData();
break;
case "m_edit_category":
$CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
$cat_pick = $_POST["cat_pick"];
$Status = (int)$_POST["status"];
$Hot=(int)$_POST["itemhot"];
$Pop = (int)$_POST["itempop"];
$New = (int)$_POST["itemnew"];
$html = (int)$_POST["html_enable"];
$objEditItems = new clsCatList();
$objEditItems->SourceTable = $objSession->GetEditTable("Category");
// check if name of cat isn't changed: begin
$original_cats = new clsCatList();
$original_cat = $original_cats->GetItemByField('CategoryId', $_POST['CategoryId']);
if( $original_cat->Get('Name') != $_POST['cat_name'] )
$objSession->SetVariable('PermCache_UpdateRequired', 1);
unset($original_cat, $original_cats);
// check if name of cat isn't changed: end
$cat = $objEditItems->Edit_Category($_POST["CategoryId"],inp_escape($_POST["cat_name"],$html), inp_escape($_POST["cat_desc"],$html), $CreatedOn, $cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"], $_POST["meta_keywords"], $_POST["meta_desc"]);
$objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
$objCustomEdit->LoadResource($cat->Get("ResourceId"));
$CustomFields = new clsCustomFieldList(1);
$DataChanged = FALSE;
foreach($_POST as $key=>$value)
{
if(substr($key,0,1)=="_")
{
$field = substr($key,1);
$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
if(is_object($cvalue))
{
$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
$DataChanged = TRUE;
}
}
}
if($DataChanged)
$objCustomEdit->SaveData();
break;
case "m_edit_custom_data":
$id = $_POST["ItemId"];
$objEditData = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
$objEditData->SetTable('edit');
$ado = GetADODBConnection();
if($id && is_array($_POST["CustomData"]))
{
foreach($_POST["CustomData"] as $FieldId => $Value)
{
$sql = "SELECT count(*) as reccount FROM ".$objEditData->SourceTable." WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
$rs = $ado->Execute($sql);
$intable = $rs->fields["reccount"];
if(!$intable)
{
$sql = "INSERT INTO ".$objEditData->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$id."','$FieldId','$Value')";
$ado->Execute($sql);
//echo $sql."<br>\n";
}
else
{
$sql = "UPDATE ".$objEditData->SourceTable." SET Value='".$Value."' WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
$ado->Execute($sql);
//echo $sql."<br>\n";
}
}
}
$objEditData->SetTable('live');
break;
case "m_customfield_edit":
if($ro_perm) break;
$DataType = $_POST["DataType"];
$FieldId = $_POST["CustomFieldId"];
$FieldName = $_POST["fieldname"];
//$FieldLabel = $_POST["fieldlabel"];
if(strlen($FieldName))
{
$objCustomFields = new clsCustomFieldList($DataType);
$objCustomFields->EditField($FieldId,$DataType,$FieldName,"",(int)$_POST["generaltab"],
$_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
$_POST["valuelist"]);
}
unset($objCustomFields);
break;
case "m_customfield_add":
if($ro_perm) break;
$DataType = $_POST["DataType"];
$FieldName = $_POST["fieldname"];
//$FieldLabel = $_POST["fieldlabel"];
if(strlen($FieldName))
{
$objCustomFields = new clsCustomFieldList($DataType);
$objCustomFields->AddField($DataType,$FieldName,"",(int)$_POST["generaltab"],
$_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
$_POST["valuelist"]);
unset($objCustomFields);
}
break;
case "m_customfield_delete":
if($ro_perm) break;
$DataType = $_POST["DataType"];
$objCustomFields = new clsCustomFieldList($DataType);
foreach($_POST["itemlist"] as $f)
{
$objCustomFields->DeleteField($f);
//$c = $objCustomFields->GetItem($f);
//$c->Delete();
}
unset($objCustomFields);
break;
case "m_SearchConfig_Edit":
if($ro_perm) break;
$SimpleValues = $_POST["simple"];
$AdvValues = $_POST["advanced"];
$module = $_POST["module"];
$priority = $_POST["pri"];
//phpinfo(INFO_VARIABLES);
$objSearchConfig = new clsSearchConfigList($module);
foreach($objSearchConfig->Items as $i)
{
$id = $i->Get("SearchConfigId");
$objSearchConfig->EditFieldSettings($id,(int)$SimpleValues[$id],(int)$AdvValues[$id],$priority[$id]);
}
$objSearchConfig->Clear();
/* save relevence settings */
$vals = $_POST["req_increase"];
foreach($vals as $var=>$value)
{
$cfg = "SearchRel_Increase_".$var;
$objConfig->Set($cfg,$value);
}
$vals = $_POST["rel_keyword"];
foreach($vals as $var=>$value)
{
$cfg = "SearchRel_Keyword_".$var;
$objConfig->Set($cfg,$value);
}
$vals = $_POST["rel_pop"];
foreach($vals as $var=>$value)
{
$cfg = "SearchRel_Pop_".$var;
$objConfig->Set($cfg,$value);
}
$vals = $_POST["rel_rating"];
foreach($vals as $var=>$value)
{
$cfg = "SearchRel_Rating_".$var;
$objConfig->Set($cfg,$value);
}
break;
case "m_keyword_reset":
if($ro_perm) break;
$objSearchList = new clsSearchLogList();
foreach($_POST["itemlist"] as $k)
{
$c = $objSearchList->GetItem($k);
$c->Delete();
}
break;
case "m_review_add":
$post_info = GetSubmitVariable($_POST, 'EditStatus');
if($post_info['variable'] > -1)
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
$Pending = (int)$_POST["review_pending"];
$Enabled = (int)$_POST["review_enabled"];
$Status = (int)$_POST["status"];
$CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat());
$CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
$html = (int)$_POST["html_enable"];
$ReviewText = inp_escape($_POST["review_body"],1);
$CreatedById = 0;
if(strlen($_POST["createdby"])>0)
{
if(strtolower($_POST["createdby"])=="root")
{
$CreatedById = -1;
}
else
{
$u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
if(is_object($u))
{
$CreatedById = $u->Get("PortalUserId");
if($CreatedById<1)
{
$CreatedById = $objSession->Get("PortalUserId");
}
}
else
$CreatedById = $objSession->Get("PortalUserId");
}
}
else
$CreatedById = $objSession->Get("PortalUserId");
$r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress,
(int)$_POST["review_priority"], $_POST["ItemId"],$_POST["ItemType"],
$CreatedById,$html, $post_info['Module']);
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT MIN(ReviewId) as MinValue FROM ".$objReviews->SourceTable);
$NewId = $rs->fields["MinValue"]-1;
$sql = "UPDATE ".$objReviews->SourceTable." SET ReviewId=".$NewId." WHERE ReviewId=".$r->Get("ReviewId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$ado->Execute($sql);
}
break;
case "m_review_edit":
$post_info = GetSubmitVariable($_POST, 'EditStatus');
if($post_info['variable'] > -1)
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
$Status = (int)$_POST["status"];
$CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat());
$CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
$html = (int)$_POST["html_enable"];
$ReviewText = inp_escape($_POST["review_body"],1);
$ReviewId = $_POST["ReviewId"];
$CreatedById = 0;
if(strlen($_POST["createdby"])>0)
{
if(strtolower($_POST["createdby"])=="root")
{
$CreatedById = -1;
}
else
{
$u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
if(is_object($u))
{
$CreatedById = $u->Get("PortalUserId");
if($CreatedById<1)
{
$CreatedById = $objSession->Get("PortalUserId");
}
}
else
$CreatedById = $objSession->Get("PortalUserId");
}
}
$r = $objReviews->EditReview($ReviewId,$CreatedOn,$ReviewText,$Status, $IPAddress,
(int)$_POST["review_priority"],$_POST["ItemId"],$_POST["ItemType"],
$CreatedById,$html, $post_info['Module']);
}
break;
case "m_review_delete":
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
foreach($_POST["itemlist"] as $id)
{
$objReviews->DeleteReview($id);
}
break;
case "m_review_approve":
if (isset($_POST["itemlist"]))
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
foreach($_POST["itemlist"] as $id)
{
$i = $objReviews->GetItem($id);
$i->Set("Status",1);
$i->Update();
}
}
break;
case "m_review_deny":
if (isset($_POST["itemlist"]))
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
foreach($_POST["itemlist"] as $id)
{
$i = $objReviews->GetItem($id);
$i->Set("Status",0);
$i->Update();
}
}
break;
case "m_review_move_up":
if (isset($_POST["itemlist"]))
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
foreach($_POST["itemlist"] as $id)
{
$i = $objReviews->GetItem($id);
$i->MoveUp();
}
}
break;
case "m_review_move_down":
if (isset($_POST["itemlist"]))
{
$objReviews = new clsItemReviewList();
$objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
$itemlist=array_reverse($_POST["itemlist"]);
foreach($itemlist as $id)
{
$i = $objReviews->GetItem($id);
$i->MoveDown();
}
}
break;
case "m_theme_add":
$objEditItems = new clsThemeList();
$objEditItems->SourceTable = $objSession->GetEditTable("Theme");
$Primary = (int)$_POST["primary"];
if(!(int)$_POST["enabled"])
$Primary = 0;
$t = $objEditItems->AddTheme($_POST["name"],$_POST["description"],(int)$_POST["enabled"],
(int)$_POST["CacheTimeout"],$Primary);
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT MIN(ThemeId) as MinValue FROM ".$objEditItems->SourceTable);
$NewId = $rs->fields["MinValue"]-1;
$sql = "UPDATE ".$objEditItems->SourceTable." SET ThemeId=".$NewId." WHERE ThemeId=".$t->Get("ThemeId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
if ($Primary==1)
{
$objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
}
$ado->Execute($sql);
break;
case "m_theme_edit":
$objEditItems = new clsThemeList();
$objEditItems->SourceTable = $objSession->GetEditTable("Theme");
$Primary = (int)$_POST["primary"];
if(!(int)$_POST["enabled"])
$Primary = 0;
$objEditItems->EditTheme($_POST["ThemeId"],$_POST["name"],$_POST["description"],
(int)$_POST["enabled"],$Primary,(int)$_POST["CacheTimeout"]);
if ($Primary==1)
{
$objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
}
break;
case "m_theme_delete":
if (isset($_POST["itemlist"]))
{
$Themes = new clsThemeList();
foreach($_POST["itemlist"] as $id)
{
$Themes->DeleteTheme($id);
}
}
break;
case "m_theme_primary":
if( count($_POST['itemlist']) )
{
$ThemeId = array_shift( $_POST['itemlist'] );
$t = new clsThemeList();
$t->SetPrimaryTheme($ThemeId);
}
break;
case "m_template_edit":
$ThemeId = $_POST["ThemeId"];
$FileId = $_POST["FileId"];
$f = new clsThemeFile($FileId);
$f->Set("Description", $_POST["Description"] );
$f->Update();
$c = stripslashes($_POST["contents"]);
$f->SaveFileContents($c);
break;
case "m_template_add":
$ThemeId = $_POST["ThemeId"];
if( !is_object($f) ) $f = new clsThemeFile();
$FilePath = $_POST['name'];
if(!$FilePath)
{
$f->SetError('Template Name is required',3);
break;
}
else
{
if( substr($FilePath,1) != '/' ) $FilePath = '/'.$FilePath;
if( substr($FilePath,-3) != '.tpl' ) $FilePath .= '.tpl';
$FileName = basename($FilePath);
$FilePath = dirname($FilePath);
// test if such file not already created
$f->LoadFromDataBase( Array($FilePath,$FileName), Array('FilePath','FileName') );
if( !$f->Get('FileId') )
{
$f->Set( Array('FilePath','FileName','ThemeId', 'Description'),
Array($FilePath, $FileName,$_POST['ThemeId'], $_POST["Description"])
);
if( $f->IsWriteablePath(true) )
{
$f->Create();
$c = stripslashes($_POST["contents"]);
$f->SaveFileContents($c, true);
}
}
else
$f->SetError('Template with this name already exists',4);
}
break;
case "m_template_delete":
$dummy = new clsThemeFile();
foreach($_POST["itemlist"] as $FileId)
{
$dummy->LoadFromDatabase($FileId);
$dummy->Delete();
}
break;
case "m_lang_add":
$objEditItems = new clsLanguageList();
$objEditItems->SourceTable = $objSession->GetEditTable("Language");
$l = $objEditItems->AddLanguage($_POST["packname"],$_POST["localname"],
(int)$_POST["enabled"],(int)$_POST["primary"],
$_POST["icon"],$_POST["date_format"],$_POST["time_format"],
$_POST["decimal"],$_POST["thousand"]);
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT MIN(LanguageId) as MinValue FROM ".$objEditItems->SourceTable);
$NewId = $rs->fields["MinValue"]-1;
$sql = "UPDATE ".$objEditItems->SourceTable." SET LanguageId=".$NewId." WHERE LanguageId=".$l->Get("LanguageId");
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$ado->Execute($sql);
if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
{
$sql = "SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"];
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$rs = $ado->Execute($sql);
$plist = new clsPhraseList();
$plist->SourceTable = $objSession->GetEditTable("Phrase");
$sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
$as = $ado->Execute($sql);
if($as && !$as->EOF)
{
$MinId = (int)$as->fields["MinId"];
}
else
$MinId = 0;
$MinId--;
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$plist->AddPhrase($data["Phrase"],$NewId,$data["Translation"],$data["PhraseType"]);
$sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
$ado->Execute($sql);
$MinId--;
$rs->MoveNext();
}
}
break;
case "m_lang_export":
include_once($pathtoroot."kernel/include/xml.php");
$Ids = $_POST["LangList"]; // language ids list to export phrases from
$phrase_types = GetVar('langtypes');
$phrase_types = ($phrase_types !== false) ? implode(',',$phrase_types) : null;
$filename=$_POST["filename"];
if(strlen($filename)>0)
{
$ExportFilename = $pathtoroot.$admin."/export/".$filename;
$ExportResult = $objLanguages->ExportPhrases($ExportFilename,$Ids, $phrase_types);
}
break;
case "m_lang_edit":
$objEditItems = new clsLanguageList();
$objEditItems->SourceTable = $objSession->GetEditTable("Language");
$objEditItems->EditLanguage($_POST["LanguageId"],$_POST["packname"],
$_POST["localname"],(int)$_POST["enabled"],
(int)$_POST["primary"], $_POST["icon"],$_POST["date_format"],
$_POST["time_format"], $_POST["decimal"],$_POST["thousand"]);
if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
{
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"]);
$plist = new clsPhraseList();
$plist->SourceTable = $objSession->GetEditTable("Phrase");
$sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
$as = $ado->Execute($sql);
if($as && !$as->EOF)
{
$MinId = (int)$as->fields["MinId"];
}
else
$MinId = 0;
$MinId--;
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$plist->AddPhrase($data["Phrase"],$_POST["LanguageId"],$data["Translation"],$data["PhraseType"]);
$sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
$ado->Execute($sql);
$MinId--;
$rs->MoveNext();
}
unset($plist);
}
break;
case "m_lang_delete":
if($ro_perm) break;
if (isset($_POST["itemlist"]))
{
$Phrases = new clsPhraseList();
foreach($_POST["itemlist"] as $id)
{
$objLanguages->DeleteLanguage($id);
$Phrases->DeleteLanguage($id);
}
unset($Phrases);
}
break;
case "m_lang_select":
$LangId = (int)$_POST["langselect"];
if($LangId)
{
if($objSession->Get("PortalUserId")>0)
{
//echo "$LangId";
$objSession->SetPersistantVariable("Language",$LangId);
}
$objSession->Set("Language",$LangId);
$objSession->Update();
$m_var_list_update["lang"] = $LangId;
$m_var_list["lang"] = $LangId;
}
break;
case "m_phrase_edit":
$objPhraseList = new clsPhraseList();
if((int)$_POST["direct"] != 1)
$objPhraseList->SourceTable = $objSession->GetEditTable("Phrase");
$Phrases = $_POST["name"];
foreach($Phrases as $PhraseId =>$name)
{
if($PhraseId>0)
{
$objPhraseList->EditPhrase($PhraseId,$_POST["name"][$PhraseId],$_POST["LanguageId"],$_POST["translation"][$PhraseId],$_POST["phrasetype"][$PhraseId]);
}
}
if(strlen($_POST["name"][0]) && strlen($_POST["translation"][0]) && $_POST['Action1'] == "new")
{
$r = $objPhraseList->AddPhrase($_POST["name"][0],$_POST["LanguageId"],$_POST["translation"][0],$_POST["phrasetype"][0]);
if ($r != "Error") {
$ado = GetADODBConnection();
$rs = $ado->Execute("SELECT MIN(PhraseId) as MinValue FROM ".$objPhraseList->SourceTable);
$NewId = $rs->fields["MinValue"]-1;
$sql = "UPDATE ".$objPhraseList->SourceTable." SET PhraseId=".$NewId." WHERE PhraseId=$PhraseId";
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql."<br>\n";
$ado->Execute($sql);
}
else {
$add_error = "Language tag with the same name already exists!";
}
}
else if ($_POST['Action1'] == "new") {
$add_error = "Fields name and translation are required!";
}
unset($objPhraseList);
break;
case "m_config_missing_phrase":
//phpinfo(INFO_VARIABLES);
$LangId = $_POST["LangId"];
$ThemeId = $_POST["ThemeId"];
if(is_array($_POST["Phrase"]))
{
$objPhraseList = new clsPhraseList();
$objPhraseList->SourceTable = $objSession->GetSessionKey()."_".$ThemeId."_labels";
foreach($_POST["Phrase"] as $p => $value)
{
if(strlen($value))
{
$obj = $objPhraseList->GetItemByField("Phrase",$p,TRUE);
if(is_object($obj))
{
if($obj->Get("Phrase")==$p)
{
$obj->Set("Translation",$value);
$obj->Update();
}
else
$objPhraseList->AddPhrase($p,$LangId,$value,1);
}
else
$objPhraseList->AddPhrase($p,$LangId,$value,1);
}
}
}
break;
case "m_phrase_delete":
$objPhraseList = new clsPhraseList();
$objPhraseList->SourceTable = $objSession->GetEditTable("Phrase");
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$objPhraseList->DeletePhrase($id);
}
}
unset($objPhraseList);
break;
case "m_emailevent_disable":
if($ro_perm) break;
$objEvents = new clsEventList();
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$m =& $objEvents->GetItem($id);
$m->Set("Enabled",0);
$m->Update();
}
}
unset($objEvents);
break;
case "m_emailevent_enable":
if($ro_perm) break;
$objEvents = new clsEventList();
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$m =& $objEvents->GetItem($id);
$m->Set("Enabled",1);
$m->Update();
}
}
unset($objEvents);
break;
case "m_emailevent_frontonly":
if($ro_perm) break;
$objEvents = new clsEventList();
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$m =& $objEvents->GetItem($id);
$m->Set("Enabled",2);
$m->Update();
}
}
unset($objEvents);
break;
case "m_dlid":
echo $Action.":".$DownloadId;
die();
break;
case "m_emailevent_user":
if($ro_perm) break;
$objEvents = new clsEventList();
//phpinfo(INFO_VARIABLES);
//$objEvents->SourceTable = $objSession->GetEditTable("Events");
$ids = $_POST["EventId"];
$ids = str_replace("[","",$ids);
$ids = str_replace("]","",$ids);
$ids = str_replace("\"","",$ids);
$ids = str_replace("\\","",$ids);
$idlist = explode(",",$ids);
foreach($idlist as $EventId)
{
$id = (int)stripslashes($EventId);
$e =& $objEvents->GetItem((int)$EventId);
$e->Set("FromUserId", $_POST["FromUserId"]);
$e->Update();
}
$objEvents->Clear();
unset($objEvents);
break;
case "m_emailevent_edit":
$Template = $_POST["headers"];
if(strlen($Template))
{
$Template .= "\n";
}
$Template = str_replace("\n\n","",$Template);
$Template .= "Subject: ".$_POST["subject"]."\n\n";
$Template .= $_POST["messageBody"];
$objMessages = new clsEmailMessageList();
$objMessages->SourceTable = $objSession->GetEditTable("EmailMessage");
$m =& $objMessages->GetItem($_POST["MessageId"]);
if(is_object($m))
{
if($_POST["sendhtml"]==1)
{
$m->Set("MessageType","html");
}
else
$m->Set("MessageType","text");
$m->Set("Template",$Template);
$m->Update();
}
break;
case "m_config_edit":
//phpinfo(INFO_VARIABLES);
if($ro_perm) break;
$objAdmin = new clsConfigAdmin();
$objAdmin->module = $_POST["module"];
$objAdmin->section = $_POST["section"];
if($objAdmin->section=="in-portal:configure_users")
{
if(strlen($_POST["RootPass"]) && strlen($_POST["RootPassVerify"]))
{
if($_POST["RootPass"]==$_POST["RootPassVerify"])
{
$_POST["RootPass"] = md5($_POST["RootPass"]);
}
}
else
{
$_POST["RootPass"] = $objConfig->Get("RootPass");
$_POST["RootPassVerify"] = $objConfig->Get("RootPassVerify");
}
}
$objAdmin->LoadItems(FALSE);
$objAdmin->SaveItems($_POST);
break;
case "m_mod_enable":
if($ro_perm) break;
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$m =& $objModules->GetItemByField("Name",$id);
if(is_object($m))
{
$m->Set("Loaded",1);
$m->Update();
}
}
$_GET["Refresh"] = 1;
}
break;
case "m_mod_disable":
if($ro_perm) break;
if (isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
if($id != "In-Portal")
{
$m =& $objModules->GetItemByField("Name",$id);
if(is_object($m))
{
$m->Set("Loaded",0);
$m->Update();
}
}
}
$_GET["Refresh"] = 1;
}
break;
case "m_img_add":
$objImageList = new clsImageList();
$objImageList->SourceTable = $objSession->GetEditTable("Images");
$LocalImage=0;
$LocalThumb=0;
$DestDir = "kernel/images/";
$UserThumbSource = (int)$_POST["imgLocalThumb"];
$LocalThumb = $UserThumbSource;
$thumb_url = !$LocalThumb? $_POST["imgThumbUrl"] : "";
if($_POST["imgSameImages"])
{
$LocalImage = $LocalThumb;
$full_url = $thumb_url;
}
else
{
$LocalImage = (int)$_POST["imgLocalFull"];
$file = $_FILES["imgFullFile"];
$full_url = $LocalImage? "" : $_POST["imgFullUrl"];
}
if((!strlen($thumb_url) && !$LocalThumb) || (!strlen($full_url) && !$LocalImage))
{
break;
}
$ado = GetADODBConnection();
$sql = "SELECT MIN(ImageId) as MinValue FROM ".$objImageList->SourceTable;
$rs = $ado->Execute($sql);
$NewId = ($rs->fields["MinValue"]<0)? $rs->fields["MinValue"]-1 : -1;
$img = $objImageList->Add($_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImage, $LocalThumb, $full_url, $thumb_url, (int)$_POST["imgEnabled"], 0, (int)$_POST["imgDefault"], 0,(int)$_POST["imgSameImages"], $NewId);
$img->Set("ImageId", $NewId);
// $img->debuglevel=1;
/*
$sql = "UPDATE ".$objImageList->SourceTable." SET ImageId=".$NewId." WHERE ImageId=0";
$ado->Execute($sql);
// $img->Update();
*/
// echo "SL: $sql $NewId<BR>";
// $img->debuglevel=1;
$img->Pending=TRUE;
if($LocalImage)
{
$file = $_FILES["imgFullFile"];
if(is_array($file))
{
if($file["size"]>0)
{
$img->Set("LocalPath",$img->StoreUploadedImage($file,1, $DestDir,0));
$uploaded=1;
}
}
}
if($LocalThumb)
{
$thumb = $_FILES["imgThumbFile"];
if(is_array($thumb))
{
if($thumb["size"]>0)
{
$img->Set("ThumbPath",$img->StoreUploadedImage($thumb,1, $DestDir,1));
$uploaded=1;
}
}
}
if($uploaded==1)
$img->Update();
break;
case "m_img_edit":
$objImageList = new clsImageList();
$objImageList->SourceTable = $objSession->GetEditTable("Images");
// $img->debuglevel=1;
$img = $objImageList->GetItem($_POST["ImageId"]);
## Get original values
$LocalImage = $img->Get("LocalImage");
$LocalThumb = $img->Get("LocalThumb");
$SameImages = $img->Get("SameImages");
$ThumbPath = $img->Get("ThumbPath");
## New values
$LocalThumbN = (int)$_POST["imgLocalThumb"];
$LocalImageN = (int)$_POST["imgLocalFull"];
$FULLFile = $_FILES["imgFullFile"];
$THFile = $_FILES["imgThumbFile"];
$DestDir = "kernel/images/";
$img->Pending = FALSE;
$SameImagesN = 0;
$uploaded = 0;
## Images were the same, but not any more
if ($SameImages && !$_POST["imgSameImages"])
{
## TH was a local file
if ($LocalThumb)
{
## TH image
{
## Try to Delete OLD FULL
$img->DeleteLocalImage(FALSE, TRUE);
## FULL image select, but field EMPTY - make a copy of old TH as FULL
if ($LocalImageN && !(int)$FULLFile["size"])
{
// echo $pathToPending = $img->GetImageDir();
if (!eregi("pending/$", $pathToPending))
$pathToPending.= "pending/";
$LocalThumb_File = $img->GetFileName(1);
// echo "<b>CAN'T FIND FILE:</b> ".$pathToPending.$LocalThumb_File."<BR>";
if (file_exists($pathToPending.$LocalThumb_File))
{
$LocalThumb_FileN = eregi_replace("^th_", "", $LocalThumb_File);
$LocalThumb_FullFileN = $pathToPending.$LocalThumb_FileN;
@unlink($LocalThumb_FullFileN);
@copy($pathToPending.$LocalThumb_File, $LocalThumb_FullFileN);
$uploaded = 1;
$copied = 1;
// echo "COPING: ".$DestDir."pending/".$LocalThumb_FileN." <BR>";
}
else
{
// echo "CAN'T FIND FILE: ".$pathToPending.$LocalThumb_File."<BR>";
}
}
## Upload new FULL image
elseif ($LocalImageN && (int)$FULLFile['size'])
{
$FULL_FileToUpload = $FULLFile;
$FULL_URL = "";
// echo " Upload new FULL image";
}
## Full is URL
elseif (!$LocalImageN)
{
$img->DeleteLocalImage(FALSE, TRUE);
$FULL_URL = $_POST['imgFullUrl'];
$FULL_FileToUpload = "";
}
else
{
// echo " ## Unknow condition";
}
## Take care of Thumbnail here
if ($LocalThumbN)
{
## Delete old if NEW TH image selected
if ((int)$THFile['size'])
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = $THFile;
}
else
$TH_FileToUpload = "";
}
else
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = "";
$TH_URL = $_POST['imgThumbUrl'];
}
}
}
## TH was URL
else
{
## Take care of FULL image here
if ($LocalImageN && (int)$FULLFile["size"])
{
$FULL_FileToUpload = $FULLFile;
$FULL_URL = "";
}
## Full is URL (or image size 0)
else
{
$FULL_FileToUpload = "";
$FULL_URL = $_POST['imgFullUrl'];
}
## Take care of Thumbnail here
if ($LocalThumbN)
{
$TH_FileToUpload = (int)$THFile['size']? $THFile : "";
$TH_URL = "";
}
else
{
$TH_FileToUpload = "";
$TH_URL = $_POST['imgThumbUrl'];
}
}
}
## Images were the same, and still the same
elseif ($SameImages && $_POST['imgSameImages'])
{
## Take care of Thumbnail & FULL here
if ($LocalThumbN)
{
if ((int)$THFile['size'])
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = $THFile;
}
else
$TH_FileToUpload = "";
$FULL_URL = $TH_URL = "";
}
else
{
$TH_FileToUpload = $FULL_FileToUpload = "";
$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];
}
## Delete old FULL image
$img->DeleteLocalImage(FALSE,TRUE);
$SameImagesN = 1;
}
## Images were NOT the same, and selected as the same now
elseif (!$SameImages && $_POST["imgSameImages"])
{
## Take care of Thumbnail & FULL here
if ($LocalThumbN)
{
if ((int)$THFile['size'])
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = $THFile;
}
else
$TH_FileToUpload = "";
$FULL_URL = $TH_URL = "";
}
else
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = $FULL_FileToUpload = "";
$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];
}
## Clean up FULL image
$img->DeleteLocalImage(FALSE, TRUE);
$SameImagesN = 1;
}
## Images were NOT the same, and selected as NOT the same
elseif (!$SameImages && !$_POST["imgSameImages"])
{
## Take care of Thumbnail
if ($LocalThumbN)
{
if ((int)$THFile['size'])
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = $THFile;
}
else
$TH_FileToUpload = "";
$TH_URL = "";
}
else
{
$img->DeleteLocalImage(TRUE, FALSE);
$TH_FileToUpload = "";
$TH_URL = $_POST['imgThumbUrl'];
}
## Take care of FULL here
if ($LocalImageN)
{
if ((int)$FULLFile['size'])
{
$img->DeleteLocalImage(FALSE, TRUE);
$FULL_FileToUpload = $FULLFile;
}
else
$FULL_FileToUpload = "";
$FULL_URL = "";
}
else
{
$img->DeleteLocalImage(FALSE, TRUE);
$FULL_FileToUpload = "";
$FULL_URL = $_POST['imgFullUrl'];
}
}
## Unknow condition
else
{
;
}
$img = $objImageList->Edit($_POST["ImageId"],$_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImageN, $LocalThumbN, $FULL_URL, $TH_URL, (int)$_POST["imgEnabled"], (int)$_POST["imgPriority"], (int)$_POST["imgDefault"], 0, $SameImagesN);
// echo "<B>DATA:</B> <BR> LocalImageN: $LocalImageN, LocalThumbN: $LocalThumbN, FULL_URL: $FULL_URL, TH_URL: $TH_URL, SameImagesN: $SameImagesN <BR>";
$img->Pending = TRUE;
if (!empty($FULL_FileToUpload))
{
$img->Set("LocalPath",$img->StoreUploadedImage($FULL_FileToUpload, 1, $DestDir, 0));
$uploaded = 1;
}
/*
elseif (!$LocalImageN)
{
$img->Set("LocalPath", "");
$uploaded = 1;
}
*/
if (!empty($TH_FileToUpload))
{
$img->Set("ThumbPath", $img->StoreUploadedImage($TH_FileToUpload, 1, $DestDir, 1));
$uploaded = 1;
}
if ($copied)
{
$img->Set("LocalPath", $DestDir."pending/".$LocalThumb_FileN);
$uploaded = 1;
}
if($uploaded==1)
$img->Update();
break;
case "m_img_move_up":
if (isset($_POST["itemlist"]))
{
$objImageList = new clsImageList();
$objImageList->SourceTable = $objSession->GetEditTable("Images");
foreach($_POST["itemlist"] as $id)
{
$img = $objImageList->GetItem($id);
$img->MoveUp();
}
}
break;
case "m_img_move_down":
if (isset($_POST["itemlist"]))
{
$objImageList = new clsImageList();
$objImageList->SourceTable = $objSession->GetEditTable("Images");
$itemlist=array_reverse($_POST["itemlist"]);
foreach($itemlist as $id)
{
$img = $objImageList->GetItem($id);
$img->MoveDown();
}
}
break;
case "m_img_delete":
if(isset($_POST["itemlist"]))
{
$objImageList = new clsImageList();
$objImageList->SourceTable = $objSession->GetEditTable("Images");
foreach($_POST["itemlist"] as $id)
{
$img = $objImageList->GetItem($id);
$img->Set("ResourceId", 0);
$img->Update();
//$img->Delete();
}
}
break;
case "m_restore_delete":
$bdate = $_POST["backupdate"];
if($bdate>0)
{
$BackupFile = $objConfig->Get("Backup_Path")."/dump".$bdate.".txt";
if(file_exists($BackupFile))
unlink($BackupFile);
}
break;
case "m_taglib":
include($pathtoroot."kernel/include/tag-class.php");
ParseTagLibrary();
break;
case "m_sql_query":
$SqlQuery = $_POST["sql"];
$ado = GetADODBConnection();
if(strlen($sql))
{
$SqlResult = $ado->Execute(stripslashes($SqlQuery));
$SqlError = $ado->ErrorMsg();
$SqlErrorNum = $ado->ErrorNo();
}
break;
case "m_session_delete":
if($ro_perm) break;
$ado = GetADODBConnection();
if (count($_POST['itemlist']) > 0) {
foreach($_POST["itemlist"] as $id)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey='$id'";
$ado->Execute($sql);
}
}
else {
$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE Status='0'";
$ado->Execute($sql);
}
break;
case "m_add_rule":
$objEditItems = new clsBanRuleList();
$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
$objEditItems->AddRule($_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
$_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
(int)$_POST["rule_status"], $_POST['rule_error']);
break;
case "m_edit_rule":
$objEditItems = new clsBanRuleList();
$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
$objEditItems->EditRule($_POST["rule_id"],$_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
$_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
(int)$_POST["rule_status"], $_POST['rule_error']);
break;
case "m_rule_move_up":
if($ro_perm) break;
if(isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$i = $objBanList->GetItem($id);
$i->Increment("Priority");
}
}
break;
case "m_rule_move_down":
if($ro_perm) break;
if(isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$i = $objBanList->GetItem($id);
$i->Decrement("Priority");
}
}
break;
case "m_rule_delete":
if($ro_perm) break;
if(isset($_POST["itemlist"]))
{
foreach($_POST["itemlist"] as $id)
{
$i = $objBanList->GetItem($id);
$i->Delete();
}
}
break;
case "m_ban_user":
if($ro_perm) break;
if($_POST["UserEditStatus"]==1)
{
$UserId = $_POST["user_id"];
$u = $objUsers->GetItem($UserId);
if(is_object($u))
{
if((int)$_POST["ban_login"])
{
if(strlen($_POST["user_login"]))
$objBanList->AddRule(6,0,"Login",3,$_POST["user_login"],0,1);
}
if((int)$_POST["ban_email"])
{
if(strlen($_POST["user_email"]))
$objBanList->AddRule(6,0,"Email",3,$_POST["user_email"],0,1);
}
if((int)$_POST["ban_ip"])
{
if(strlen($_POST["user_ip"]))
$objBanList->AddRule(6,0,"ip",3,$_POST["user_ip"],0,1);
}
$u->Deny();
}
}
break;
}
/* image upload management */
if( isset($_POST['img']) && $_POST['img'] == 1 )
{
foreach($_FILES as $img => $FILE)
{
$name = $_POST["img_Name_$img"];
$alt = $_POST["img_Alt_$img"];
$url = $_POST["img_Url_$img"];
$res_id = $_POST["img_Res_$img"];
$relvalue = $_POST["img_Rel_$img"];
$thumb = (int)$_POST["img_Thumb_$img"];
$dest = AddSlash($_POST["img_DestDir_$img"]);
if($_POST["img_Del_$img"]=="Delete")
{
$img = $objImageList->GetImageByResource($res_id,$relvalue);
$img->Delete();
unset($img);
$objImageList->Clear();
}
else
{
if($FILE["size"]>0)
{
/* an image was uploaded */
$objImageList->HandleImageUpload($FILE,$res_id,$relvalue,$dest, $name,$alt,$thumb);
}
else
{ /* remote images handled here */
if(strlen($url)>0)
{
if($relvalue>0)
{
$img = $objImageList->GetImageByResource($res_id,$relvalue);
$img->Set("Name",$name);
$img->Set("AltName", $alt);
$img->Set("IsThumbnail",$thumb);
$img->Set("Url",$url);
$img->Update();
}
else
{
$relvalue = $objImageList->GetNextRelateValue($res_id);
$objImageList->NewRemoteImage($url,$res_id,$relvalue, $name, $alt, $thumb);
}
}
}
}
}
}
// ALL Saving Stuff From Temp Tables Heppens Here
//echo "==== BEGIN ==== <br>";
$has_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
//echo "PortalUserID: [".$objSession->Get("PortalUserId")."]<br>";
//echo "PermSet: [".$has_perm."]<br>";
if( !$has_perm )
{
/* category Edit */
if( GetVar('CatEditStatus') == 1 )
{
$adodbConnection = GetADODBConnection();
// $sql = "SELECT * FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=0";
$sql = "SELECT * FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=-1";
$rs = $adodbConnection->Execute($sql);
while ($rs && !$rs->EOF)
{
if($rs->fields["ParentId"]>0)
RunUp($rs->fields["ParentId"],"Increment_Count");
$rs->MoveNext();
}
$objCatList->CopyFromEditTable("CategoryId");
$objCustomDataList->CopyFromEditTable("CustomDataId");
$objCatList->Clear();
if($_REQUEST['CategoryId'] > 0) // not root category is updated
{
$objImages = new clsImageList();
$objImages->CopyFromEditTable("ImageId");
}
}
if( GetVar('CatEditStatus') == 2 )
{
$objCatList->PurgeEditTable("CategoryId");
$objCustomDataList->PurgeEditTable("CustomDataId");
if($_REQUEST['CategoryId'] > 0) // not root category is updated
{
$objImages = new clsImageList();
$objImages->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 ".$objPhraseList->SourceTable);
+ $ado->Execute("DROP TABLE IF EXISTS ".$objPhraseList->SourceTable);
}
if( GetVar('MissingLangEditStatus') == 2 )
{
$table = $objSession->GetSessionKey()."_".$ThemeId."_labels";
$ado = GetADODBConnection();
- $ado->Execute("DROP TABLE ".$table);
+ $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.22
\ No newline at end of property
+1.23
\ No newline at end of property
Index: trunk/kernel/include/emailmessage.php
===================================================================
--- trunk/kernel/include/emailmessage.php (revision 270)
+++ trunk/kernel/include/emailmessage.php (revision 271)
@@ -1,884 +1,884 @@
<?php
class clsEmailMessage extends clsParsedItem
{
var $Event = "";
var $Item;
var $headers = array();
var $subject = "";
var $body = "";
var $TemplateParsed = FALSE;
var $recipient = NULL;
var $fromuser = NULL;
function clsEmailMessage($MessageId=NULL,$Item=NULL)
{
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."EmailMessage";
$this->Item = $Item;
$this->BasePermission = "EMAIL";
$this->id_field = "EmailMessageId";
$this->TagPrefix = "email";
$this->NoResourceId=1;
if($MessageId)
$this->LoadFromDatabase($MessageId);
}
function LoadEvent($event,$language=NULL)
{
global $objConfig, $objLanguages;
if(!strlen($language))
$language = $objLanguages->GetPrimary();
$sql = "SELECT * FROM ".$this->tablename." WHERE EventId = $event AND LanguageId=$language";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
else
return FALSE;
}
function LoadFromDatabase($MessageId)
{
global $Errors;
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$MessageId);
$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);
return TRUE;
}
function EditTemplate()
{
}
/* read the template, split into peices */
function ReadTemplate()
{
if(!$this->TemplateParsed)
{
$this->headers = array();
$lines = explode("\n",$this->Get("Template"));
$header_end = FALSE;
$i = 0;
while(!$header_end && $i<count($lines))
{
$h = $lines[$i];
if(strlen(trim($h))==0 || ($h=="."))
{
$header_end = TRUE;
}
else
{
$parts = explode(":",$h,2);
if(strtolower($parts[0])=="subject")
{
$this->subject = $h;
}
else
$this->headers[] = $h;
}
$i++;
}
while($i<count($lines))
{
$this->body .= $lines[$i++];
}
$this->TemplateParsed=TRUE;
}
}
function ParseSection($text, $parser=null)
{
global $objUsers, $objTemplate;
$res = $this->ParseTemplateText($text);
/* parse email class tags */
if(!is_object($this->fromuser))
{
$this->fromuser = $objUsers->GetItem($this->Get("FromUserId"));
$this->fromuser->TagPrefix = "fromuser";
}
/* parse from user object */
if(is_object($this->fromuser))
{
$res = $this->fromuser->ParseTemplateText($res);
}
/* parse recipient user object */
if(is_object($this->recipient))
{
$res = $this->recipient->ParseTemplateText($res);
}
//print_pre($this->Item);
if(is_object($this->Item))
{
$res = $this->Item->ParseTemplateText($res);
}
else
{
if(!is_object($objTemplate))
$objTemplate = new clsTemplateList(" ");
$res = $objTemplate->ParseTemplateText($res);
}
return $res;
}
function SendToGroup($GroupId)
{
global $objUsers;
$users = $objUsers->Query_GroupPortalUser("GroupId=$GroupId");
if(is_array($users))
{
foreach($users as $u)
{
$this->SendToUser($u->Get("PortalUserId"));
}
}
}
function SendToAddress($EmailAddress,$name="")
{
global $objUsers, $objEmailQueue,$objConfig;
//$this->recipient = $objUsers->GetUser($UserId);
//$this->recipient->TagPrefix="touser";
if(strlen($EmailAddress))
{
$to_addr = $EmailAddress;
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject);
$body = $this->ParseSection($this->body);
if(is_object($this->fromuser))
{
$FromAddr = $this->fromuser->Get("Email");
$FromName = trim($this->fromuser->Get("FirstName")." ".$this->fromuser->Get("LastName"));
}
if(!strlen($FromAddr))
{
$FromName = $objConfig->Get("Site_Name");
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
}
$charset = "ascii-us";
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset,NULL,$this->headers);
}
else
{
$body = nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset,NULL,$this->headers);
}
return TRUE;
}
return FALSE;
}
function SendToUser($UserId)
{
global $objUsers, $objEmailQueue, $objConfig;
//echo "Handling Event ".$this->Get("Event")." for user $UserId <br>\n";
$this->recipient = new clsPortalUser($UserId); // $objUsers->GetItem($UserId);
//echo "<PRE>";print_r($this->recipient); echo "</PRE>";
$this->recipient->TagPrefix="touser";
if($this->recipient->Get("PortalUserId")==$UserId)
{
$to_addr = $this->recipient->Get("Email");
$To = trim($this->recipient->Get("FirstName")." ".$this->recipient->Get("LastName"));
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject, $this->recipient);
$body = $this->ParseSection($this->body);
if(!is_object($this->fromuser))
{
$this->fromuser = $objUsers->GetItem($this->Get("FromUserId"));
}
if(is_object($this->fromuser))
{
$FromAddr = $this->fromuser->Get("Email");
$FromName = trim($this->fromuser->Get("FirstName")." ".$this->fromuser->Get("LastName"));
$charset = "ascii-us";
}
if(!strlen($FromAddr))
{
$FromName = $objConfig->Get("Site_Name");
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
}
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset,NULL,$this->headers);
}
else
{
$body = nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset,NULL,$this->headers);
}
return TRUE;
}
return FALSE;
}
function SendAdmin()
{
global $objUsers, $objConfig, $objEmailQueue;
$this->recipient = $objUsers->GetUser($this->Get("FromUserId"));
$this->recipient->TagPrefix="touser";
if($this->recipient->Get("PortalUserId")==$this->Get("FromUserId"))
{
$to_addr = $this->recipient->Get("Email");
$To = trim($this->recipient->Get("FirstName")." ".$this->recipient->Get("LastName"));
$this->ReadTemplate();
$subject = $this->ParseSection($this->subject);
$body = $this->ParseSection($this->body);
$FromName = "System Event";
$FromAddr = $objConfig->Get("Smtp_AdminMailFrom");
if(strlen($FromAddr))
{
$charset = "ascii-us";
if($this->Get("MessageType")=="html")
{
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,"",$body,$charset,NULL,$this->headers);
}
else
{
$body=nl2br($body);
$body = str_replace("<br />","\n",$body);
$objEmailQueue->SendMail($FromAddr,$FromName,$to_addr,$To,$subject,$body,"",$charset,NULL,$this->headers);
}
return TRUE;
}
}
return FALSE;
}
function ParseTemplateText($text)
{
$html = $text;
$search = "<inp:".$this->TagPrefix;
$next_tag = strpos($html,"<inp:");
//$next_tag = strpos($html,$search);
while($next_tag)
{
$closer = strpos(strtolower($html),">",$next_tag);
$end_tag = strpos($html,"/>",$next_tag);
if($end_tag < $closer || $closer == 0)
{
$tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2);
$pre = substr($html,0,$next_tag);
$post = substr($html,$end_tag+2);
$inner = $this->ParseElement($tagtext);
$html = $pre.$inner.$post;
}
else
{
$OldTagStyle = "</inp>";
## Try to find end of TagName
$TagNameEnd = strpos($html, " ", $next_tag);
## Support Old version
// $closer = strpos(strtolower($html),"</inp>",$next_tag);
if ($TagNameEnd)
{
$Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag));
$TagName = explode(":", $Tag);
if (strlen($TagName[1]))
$CloserTag = "</inp:".$TagName[1].">";
}
else
{
$CloserTag = $OldTagStyle;
}
$closer = strpos(strtolower($html), $CloserTag, $next_tag);
## Try to find old tag closer
if (!$closer && ($CloserTag != $OldTagStyle))
{
$CloserTag = $OldTagStyle;
$closer = strpos(strtolower($html), $CloserTag, $next_tag);
}
$end_tag = strpos($html,">",$next_tag);
$tagtext = substr($html,$next_tag,($end_tag - $next_tag)+1);
$pre = substr($html,0,$next_tag);
$inner = substr($html,$end_tag+1,$closer-($end_tag+1));
$post = substr($html,$end_tag+1+strlen($inner) + strlen($CloserTag));
//echo "PRE:". htmlentities($pre,ENT_NOQUOTES);
//echo "INNER:". htmlentities($inner,ENT_NOQUOTES);
//echo "POST:". htmlentities($post,ENT_NOQUOTES);
$parsed = $this->ParseElement($tagtext);
if(strlen($parsed))
{
$html = $pre.$this->ParseTemplateText($inner).$post;
}
else
$html = $pre.$post;
}
$next_tag = strpos($html,$search);
}
return $html;
}
function ParseElement($raw, $inner_html ="")
{
$tag = new clsHtmlTag($raw);
$tag->inner_html = $inner_html;
if($tag->parsed)
{
if($tag->name=="include" || $tag->name=="perm_include" || $tag->name=="lang_include")
{
$output = $this->Parser->IncludeTemplate($tag);
}
else
{
if (is_object($this->Item)) {
$output = $this->Item->ParseObject($tag);
}
else {
$output = $this->ParseObject($tag);
}
//echo $output."<br>";
if(substr($output,0,9)=="Undefined")
{
$output = $tag->Execute();
// if(substr($output,0,8)="{Unknown")
// $output = $raw;
} return $output;
}
}
else
return "";
}
}
class clsEmailMessageList extends clsItemCollection
{
function clsEmailMessageList()
{
$this->clsItemCollection();
$this->classname = "clsEmailMessage";
$this->SourceTable = GetTablePrefix()."EmailMessage";
$this->PerPageVar = "Perpage_EmailEvents";
$this->AdminSearchFields = array("Template","Description", "Module","Event");
}
function LoadLanguage($LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$sql = "SELECT * FROM ".$this->SourceTable." WHERE LanguageId=$LangId";
$this->Clear();
return $this->Query_Item($sql);
}
function &GetMessage($EventId,$LangId,$LoadFromDB=TRUE)
{
$found=FALSE;
if(is_array($this->Items))
{
for($x=0;$x<count($this->Items);$x++)
{
$i =& $this->GetItemRefByIndex($x);
if(is_object($i))
{
if($i->Get("EventId")==$EventId && $i->Get("LanguageId")==$LangId)
{
$found=TRUE;
break;
}
}
}
}
if(!$found)
{
if($LoadFromDB)
{
$n = NULL;
$n = new $this->classname();
$n->tablename = $this->SourceTable;
if($n->LoadEvent($EventId,$LangId))
{
array_push($this->Items, $n);
$i =& $this->Items[count($this->Items)-1];
}
else
$i = FALSE;
}
else
$i = FALSE;
}
return $i;
}
function CreateEmptyEditTable($IdList)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
$query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
$this->LoadLanguage();
$idvalue = -1;
for($i=0;$i<$this->NumItems();$i++)
{
$e =& $this->Items[$i];
$e->SourceTable = $edit_table;
if(is_array($IdList))
{
foreach($IdList as $id)
{
$e->UnsetIdField();
$e->Set("EmailMessageId",$idvalue--);
$e->Set("LanguageId",$id);
$e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$id));
$e->Create();
}
}
else
{
$e->UnsetIdField();
$e->Set("EmailMessageId",$idvalue--);
$e->Set("LanguageId",$IdList);
$e->Set("Description",admin_language("la_desc_emailevent_".$e->Get("Event"),$LangId));
$e->Create();
}
}
$this->Clear();
}
function CopyFromEditTable()
{
global $objSession;
$idfield = "EmailMessageId";
$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;
if($c->Get($idfield)<1)
{
$old_id = $c->Get($idfield);
$c->Dirty();
$c->UnsetIdField();
$c->Create();
}
else
{
$c->Dirty();
$c->Update();
}
$rs->MoveNext();
}
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function &GetEmailEventObject($EventName,$Type=0,$LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$EmailTable = $this->SourceTable;
$EventTable = GetTablePrefix()."Events";
$sql = "SELECT * FROM $EventTable INNER JOIN $EmailTable ON ($EventTable.EventId = $EmailTable.EventId) ";
$sql .="WHERE Event='$EventName' AND LanguageId=$LangId AND Type=$Type";
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
//$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"","clsEvent","GetEmailEventObject");
return FALSE;
}
$data = $result->fields;
$e = new clsEmailMessage();
$e->SetFromArray($data);
$e->Clean();
return $e;
}
function ReadImportTable($TableName,$Overwite=FALSE, $MaxInserts=100,$Offset=0)
{
$eml = new clsEmailMessageList();
$this->Clear();
$Inserts = 0;
$sql = "SELECT * FROM $TableName LIMIT $Offset,$MaxInserts";
$this->Query_Item($sql);
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$e = $eml->GetMessage($i->Get("EventId"),$i->Get("LanguageId"));
if(is_object($e))
{
if($Overwrite)
{
$e->Set("MessageType",$i->Get("MessageType"));
$e->Set("Template",$i->Get("Template"));
$e->Update();
}
}
else
{
$i->Create();
}
$Inserts++;
}
}
$Offset = $Offset + $Inserts;
return $Offset;
}
}
function EventEnabled($e)
{
global $objConfig;
$var = "Email_".$e."_Enabled";
return ($objConfig->Get($var)=="1");
}
class clsEmailQueue
{
var $SourceTable;
var $MessagesAtOnce;
var $MessagesSent=0;
var $LogLevel = 0;
function clsEmailQueue($SourceTable=NULL,$MessagesAtOnce=NULL)
{
global $objConfig;
if($SourceTable)
{
$this->SourceTable=$SourceTable;
}
else
$this->SourceTable = GetTablePrefix()."EmailQueue";
if(!$MessagesAtOnce)
$MessagesAtOnce = (int)$objConfig->Get("Email_MaxSend");
if($MessagesAtOnce<1)
$MessagesAtOnce=1;
$this->MessagesAtOnce = $MessagesAtOnce;
$this->LogLevel = (int)$objConfig->Get("Smtp_LogLevel");
}
function WriteToMailLog($text)
{
global $pathtoroot,$admin;
//echo htmlentities($text)."<br>\n";
if($this->LogLevel>0)
{
$Logfile = $pathtoroot.$admin."/email/log.txt";
if(is_writable($Logfile))
{
$fp = fopen($Logfile,"a");
if($fp)
{
fputs($fp,$text."\n");
fclose($fp);
}
}
}
}
function AllowSockets()
{
$minver = explode(".", "4.3.0");
$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 DeliverMail($To,$From,$Subject,$Msg,$headers, $ForceSend=0)
{
global $MessagesSent,$objConfig;
if(($this->MessagesSent >$this->MessagesAtOnce) && !$ForceSend)
{
$this->EnqueueMail($To,$From,$Subject,$Msg,$headers);
return TRUE;
}
else
{
$this->MessagesSent++;
/* ensure headers are using \r\n instead of \n */
//$headers = str_replace("\r\n","\n",$headers);
//$headers = str_replace("\n","\r\n",$headers);
$headers = "Date: ".date("r")."\n".$headers;
$headers = "Return-Path: ".$objConfig->Get("Smtp_AdminMailFrom")."\n".$headers;
//$Msg = str_replace("\r\n","\n",$Msg);
//$Msg = str_replace("\n","\r\n",$Msg);
//echo "<PRE>"; print_r(htmlentities($headers)); echo "</PRE>";
//echo "<PRE>"; print_r(htmlentities($Msg)); echo "</PRE>";
$ver = phpversion();
if(substr($Subject,0,9)=="Subject: ")
$Subject = substr($Subject,9);
if(!strlen($objConfig->Get("Smtp_Server")) || !$this->AllowSockets())
{
return mail($To,trim($Subject),$Msg, $headers);
}
$headers = "Subject: ".trim($Subject)."\r\n".$headers;
$send_params['recipients'] = array($To); // The recipients (can be multiple)
$send_params['headers'] = explode("\r\n",$headers);
$send_params['from'] = $From; // This is used as in the MAIL FROM: cmd
// It should end up as the Return-Path: header
$send_params['body'] = $Msg; // The body of the email
$params['host'] = $objConfig->Get("Smtp_Server"); // The smtp server host/ip
$params['port'] = 25; // The smtp server port
$params['helo'] = 'INPORTAL'; // What to use when sending the helo command. Typically, your domain/hostname
if($objConfig->Get("Smtp_Authenticate")) // Whether to use basic authentication or not
{
$params['auth'] = TRUE;
$params['user'] = $objConfig->Get("Smtp_User");
$params['pass'] = $objConfig->get("Smtp_Pass");
}
else
$params['auth'] = FALSE;
$this->LogLevel=0;
$SmtpServer = new smtp($params);
if($this->LogLevel>0)
{
$SmtpServer->debug=1;
foreach($params as $key=>$value)
{
$this->WriteToMailLog($key."=".$value);
}
}
else
$SmtpServer->debug = 0;
$connected = $SmtpServer->connect();
if($connected)
{
if($this->LogLevel>1)
{
$this->WriteToMailLog("Connected to ".$params['host']);
}
$res = $SmtpServer->send($send_params);
}
$SmtpServer->disconnect();
if($this->LogLevel>1)
{
foreach($SmtpServer->buffer as $l)
{
$this->WriteToMailLog($l);
}
}
if($this->LogLevel>0)
{
if(count($SmtpServer->errors)>0)
{
foreach($SmtpServer->errors as $e)
{
$this->WriteToMailLog($e);
}
}
else
$this->WriteToMailLog("Message to $From Delivered Successfully");
}
unset($SmtpServer);
return $res;
}
}
function EnqueueMail($To,$From,$Subject,$Msg,$headers)
{
global $objSession;
$ado = GetADODBConnection();
$To = mysql_escape_string($To);
$From = mysql_escape_string($From);
$Msg = mysql_escape_string($Msg);
$headers = mysql_escape_string($headers);
$Subject = mysql_escape_string($Subject);
$sql = "INSERT INTO ".$this->SourceTable." (toaddr,fromaddr,subject,message,headers) VALUES ('$To','$From','$Subject','$Msg','$headers')";
$ado->Execute($sql);
}
function SendMailQeue()
{
global $objConfig, $objSession, $TotalMessagesSent;
$ado = GetADODBConnection();
$MaxAllowed = $this->MessagesAtOnce;
$del_sql = array();
$NumToSend = $MaxAllowed - $this->MessagesSent;
$sql = "SELECT * FROM ".$this->SourceTable." ORDER BY queued ASC LIMIT $NumToSend";
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->DeliverMail($data["toaddr"],$data["fromaddr"],$data["Subject"],$data["headers"],$data["message"],1);
$del_sql[] = "DELETE FROM ".$this->SourceTable." WHERE queued=".$data["queued"];
$rs->MoveNext();
}
$numdel = count($del_sql);
for($i=0;$i<$numdel;$i++)
{
$sql = $del_sql[$i];
if(strlen($sql))
$ado->Execute($sql);
if($objSession->HasSystemPermission("DEBUG.ITEM"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
}
}
function SendMail($From, $FromName, $ToAddr, $ToName, $Subject, $Text, $Html, $charset,
$FileName="",$FileLoc="",$QueueOnly=0,$extra_headers = array())
{
$HasFile = FALSE;
$HasFile = (strlen($FileName)>0);
$OB="----=_OuterBoundary_000";
$boundary = "-----=".md5( uniqid (rand()));
$f = "\"$FromName\" <".$From.">";
$headers = "From: $f\n";
$headers .= "MIME-Version: 1.0\n";
if($HasFile)
{
//Messages start with text/html alternatives in OB
$headers.="Content-Type: multipart/mixed;\n\tboundary=\"".$OB."\"\n\n";
$msg.="--".$OB."\n";
$msg.="Content-Type: multipart/alternative; boundary=\"$boundary\"\n\n";
}
else
$headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"";
if(is_array($extra_headers))
{
for($i=0;$i<count($extra_headers);$i++);
{
$headers .= $extra_headers[$i]."\n";
}
}
$msg .="This is a multi-part message in MIME format.\n\n";
$msg .= "--" . $boundary . "\n";
$msg .= "Content-Type: text/plain; charset=\"$charset\"\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n";
$msg .= stripslashes($Text);
$msg .= "\r\n\r\n";
if(strlen($Html)>0)
{
$msg .= "--" . $boundary . "\n";
$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$msg .= stripslashes($Html);
$msg .= "\r\n\r\n";
}
$msg .= "--" . $boundary . "--\n";
if($HasFile)
{
if(!strlen($FileLoc))
$FileLoc = $FileName;
$FileName = basename($FileName);
$msg .= "\n--".$OB."\n";
$msg.="Content-Type: application/octetstream;\n\tname=\"".$FileName."\"\r\n";
$msg.="Content-Transfer-Encoding: base64\n";
$msg.="Content-Disposition: attachment;\n\tfilename=\"".$FileName."\"\r\n\r\n";
//file goes here
$fd=fopen ($FileLoc, "r");
if($fd)
{
$FileContent=fread($fd,filesize($FileLoc));
fclose ($fd);
}
$FileContent=chunk_split(base64_encode($FileContent));
$msg.=$FileContent;
$msg .= "--".$OB."\n";
}
if(strlen($ToName)>0)
{
$To = "\"$ToName\" <$ToAddr>";
}
else
$To = "<".$ToAddr.">";
//$headers.="To: $To\r\n";
if($this->MessagesSent>$this->MessagesAtOnce || $QueueOnly==1)
{
$this->EnqueueMail($To,$f,$Subject,$msg,$headers);
}
else
{
$this->DeliverMail($To,$f,$Subject,$msg,$headers);
}
}
}
?>
Property changes on: trunk/kernel/include/emailmessage.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.22
\ No newline at end of property
+1.23
\ No newline at end of property
Index: trunk/kernel/include/advsearch.php
===================================================================
--- trunk/kernel/include/advsearch.php (revision 270)
+++ trunk/kernel/include/advsearch.php (revision 271)
@@ -1,198 +1,198 @@
<?php
class clsAdvancedSearchResults extends clsItemCollection
{
var $ResultTable;
var $FieldList;
var $FieldWeight;
var $WhereClauses;
var $SourceTable;
var $Relationships;
var $Ignored_Words;
var $CatClause;
var $Keywords;
var $Phrase = "";
var $SearchType;
var $RequiredRelevance;
var $PctRelevance;
var $PctPop;
var $PctRating;
function clsAdvancedSearchResults($SearchSource,$DataClass)
{
global $objConfig, $objSearchConfig;
$this->clsItemCollection();
$this->SourceTable = $SearchSource;
$this->SetResultTable($SearchSource,$DataClass);
$this->FieldList = array();
$this->Relationships = array();
$this->Ignored_Words = array();
$this->WhereClauses = array();
$this->FieldWeight = array();
$this->Keywords = GetKeywords("");
$this->SearchType = 0; //simple
$this->RequiredRelevance=0;
$this->PctRelevance = $objConfig->Get("SearchRel_DefaultKeyword")/100;
$this->PctPop = $objConfig->Get("SearchRel_DefaultPop")/100;
$this->PctRating = $objConfig->Get("SearchRel_DefaultRating")/100;
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSearchConfigList();
$objSearchConfig->Clear();
$objSearchConfig->Query_Item("SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$SearchSource' AND AdvancedSearch=1 ORDER BY DisplayOrder");
}
function SetResultTable($SearchSource,$DataClass)
{
global $objSession;
//$this->ResultTable = $objSession->GetSessionKey()."_Search";
$this->ResultTable = $objSession->GetSessionTable('Search', '');
$this->classname= $DataClass;
}
function LoadSearchResults($Start=0,$PerPage=NULL)
{
if($PerPage)
{
$limit = "LIMIT $Start,$PerPage";
}
$sql = "SELECT * FROM ".$this->ResultTable." ".$limit;
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
return $this->Query_Item($sql);
}
function SetCategoryClause($whereclause)
{
$this->CatClause=$whereclause;
}
function AddRelationship($JoinTable,$JoinExpression=NULL)
{
$this->Relationships[$JoinTable]=$JoinExpression;
}
function SetKeywords($keywords)
{
$this->Phrase=$keywords;
$this->keywords = GetKeywords($keywords);
}
function AddAdvancedField($TableName,$FieldName,$Verb,$Value,$conj)
{
global $objSearchConfig;
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSeachConfigList();
$f = GetTablePrefix().$TableName.".".$FieldName;
$FieldConfig = $objSearchConfig->GetItemByName($TableName,$FieldName);
if(is_object($FieldConfig))
{
if(strlen($FieldConfig->Get("ForeignField"))>0)
{
$parts = explode(".",$FieldConfig->Get("ForeignField"));
$Table = $parts[0];
$Table = AddTablePrefix($Table);
$Field = $parts[1];
$join = $FieldConfig->Get("JoinClause");
$join = str_replace("{ForeignTable}",$Table,$join);
$join = str_replace("{LocalTable}",AddTablePrefix($TableName),$join);
$this->AddRlationship($Table,$join);
$FieldItem["where"] = $FieldConfig->GetWhereClause($Verb,$Value);
$FieldItem["Field"] = $FieldConfig->Get("ForeignField");
$FieldItem["Table"] = "";
$FieldItem["conjuction"] = $conj;
$FieldItem["weight"] = $FieldConfig->Get("Priority");
}
else
{
$FieldItem = array();
$FieldItem["Table"] = AddTablePrefix($TableName);
$FieldItem["Field"] = $FieldName;
$FieldItem["where"] = $FieldConfig->GetWhereClause($Verb,$Value);
$FieldItem["conjuction"] = $conj;
$FieldItem["weight"] = $FieldConfig->Get("Priority");
}
$this->FieldList[] = $FieldItem;
unset($FieldItem);
}
}
/* ready to write the code to build the query and go */
function BuildWhereClause()
{
$where = "";
foreach($this->FieldList as $f)
$where .= " (".$f["where"].") ".$f["conjuction"];
$cut_length = substr($where, -2) == 'OR' ? 2 : substr($where, -3) == 'AND' ? 3 : 0;
$where = substr($where, 0, strlen($where) - $cut_length);
return $where;
}
function PerformSearch($ItemType,$OrderBy=NULL,$InitTable=FALSE, $idlist=NULL)
{
static $SelectSQL, $OldItemType;
global $objSession, $objItemTypes;
$ctype = $objItemTypes->GetItem($ItemType);
$idField = $ctype->Get("SourceTable")."Id";
$this->SourceTable = AddTablePrefix($ctype->Get("SourceTable"));
$result=0;
$PopField = $ctype->Get("PopField");
$RateField = $ctype->Get("RateField");
$typestr = str_pad($ItemType,2,"0",STR_PAD_LEFT);
$SelectSQL = "SELECT ".$this->SourceTable.".".$idField." as ItemId, ". $this->SourceTable.".Priority as Relevance, ResourceId, CONCAT($typestr) as ItemType, EditorsPick as EdPick FROM ".$this->SourceTable." ";
foreach($this->Relationships as $JoinTable=>$OnClause)
{
$SelectSQL .= "LEFT JOIN $JoinTable ON ($OnClause) ";
}
$first=1;
$WhereClause = $this->BuildWhereClause();
if(strlen($WhereClause)>0)
{
$SelectSQL .= " WHERE ".$WhereClause;
}
$SelectSQL .= " GROUP BY $idField ";
- $this->adodbConnection->Execute("DROP TABLE ".$this->ResultTable);
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$this->ResultTable);
$full_sql = "CREATE TABLE ".$this->ResultTable." ".$indexSQL.$SelectSQL;
$this->adodbConnection->Execute($full_sql);
// if advanced seaech used, then delete simple search keywords
$objSession->SetVariable('Search_Keywords', '');
//print_pre($full_sql);
}
function BuildIndexes()
{
$sql = "ALTER TABLE ".$this->ResultTable." ADD INDEX (Relevance), ";
$sql .="ADD INDEX (ItemId), ";
$sql .="ADD INDEX (ItemType), ";
$sql .=" ADD INDEX sorting (EdPick,Relevance)";
$this->adodbConnection->Execute($sql);
}
function Result_IdList()
{
/* returns an array contain a resource ID list */
$sql = "SELECT DISTINCT(ResourceId) FROM ".$this->ResultTable;
$rs = $this->adodbConnection->Execute($sql);
$result = array();
while($rs && !$rs->EOF)
{
$result[] = $rs->fields["ResourceId"];
$rs->MoveNext();
}
return $result;
}
function SetRelevence($ItemType, $IdField)
{
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/include/advsearch.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/events.php
===================================================================
--- trunk/kernel/include/events.php (revision 270)
+++ trunk/kernel/include/events.php (revision 271)
@@ -1,99 +1,99 @@
<?php
class clsEvent extends clsItemDB
{
function clsEvent($EventId = NULL)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Events";
$this->id_field = "EventId";
$this->NoResourceId=1;
$this->debuglevel=0;
if($EventId)
{
$this->LoadFromDatabase($EventId);
}
}
function LoadFromDatabase($Id)
{
global $Errors;
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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;
}
}
class clsEventList extends clsItemCollection
{
function clsEventList()
{
$this->clsItemCollection();
$this->classname="clsEvent";
$this->SourceTable = GetTablePrefix()."Events";
$this->PerPageVar = "Perpage_Events";
$this->AdminSearchFields = array("Description", "Module","Event","u.Login");
}
function CopyFromEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
if($data["EventId"]>0)
{
$c->Update();
}
$rs->MoveNext();
}
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- $this->adodbConnection->Execute("DROP TABLE $edit_table");
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function &GetEmailEventObject($EventName,$LangId=NULL)
{
global $objLanguages;
if(!$LangId)
$LangId = $objLanguages->GetPrimary();
$EmailTable = GetTablePrefix()."EmailMessage";
$EventTable = $this->SourceTable;
$sql = "SELECT * FROM $EventTable INNER JOIN $EmailTable ON ($EventTable.EventId = $EmailTable.EventId) ";
$sql .="WHERE Event='$EventName' AND LanguageId=$LangId";
$result = $this->adodbConnection->Execute($sql);
if ($result === FALSE)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"GetEmailEventObject");
return FALSE;
}
$data = $result->fields;
$e = new clsEmailMessage();
$e->SetFromArray($data);
$e->Clean();
return $e;
}
}
Property changes on: trunk/kernel/include/events.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/include/searchitems.php
===================================================================
--- trunk/kernel/include/searchitems.php (revision 270)
+++ trunk/kernel/include/searchitems.php (revision 271)
@@ -1,657 +1,657 @@
<?php
/* search string syntax:
+<word> : <word> is required
-<word> : <word> cannot exist in the searched field
"word word" : contents between the quotes are treated as a single entity
+/-"word word" is supported
ignore words are not case sensitive
*/
class clsSearchLog extends clsItemDB
{
function clsSearchLog($id=NULL)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."SearchLog";
$this->id_field = "SearchLogId";
$this->NoResourceId = 1;
if($id)
$this->LoadFromDatabase($id);
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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;
}
}
class clsSearchLogList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsSearchLogList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."SearchLog";
$this->classname = "clsSearchLog";
$this->Page=1;
$this->PerPageVar = "Perpage_SearchLog";
$this->AdminSearchFields = array("Keyword");
}
function UpdateKeyword($keyword,$SearchType)
{
$sql = "UPDATE ".$this->SourceTable." SET Indices = Indices+1 WHERE Keyword='$keyword' AND SearchType=$SearchType";
//echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
if($this->adodbConnection->Affected_Rows()==0)
{
//echo "Creating Keyword record..<br>\n";
$k = new clsSearchLog();
$k->Set("Keyword",$keyword);
$k->Set("Indices",1);
$k->Set("SearchType",$SearchType);
$k->Create();
}
}
function AddKeywords($Keywords)
{
if(is_array($Keywords))
{
for($i=0;$i<count($Keywords);$i++)
{
$this->UpdateKeyword($Keywords[$i]);
}
}
else
$this->UpdateKeyword($Keywords);
}
}
class clsSearchResults extends clsItemCollection
{
var $ResultTable;
var $FieldList;
var $FieldWeight;
var $WhereClauses;
var $SourceTable;
var $Relationships;
var $Ignored_Words;
var $CatClause;
var $Keywords;
var $Phrase = "";
var $SearchType;
var $RequiredRelevance;
var $PctRelevance;
var $PctPop;
var $PctRating;
function clsSearchResults($SearchSource,$DataClass)
{
global $objConfig;
$this->clsItemCollection();
$this->SourceTable = $SearchSource;
$this->SetResultTable($SearchSource,$DataClass);
$this->FieldList = array();
$this->Relationships = array();
$this->Ignored_Words = array();
$this->WhereClauses = array();
$this->FieldWeight = array();
$this->Keywords = GetKeywords("");
$this->SearchType = 0; //simple
$this->RequiredRelevance=0;
$this->PctRelevance = $objConfig->Get("SearchRel_DefaultKeyword")/100;
$this->PctPop = $objConfig->Get("SearchRel_DefaultPop")/100;
$this->PctRating = $objConfig->Get("SearchRel_DefaultRating")/100;
}
function SetResultTable($SearchSource,$DataClass)
{
global $objSession;
$this->ResultTable = $objSession->GetSearchTable();
$this->classname= $DataClass;
}
function LoadSearchResults($Start=0,$PerPage=NULL)
{
if($PerPage)
{
$limit = "LIMIT $Start,$PerPage";
}
$sql = "SELECT * FROM ".$this->ResultTable." ".$limit;
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
return $this->Query_Item($sql);
}
function SetCategoryClause($whereclause)
{
$this->CatClause=$whereclause;
}
function AddRelationship($JoinTable,$JoinExpression=NULL)
{
$this->Relationships[$JoinTable]=$JoinExpression;
}
function SetKeywords($keywords)
{
$this->Phrase=$keywords;
$this->keywords = GetKeywords($keywords);
}
function AddSimpleCustomFields()
{
$sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId>0";
//echo $sql;
foreach($this->Relationships as $Table=>$clause)
{
if(strlen($Table)>0 && $Table != "Category")
$sql .= " OR TableName='".$Table."'";
}
$ctable = GetTablePrefix()."CustomMetaData";
$rs = $this->adodbConnection->Execute($sql);
$CustomJoined = FALSE;
while($rs && !$rs->EOF)
{
$x = $rs->fields["CustomFieldId"];
$t = $ctable." as c".$x;
$join = "(c$x.ResourceId=".GetTablePrefix().$this->SourceTable.".ResourceId AND c$x.CustomFieldId=".$rs->fields["CustomFieldId"].")";
$this->AddRelationship($t,$join);
$f = "c".$x.".Value ";
$this->FieldList[] = $f;
$this->FieldWeight[$f] = $rs->fields["Priority"];
$rs->MoveNext();
}
}
function AddSimpleFields()
{
$sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId=0";
//echo $sql;
foreach($this->Relationships as $Table=>$clause)
{
if(strlen($Table)>0 && $Table != "Category")
$sql .= " OR TableName='".$Table."'";
}
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$f = GetTablePrefix().$rs->fields["TableName"].".".$rs->fields["FieldName"];
$this->FieldList[] = $f;
$this->FieldWeight[$f] = $rs->fields["Priority"];
$rs->MoveNext();
}
$this->AddSimpleCustomFields();
}
function AddSearchWhereClause($FieldName)
{
$req_where = "";
/* build required keywords string */
if(count($this->keywords["required"])>0)
{
$required = $this->keywords["required"];
for($i=0;$i<count($required);$i++)
{
if(strlen($required[$i])>0)
{
if($i>0)
{
$or =" AND ";
}
else
$or = "";
$w .= $or." ".$FieldName." LIKE '%".$required[$i]."%'";
}
}
if(strlen($w)>0)
{
$req_where = "(". $w.")";
}
else
$req_where = "";
}
$w = "";
$not_where="";
if(count($this->keywords["notallowed"])>0)
{
$words = $this->keywords["notallowed"];
for($i=0;$i<count($words);$i++)
{
if(strlen($words[$i])>0)
{
if($i>0)
{
$or =" AND ";
}
else
$or = "";
$w .= $or." ".$FieldName." NOT LIKE '%".$words[$i]."%'";
}
}
if(strlen($w)>0)
{
$not_where = "(".$w.")";
}
else
$not_where = "";
}
$w="";
$normal = $this->keywords["normal"];
if(count($normal)>0)
{
for($i=0;$i<count($normal);$i++)
{
if (strlen($normal[$i])>0)
{
if($i>0)
{
$or =" OR ";
}
else
$or = "";
$w .= "$or $FieldName LIKE '%".$normal[$i]."%'";
}
}
if(count($required)>0)
$w .= " OR ";
for($i=0;$i<count($required);$i++)
{
if(strlen($required[$i])>0)
{
if($i>0)
{
$or = " OR ";
}
else
$or="";
$w .= "$or $FieldName LIKE '%".$required[$i]."%'";
}
}
if(strlen($w)>0)
{
$where = "(".$w.")";
}
else
$where = "";
}
$complete= BuildWhereClause($where,$req_where,$not_where);
$this->WhereClauses[$FieldName]="(".$complete.")";
$this->Ignored_Words=$this->keywords["ignored"];
}
function PerformSearch($ItemType,$OrderBy=NULL,$InitTable=FALSE, $idlist=NULL)
{
static $SelectSQL, $OldItemType;
global $objSession, $objItemTypes;
//echo "perfirming Simple Search<br>";
//echo "Old Item Type: $OldItemType New: $ItemType <br>\n";
if($ItemType != $OldItemType)
$SelectSQL = "";
$OldItemType = $ItemType;
$ctype = $objItemTypes->GetItem($ItemType);
$idField = $ctype->Get("SourceTable")."Id";
$this->SourceTable = GetTablePrefix().$ctype->Get("SourceTable");
$result=0;
$PopField = $ctype->Get("PopField");
$RateField = $ctype->Get("RateField");
//print_pre($this->keywords);
if(!strlen($SelectSQL))
{
$typestr = str_pad($ItemType,2,"0",STR_PAD_LEFT);
$SelectSQL = "SELECT ";
$ifs = array();
$weightsum = 0;
foreach($this->FieldWeight as $w)
$weightsum += $w;
$wordcount = count($this->keywords["normal"])+count($this->keywords["required"]);
$single = ($wordcount == 1);
foreach($this->FieldList as $f)
{
$weight = (int)$this->FieldWeight[$f];
$s = array();
if(!$single)
{
$full = trim(implode(" ",$this->keywords["normal"]));
$s[] = " (IF ($f LIKE '%$full%', ".$weightsum.", 0))";
}
foreach($this->keywords["normal"] as $k)
{
if($k != $full || $single)
{
$temp = " (IF ($f LIKE '%$k%', ".$weight.", 0))";
$s[] = $temp;
}
}
foreach($this->keywords["required"] as $k)
{
if($this->RequiredRelevance>0)
$weight = $this->FieldWeight[$f] + ($this->FieldWeight[$f]*($this->RequiredRelevance/100));
if($k != $full || $single)
{
$s[] = " (IF ($f LIKE '%$k%', ".$weight.", 0))";
}
}
// echo "<PRE>";print_r($s); echo "</PRE>";
$txt = implode("+",$s);
//echo $txt."<br>\n";
$ifs[] = $txt;
unset($s);
}
// echo "<PRE>";print_r($ifs); echo "</PRE>";
/* add relevance formula for weighting hits & popularity */
if($weightsum==0)
$weightsum=1;
if(strlen($PopField)>0 && $this->PctPop>0)
{
$popcalc = " + ((($PopField + 1) / (max($PopField)+1)*".$this->PctPop."))";
}
else
$popcalc = "";
if(strlen($RateField)>0 && $this->PctRating>0)
{
$ratecalc = " + ((($RateField + 1) / (max($RateField)+1)*".$this->PctRating."))";
}
else
$ratecalc = "";
if($this->PctRelevance>0)
{
$relcalc = "(((".implode("+",$ifs).")/$weightsum)*".$this->PctRelevance.")";
}
else
$relcalc = "0";
$SelectSQL .= $relcalc.$popcalc.$ratecalc." as Relevance, ";
$SelectSQL .= $this->SourceTable.".".$idField." as ItemId, ".$this->SourceTable.".ResourceId as ResourceId, CONCAT($typestr) as ItemType, EditorsPick as EdPick FROM ".$this->SourceTable." ";
foreach($this->Relationships as $JoinTable=>$OnClause)
{
$SelectSQL .= "LEFT JOIN $JoinTable ON $OnClause ";
}
$first=1;
$where=0;
foreach($this->FieldList as $field)
{
if(strpos($field,"as")>0)
{
$fparts = explode("as",$field,2);
$f = $fparts[1];
$this->AddSearchWhereClause($field);
}
else {
$this->AddSearchWhereClause($field);
}
}
$SelectSQL .= " WHERE ";
$SelectSQL .= implode(" or ",$this->WhereClauses);
if(is_array($idlist))
{
$SelectSQL .= " AND (ResourceId IN (".implode(",",$idlist)."))";
}
}
$SelectSQL .= "GROUP BY $idField ";
//echo $SelectSQL."<br><br>\n";
if($InitTable)
{
- $this->adodbConnection->Execute("DROP TABLE ".$this->ResultTable);
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$this->ResultTable);
//$indexSQL = "(INDEX(Relevance), INDEX(ItemId), INDEX(ItemType), INDEX sorting (EdPick,Relevance)) ";
$full_sql = "CREATE TABLE ".$this->ResultTable." ".$indexSQL.$SelectSQL;
//echo $full_sql."<br>\n";
$this->adodbConnection->Execute($full_sql);
//echo $this->adodbConnection->ErrorMsg()."<br>\n";
$objSession->SetVariable("Search_Keywords",$this->Phrase);
}
else
{
$full_sql = "INSERT INTO ".$this->ResultTable." (Relevance,ItemId,ResourceId,ItemType,EdPick) ".$SelectSQL;
//echo "[<b>".htmlspecialchars($full_sql)."</b>]<br>\n";
$this->adodbConnection->Execute($full_sql);
//echo $this->adodbConnection->ErrorMsg()."<br>\n";
}
//Here we need to remove found items which was found by HTML tags matching keywords
//$this->adodbConnection->Execute("DELETE FROM ".$this->ResultTable." WHERE ItemId = 13 AND ItemType = 4");
}
function BuildIndexes()
{
$sql = "ALTER TABLE ".$this->ResultTable." ADD INDEX (Relevance), ";
$sql .="ADD INDEX (ItemId), ";
$sql .="ADD INDEX (ItemType), ";
$sql .=" ADD INDEX sorting (EdPick,Relevance)";
//echo $sql;
$this->adodbConnection->Execute($sql);
}
function Result_IdList()
{
/* returns an array contain a resource ID list */
$sql = "SELECT DISTINCT(ResourceId) FROM ".$this->ResultTable;
$rs = $this->adodbConnection->Execute($sql);
$result = array();
while($rs && !$rs->EOF)
{
$result[] = $rs->fields["ResourceId"];
$rs->MoveNext();
}
return $result;
}
}
function count_words($string)
{
// below line added to make contiguous spaces count as one space
if(strlen($string))
{
$string = eregi_replace(" +", " ", $string);
return substr_count($string," ")+1;
}
else
return 0;
}
function GetKeywords($phrase)
{
global $KeywordIgnore;
if(count($KeywordIgnore)==0)
GetIgnoreList();
$keywords["normal"]= array();
$keywords["required"]= array();
$keywords["notallowed"] = array();
$keywords["ignored"] = array();
if(!strlen($phrase))
return $keywords;
$w_array = array();
$phrase=trim($phrase);
//if(count_words($phrase)>1)
// $keywords["normal"][] = $phrase;
$t_len = strlen($phrase);
$ce=0;
for ($i=0; $i<$t_len; $i++)
{ #search for next special tag
switch ($phrase[$i])
{
case "\"":
$exact_match_close = strpos($phrase,"\"", $i+1);
if(!$exact_match_close)
break;
$exact_word=substr($phrase, $i+1, ($exact_match_close-$i)-1);
$i=$exact_match_close;
if($exact_word)
{
if(strlen($token)==0)
$token="|";
$w_array[$ce]=$token.addslashes($exact_word);
$token="";
$ce++;
$exact_word="";
}
break;
case "+":
if(strlen($exact_word)==0)
{
$token = "+";
}
else
$exact_word .= "+";
break;
case "-":
if(strlen($exact_word)==0)
{
$token = "-";
}
else
$exact_word .="-";
break;
case " ":
case ",":
if($exact_word)
{
if(strlen($token)==0)
$token="|";
if($token=="|")
{
if($KeywordIgnore[strtolower($exact_word)]==1)
{
$w_array[$ce]= "=".addslashes($exact_word);
$ce++;
}
else
{
$w_array[$ce]=$token.addslashes($exact_word);
$ce++;
}
}
else
{
$w_array[$ce]=$token.addslashes($exact_word);
$ce++;
}
$token="";
$exact_word="";
}
break;
default:
$exact_word.=$phrase[$i];
}
}
if($exact_word)
{
if(strlen($token)==0)
$token="|";
if($KeywordIgnore[strtolower($exact_word)]==1 && ($token =="|" || $token=="="))
{
$w_array[$ce]= "=".addslashes($exact_word);
$ce++;
}
else
{
$w_array[$ce]=$token.addslashes($exact_word);
$ce++;
}
}
for ($i=0;$i<count($w_array);$i++)
{
$keyword = $w_array[$i];
switch(substr($keyword,0,1))
{
case "|":
$keywords["normal"][]=substr($keyword,1);
break;
case "+":
$keywords["required"][] = substr($keyword,1);
break;
case "-":
$keywords["notallowed"][] = substr($keyword,1);
break;
case "=":
$keywords["ignored"][] = substr($keyword,1);
break;
}
}
return($keywords);
}
function BuildWhereClause($normal,$required,$notallowed)
{
$return="";
$return = $required;
if(strlen($return)>0 && strlen($notallowed)>0)
{
$return .= " AND ";
}
$return .= $notallowed;
if(strlen($return)>0 && strlen($normal)>0)
{
$return .= " AND ";
}
$return .= $normal;
return $return;
}
function GetIgnoreList()
{
global $KeywordIgnore;
$adodbConnection = GetADODBConnection();
$rs = $adodbConnection->Execute("SELECT * FROM IgnoreKeywords");
while($rs && !$rs->EOF)
{
$KeywordIgnore[strtolower($rs->fields["keyword"])]=1;
$rs->MoveNext();
}
// foreach($KeywordIgnore as $word=>$dummy)
// echo $word.",";
// echo "<br>\n";
}
?>
Property changes on: trunk/kernel/include/searchitems.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/modules.php
===================================================================
--- trunk/kernel/include/modules.php (revision 270)
+++ trunk/kernel/include/modules.php (revision 271)
@@ -1,902 +1,902 @@
<?php
/* List of installed modules and module-specific variables
Copyright 2002, Intechnic Corporation, All rights reserved
*/
setcookie("CookiesTest", "1");
$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 = $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");
while($key = key($vars))
{
$key = "g_".$key;
global $$key;
$$key = current($vars); //variable variables
if(strlen($$key)>80)
{
$lic = base64_decode($$key);
}
next($vars);
}
//$lic = base64_decode($g_License);
_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['SERVER_NAME'].$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(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 = $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->Delete();
}
if( !isset($SearchPerformed) ) $SearchPerformed = false;
if($SearchPerformed == true) $objSearch->BuildIndexes();
LogEntry("Finished Loading Module action scripts\n");
?>
Property changes on: trunk/kernel/include/modules.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/kernel/include/custommetadata.php
===================================================================
--- trunk/kernel/include/custommetadata.php (revision 270)
+++ trunk/kernel/include/custommetadata.php (revision 271)
@@ -1,272 +1,272 @@
<?php
class clsCustomMetaData extends clsItem
{
// var $m_CustomDataId;
// var $m_ResourceId;
// var $m_CustomFieldId;
// var $m_Value;
var $FieldName;
function clsCustomMetaData($CustomDataId=-1,$table="CustomMetaData")
{
$this->clsItem();
$this->tablename=GetTablePrefix()."CustomMetaData";
$this->type=12;
$this->BasePermission="";
$this->id_field = "CustomDataId";
$this->NoResourceId=1; //set this to avoid using a resource ID
if(isset($CustomDataId))
$this->LoadFromDatabase($CustomDataId);
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!strlen($this->Get("ResourceId")))
{
$Errors->AddError("error.fieldIsRequired",'ResourceId',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function SetFieldName($name)
{
$this->FieldName = $name;
}
function GetFieldName()
{
return $this->FieldName;
}
function Save()
{
if(is_numeric($this->Get("CustomDataId")))
{
$this->Update();
}
else
$this->Create();
}
/*
function LoadFromDatabase($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId = '%s'",$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;
}
*/
} /*clsCustomMetaData*/
class clsCustomDataList extends clsItemCollection
{
function clsCustomDataList($table="")
{
$this->clsItemCollection();
$this->classname = "clsCustomMetaData";
if(!strlen($table))
$table = GetTablePrefix()."CustomMetaData";
$this->SetTable('live', $table);
}
function LoadResource($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$this->Query_Item($sql);
return $this->Items;
}
function DeleteResource($ResourceId)
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceID=".$ResourceId;
$this->adodbConnection->Execute($ResourceId);
}
function &SetFieldValue($FieldId,$ResourceId,$Value)
{
// so strange construction used, because in normal
// way it doesn't work at all (gets item copy not
// pointer)
$index = $this->GetDataItem($FieldId, true);
if($index !== false)
$d =& $this->Items[$index];
else
$d = null;
if(is_object($d))
{
$d->Set("Value",$Value);
if(!strlen($Value))
{
for($x=0;$x<count($this->Items);$x++)
{
if($this->Items[$x]->Get("CustomFieldId")==$FieldId &&
$this->Items[$x]->Get("ResourceId")==$ResourceId)
{
$this->Items[$x]->Set("CustomFieldId",0);
break;
}
}
$d->Delete();
}
}
else
{
if(strlen($Value)>0)
{
$d = new clsCustomMetaData();
$d->Set("CustomFieldId",$FieldId);
$d->Set("ResourceId",$ResourceId);
$d->Set("Value",$Value);
array_push($this->Items,$d);
}
}
return $d;
}
function &GetDataItem($id, $return_index = false)
{
// $id - custom field id to find
// $return_index - return index to items, not her.
$found = false;
$index = false;
for($i = 0; $i < $this->NumItems(); $i++)
{
$d =& $this->GetItemRefByIndex($i);
if($d->Get("CustomFieldId")==$id)
{
$found=TRUE;
break;
}
}
return $found ? ($return_index ? $i : $d) : false;
}
function SaveData()
{
foreach($this->Items as $f)
{
$FieldId = $f->Get("CustomFieldId");
$value = $f->Get("Value");
$ResId = $f->Get("ResourceId");
$DataId = $f->Get("CustomDataId");
if(is_numeric($DataId))
{
$sql = "UPDATE ".$this->SourceTable." SET Value='".$value."' WHERE CustomFieldId='$FieldId' AND ResourceId='$ResId'";
$this->adodbConnection->Execute($sql);
}
else
{
if($FieldId>0)
{
$sql = "INSERT INTO ".$this->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$ResId."','$FieldId','$value')";
$this->adodbConnection->Execute($sql);
}
}
}
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CustomDataId=0 ");
while($rs && !$rs->EOF)
{
$m = $this->adodbConnection->Execute("SELECT MIN(CustomDataId) as MinValue FROM ".$this->SourceTable);
$NewId = $m->fields["MinValue"]-1;
$sql = "UPDATE ".$this->SourceTable." SET CustomDataId=$NewId WHERE ResourceId=".$rs->fields["ResourceId"]." AND ";
$sql .= "CustomFieldId=".$rs->fields["CustomFieldId"];
$this->adodbConnection->Execute($sql);
$rs->MoveNext();
}
}
function CopyToEditTable($idfield, $idlist)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
if(is_array($idlist))
{
$list = implode(",",$idlist);
}
else
$list = $idlist;
$query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if((int)$GLOBALS["debuglevel"])
echo $insert;
$this->adodbConnection->Execute($insert);
$this->SourceTable = $edit_table;
$this->SaveData();
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
//$this->adodbConnection->Execute($sql);
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
if(strlen($data["Value"])>0)
{
$c->Dirty();
if($data["CustomDataId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("CustomDataId");
}
else
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE ResourceId=".$data["ResourceId"]." AND CustomFieldId=".$data["CustomFieldId"];
//echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
$rs->MoveNext();
}
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
} /* clsCustomDataList */
?>
Property changes on: trunk/kernel/include/custommetadata.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/category.php
===================================================================
--- trunk/kernel/include/category.php (revision 270)
+++ trunk/kernel/include/category.php (revision 271)
@@ -1,2280 +1,2280 @@
<?php
define('TYPE_CATEGORY', 0);
$DownloadId=0;
RegisterPrefix("clsCategory","cat","kernel/include/category.php");
class clsCategory extends clsItem
{
var $Permissions;
function clsCategory($CategoryId=NULL)
{
global $objSession;
$this->clsItem(TRUE);
//$this->adodbConnection = GetADODBConnection();
$this->tablename = GetTablePrefix()."Category";
$this->type=1;
$this->BasePermission ="CATEGORY";
$this->id_field = "CategoryId";
$this->TagPrefix = "cat";
$this->debuglevel=0;
/* keyword highlighting */
$this->OpenTagVar = "Category_Highlight_OpenTag";
$this->CloseTagVar = "Category_Highlight_CloseTag";
if($CategoryId!=NULL)
{
$this->LoadFromDatabase($CategoryId);
$this->Permissions = new clsPermList($CategoryId,$objSession->Get("GroupId"));
}
else
{
$this->Permissions = new clsPermList();
}
}
function ClearCacheData()
{
$env = "':m".$this->Get("CategoryId")."%'";
DeleteTagCache("m_itemcount","Category%");
DeleteTagCache("m_list_cats","",$env);
}
function Delete()
{
global $CatDeleteList;
if(!is_array($CatDeleteList))
$CatDeleteList = array();
if($this->UsingTempTable()==FALSE)
{
$this->Permissions->Delete_CatPerms($this->Get("CategoryId"));
$sql = "DELETE FROM ".GetTablePrefix()."CountCache WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->Execute($sql);
$CatDeleteList[] = $this->Get("CategoryId");
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DELETE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DELETE");
parent::Delete();
$this->ClearCacheData();
}
else
{
parent::Delete();
}
}
function Update($UpdatedBy=NULL)
{
parent::Update($UpdatedBy);
if($this->tablename==GetTablePrefix()."Category")
$this->ClearCacheData();
}
function Create()
{
if((int)$this->Get("CreatedOn")==0)
$this->Set("CreatedOn",date("U"));
parent::Create();
if($this->tablename==GetTablePrefix()."Category")
$this->ClearCacheData();
}
function SetParentId($value)
{
//Before we set a parent verify that propsed parent is not our child.
//Otherwise it will cause recursion.
$id = $this->Get("CategoryId");
$path = $this->Get("ParentPath");
$sql = sprintf("SELECT CategoryId From ".GetTablePrefix()."Category WHERE ParentPath LIKE '$path%' AND CategoryId = %d ORDER BY ParentPath",$value);
$rs = $this->adodbConnection->SelectLimit($sql,1,0);
if(!$rs->EOF)
{
return;
}
$this->Set("ParentId",$value);
}
function Approve()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.APPROVE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.APPROVE");
$this->Set("Status", 1);
$this->Update();
}
function Deny()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DENY",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DENY");
$this->Set("Status", 0);
$this->Update();
}
function IsEditorsPick()
{
return $this->Is("EditorsPick");
}
function SetEditorsPick($value)
{
$this->Set("EditorsPick", $value);
}
function GetSubCats($limit=NULL, $target_template=NULL, $separator=NULL, $anchor=NULL, $ending=NULL, $class=NULL)
{
global $m_var_list, $m_var_list_update, $var_list, $var_list_update;
$sql = "SELECT CategoryId, Name from ".GetTablePrefix()."Category where ParentId=".$this->Get("CategoryId")." AND Status=1 ORDER BY Priority";
if(isset($limit))
{
$rs = $this->adodbConnection->SelectLimit($sql, $limit, 0);
}
else
{
$rs = $this->adodbConnection->Execute($sql);
}
$count=1;
$class_name = is_null($class)? "catsub" : $class;
while($rs && !$rs->EOF)
{
if(!is_null($target_template))
{
$var_list_update["t"] = $target_template;
}
$m_var_list_update["cat"] = $rs->fields["CategoryId"];
$m_var_list_update["p"] = "1";
$cat_name = $rs->fields['Name'];
if (!is_null($anchor))
$ret .= "<a class=\"$class_name\" href=\"".GetIndexURL()."?env=" . BuildEnv() . "\">$cat_name</a>";
else
$ret .= "<span=\"$class_name\">$cat_name</span>";
$rs->MoveNext();
if(!$rs->EOF)
{
$ret.= is_null($separator)? ", " : $separator;
}
}
if(strlen($ret))
$ret .= is_null($ending)? " ..." : $ending;
unset($var_list_update["t"], $m_var_list_update["cat"], $m_var_list_update["p"]);
return $ret;
}
function Validate()
{
global $objSession;
$dataValid = true;
if(!isset($this->m_Type))
{
$Errors->AddError("error.fieldIsRequired",'Type',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Name))
{
$Errors->AddError("error.fieldIsRequired",'Name',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Description))
{
$Errors->AddError("error.fieldIsRequired",'Description',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Visible))
{
$Errors->AddError("error.fieldIsRequired",'Visible',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_CreatedById))
{
$Errors->AddError("error.fieldIsRequired",'CreatedBy',"","","clsCategory","Validate");
$dataValid = false;
}
return $dataValid;
}
function UpdateCachedPath()
{
if($this->UsingTempTable()==TRUE)
return;
$Id = $this->Get("CategoryId");
$Id2 = $Id;
$NavPath = "";
$path = array();
do
{
$rs = $this->adodbConnection->Execute("SELECT ParentId,Name from ".$this->tablename." where CategoryId='$Id2'");
$path[] = $Id2;
$nav[] = $rs->fields["Name"];
if ($rs && !$rs->EOF)
{
//echo $path;
$Id2 = $rs->fields["ParentId"];
}
else
$Id2="0"; //to prevent infinite loop
} while ($Id2 != "0");
$parentpath = "|".implode("|",array_reverse($path))."|";
$NavBar = implode(">",array_reverse($nav));
//echo "<BR>\n";
//$rs = $this->adodbConnection->Execute("update Category set ParentPath='$path' where CategoryId='$Id'");
if($this->Get("ParentPath")!=$parentpath || $this->Get("CachedNavbar")!=$NavBar)
{
$this->Set("ParentPath",$parentpath);
$this->Set("CachedNavbar",$NavBar);
$this->Update();
}
}
function GetCachedNavBar()
{
$res = $this->Get("CachedNavbar");
if(!strlen($res))
{
$this->UpdateCachedPath();
$res = $this->Get("CachedNavbar");
}
return $res;
}
function Increment_Count()
{
$this->Increment("CachedDescendantCatsQty");
}
function Decrement_Count()
{
$this->Decrement("CachedDescendantCatsQty");
$this->Update();
}
function LoadFromDatabase($Id)
{
global $objSession, $Errors, $objConfig;
if($Id==0)
return FALSE;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE CategoryId = '%s'",$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;
if(is_array($data))
{
$this->SetFromArray($data);
$this->Clean();
}
else
return false;
return true;
}
function SetNewItem()
{
global $objConfig;
$value = $this->Get("CreatedOn");
$cutoff = adodb_date("U") - ($objConfig->Get("Category_DaysNew") * 86400);
$this->IsNew = FALSE;
if($value>$cutoff)
$this->IsNew = TRUE;
return $this->IsNew;
}
function LoadFromResourceId($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResourceId");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResourceId");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
else
return false;
return true;
}
function GetParentField($fieldname,$skipvalue,$default)
{
/* this function moves up the category tree until a value for $field other than
$skipvalue is returned. if no matches are made, then $default is returned */
$path = $this->Get("ParentPath");
$path = substr($path,1,-1); //strip off the first & last tokens
$aPath = explode("|",$path);
$aPath = array_slice($aPath,0,-1);
$ParentPath = implode("|",$aPath);
$sql = "SELECT $fieldname FROM category WHERE $fieldname != '$skipvalue' AND ParentPath LIKE '$ParentPath' ORDER BY ParentPath DESC";
$rs = $this->adodbConnection->execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields[$fieldname];
}
else
$ret = $default;
$update = "UPDATE ".$this->SourceTable." SET $fieldname='$ret' WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->execute($update);
return $ret;
}
function GetCustomField($fieldName)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Get field is required in order to set custom field values","","",get_class($this),"GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_CategoryId,"category",$fieldName);
}
function SetCustomField($fieldName, $value)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Set field is required in order to set custom field values","","",get_class($this),"SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_CategoryId,"category",$fieldName,$value);
}
function LoadPermissions($first=1)
{
/* load all permissions for group on this category */
$this->Permissions->CatId=$this->Get("CategoryId");
if($this->Permissions->NumItems()==0)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
}
}
}
if($this->Permissions->NumItems()==0)
{
if($first==1)
{
$this->Permissions->GroupId=NULL;
$this->LoadPermissions(0);
}
}
}
function PermissionObject()
{
return $this->Permissions;
}
function PermissionItemObject($PermissionName)
{
$p = $this->Permissions->GetPermByName($PermissionName);
return $p;
}
function HasPermission($PermissionName,$GroupID)
{
global $objSession;
$perm = $this->PermissionValue($PermissionName,$GroupID);
// echo "Permission $PermissionName for $GroupID is $perm in ".$this->Get("CategoryId")."<br>\n";
if(!$perm)
{
$perm=$objSession->HasSystemPermission("ROOT");
}
return ($perm==1);
}
function PermissionValue($PermissionName,$GroupID)
{
//$this->LoadPermissions();
$ret=NULL;
//echo "Looping though ".count($this->Permissions)." permissions Looking for $PermissionName of $GroupID<br>\n";
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
$this->Permissions->CatId=$this->Get("CategoryId");
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if($ret == NULL)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if(is_numeric($ret))
break;
}
}
}
return $ret;
}
function SetPermission($PermName,$GroupID,$Value,$Type=0)
{
global $objSession, $objPermissions, $objGroups;
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
if($objSession->HasSystemPermission("GRANT"))
{
$current = $this->PermissionValue($PermName,$GroupID);
if($current == NULL)
{
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
else
{
$p = $this->Permissions->GetPermByName($PermName);
if($p->Inherited==FALSE)
{
$p->Set("PermissionValue",$Value);
$p->Update();
}
else
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
if($PermName == "CATEGORY.VIEW")
{
$Groups = $objGroups->GetAllGroupList();
$ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$Groups);
$this->SetViewPerms("CATEGORY.VIEW",$ViewList,$Groups);
$this->Update();
}
}
}
function SetViewPerms($PermName,$acl,$allgroups)
{
global $objPermCache;
$dacl = array();
if(!is_array($allgroups))
{
global $objGroups;
$allgroups = $objGroups->GetAllGroupList();
}
for($i=0;$i<count($allgroups);$i++)
{
$g = $allgroups[$i];
if(!in_array($g,$acl))
$dacl[] = $g;
}
if(count($acl)<count($dacl))
{
$aval = implode(",",$acl);
$dval = "";
}
else
{
$dval = implode(",",$dacl);
$aval = "";
}
if(strlen($aval)==0 && strlen($dval)==0)
{
$aval = implode(",",$allgroups);
}
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if(is_object($pc))
{
$pc->Set("ACL",$aval);
$pc->Set("DACL",$dval);
$pc->Update();
}
else
$objPermCache->AddPermCache($this->Get("CategoryId"),$PermId,$aval,$dval);
//$this->Update();
}
function GetACL($PermName)
{
global $objPermCache;
$ret = "";
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if(is_object($pc))
{
$ret = $this->Get("ACL");
}
return $ret;
}
function UpdateACL()
{
global $objGroups, $objPermCache;
$glist = $objGroups->GetAllGroupList();
$ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$glist);
$perms = $this->Permissions->GetAllViewPermGroups($this,$glist);
//echo "<PRE>";print_r($perms); echo "</PRE>";
foreach($perms as $PermName => $l)
{
$this->SetViewPerms($PermName,$l,$glist);
}
}
function Cat_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function Parent_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function Admin_Parent_Link($page=NULL)
{
global $m_var_list_update;
if(!strlen($page))
$page = $_SERVER["PHP_SELF"];
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = $page."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function StatusIcon()
{
global $imagesURL;
$ret = $imagesURL."/itemicons/";
switch($this->Get("Status"))
{
case STATUS_DISABLED:
$ret .= "icon16_cat_disabled.gif";
break;
case STATUS_PENDING:
$ret .= "icon16_cat_pending.gif";
break;
case STATUS_ACTIVE:
$img = "icon16_cat.gif";
if($this->IsPopItem())
$img = "icon16_cat_pop.gif";
if($this->IsHotItem())
$img = "icon16_cat_hot.gif";
if($this->IsNewItem())
$img = "icon16_cat_new.gif";
if($this->Is("EditorsPick"))
$img = "icon16_car_pick.gif";
$ret .= $img;
break;
}
return $ret;
}
function SubCatCount()
{
$ret = $this->Get("CachedDescendantCatsQty");
$sql = "SELECT COUNT(*) as SubCount FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$val = $rs->fields["SubCount"];
if($val != $this->Get("CachedDescendantCatsQty"))
{
$this->Set("CachedDescendantCatsQty",$val);
$this->Update();
}
$ret = $this->Get("CachedDescendantCatsQty");
}
return $ret;
}
function GetSubCatIds()
{
$sql = "SELECT CategoryId FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["CategoryId"];
$rs->MoveNext();
}
return $ret;
}
function GetParentIds()
{
$Parents = array();
$ParentPath = $this->Get("ParentPath");
if(strlen($ParentPath))
{
$ParentPath = substr($ParentPath,1,-1);
$Parents = explode("|",$ParentPath);
}
return $Parents;
}
function ItemCount($ItemType="")
{
global $objItemTypes,$objCatList,$objCountCache;
if(!is_numeric($ItemType))
{
$TypeId = $objItemTypes->GetItemTypeValue($ItemType);
}
else
$TypeId = (int)$ItemType;
//$path = $this->Get("ParentPath");
//$path = substr($path,1,-1);
//$path = str_replace("|",",",$path);
$path = implode(",",$this->GetSubCatIds());
if(strlen($path))
{
$path = $this->Get("CategoryId").",".$path;
}
else
$path = $this->Get("CategoryId");
$res = TableCount(GetTablePrefix()."CategoryItems","CategoryId IN ($path)",FALSE);
return $res;
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $var_list, $var_list_update, $m_var_list_update, $objItemTypes,$objCountCache;
$extra_attribs = ExtraAttributes($element->attributes);
//print_r($element);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower( $element->GetAttributeByName('_field') );
switch($field)
{
case "name":
/*
@field:cat.name
@description:Category name
*/
$ret = $this->HighlightField("Name");
break;
case "description":
/*
@field:cat.description
@description:Category Description
*/
$ret = inp_unescape($this->Get("Description"));
$ret = $this->HighlightText($ret);
break;
case "cachednavbar":
/*
@field:cat.cachednavbar
@description: Category cached navbar
*/
$ret = $this->HighlightField("CachedNavbar");
if(!strlen($ret))
{
$this->UpdateCachedPath();
$ret = $this->HighlightField("CachedNavbar");
}
break;
case "image":
/*
@field:cat.image
@description:Return an image associated with the category
@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->GetAttributeByName('_primary');
$name = $element->GetAttributeByName('_name');
if(strlen($name))
{
$img = $this->GetImageByName($name);
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if($img)
{
if( $element->GetAttributeByName('_thumbnail') )
{
$url = $img->parsetag("thumb_url");
}
else
$url = $img->parsetag("image_url");
}
else
{
$url = $element->GetAttributeByName('_defaulturl');
}
if( $element->GetAttributeByName('_imagetag') )
{
if(strlen($url))
{
$ret = "<IMG src=\"$url\" $extra_attribs >";
}
else
$ret = "";
}
else
$ret = $url;
break;
case "createdby":
/*
@field:cat.createdby
@description:parse a user field of the user that created the category
@attrib:_usertag::User field to return (defaults to login ID)
*/
$field = $element->GetAttributeByName('_usertag');
if(!strlen($field))
{
$field = "user_login";
}
$u = $objUsers->GetUser($this->Get("CreatedById"));
$ret = $u->parsetag($field);
break;
case "custom":
/*
@field:cat.custom
@description:Returns a custom field
@attrib:_customfield::field name to return
@attrib:_default::default value
*/
$field = $element->GetAttributeByName('_customfield');
$default = $element->GetAttributeByName('_default');
$ret = $this->GetCustomFieldValue($field,$default);
break;
case "catsubcats":
/*
@field:cat.catsubcats
@description:Returns a list of subcats of current category
@attrib:_limit:int:Number of categories to return
@attrib:_separator::Separator between categories
@attrib:_anchor:bool:Make an anchor (only if template is not specified)
@attrib:_TargetTemplate:tpl:Target template
@attrib:_Ending::Add special text at the end of subcategory list
@attrib:_Class::Specify stly sheet class for anchors (if used) or "span" object
*/
$limit = ((int)$element->attributes["_limit"]>0)? $element->attributes["_limit"] : NULL;
$separator = $element->attributes["_separator"];
$anchor = (int)($element->attributes["_anchor"])? 1 : NULL;
$template = strlen($element->attributes["_TargetTemplate"])? $element->attributes["_TargetTemplate"] : NULL;
$ending = strlen($element->attributes["_ending"])? $element->attributes["_ending"] : NULL;
$class = strlen($element->attributes["_class"])? $element->attributes["_class"] : NULL;
$ret = $this->GetSubCats($limit, $template, $separator, $anchor, $ending, $class);
break;
case "date":
/*
@field:cat.date
@description:Returns the date/time the category 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->GetAttributeByName('_tz') )
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower( $element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if(!is_numeric($d))
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "link":
/*
@field:cat.link
@description:Returns a URL setting the category to the current category
@attrib:_template:tpl:Template URL should point to
@attrib:_mod_template:tpl:Template INSIDE a module to which the category belongs URL should point to
*/
if ( strlen( $element->GetAttributeByName('_mod_template') ) ){
//will prefix the template with module template root path depending on category
$ids = $this->GetParentIds();
$tpath = GetModuleArray("template");
$roots = GetModuleArray("rootcat");
// get template path of module, by searching for moudle name
// in this categories first parent category
// and then using found moudle name as a key for module template paths array
$path = $tpath[array_search ($ids[0], $roots)];
$t = $path . $element->GetAttributeByName('_mod_template');
}
else
$t = $element->GetAttributeByName('_template');
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "adminlink":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "customlink":
$t = $this->GetCustomFieldValue("indextemplate","");
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = GetIndexURL()."?env=" . BuildEnv();
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
// pass through selector
if( isset($_REQUEST['Selector']) ) $ret .= '&Selector='.$_REQUEST['Selector'];
// pass new status
if( isset($_REQUEST['new']) ) $ret .= '&new='.$_REQUEST['new'];
unset($m_var_list_update["cat"]);
return $ret;
break;
case "admin_icon":
if( $element->GetAttributeByName('fulltag') )
{
$ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
}
else
$ret = $this->StatusIcon();
break;
case "subcats":
/*
@field:cat.subcats
@description: Loads category's subcategories into a list and renders using the m_list_cats global tag
@attrib:_subcattemplate:tpl:Template used to render subcategory list elements
@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
@attrib: _maxlistcount:int: Maximum number of categories to list
@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
@attrib: _LastItemTemplate:tpl: Template used for the last category listed
@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
*/
$attr = array();
$attr["_catid"] = $this->Get("CategoryId");
$attr["_itemtemplate"] = $element->GetAttributeByName('_subcattemplate');
if( $element->GetAttributeByName('_notable') )
$attr["_notable"]=1;
$ret = m_list_cats($attr);
break;
case "subcatcount":
/*
@field:cat.subcatcount
@description:returns number of subcategories
*/
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .="_CategoryCount=\"1\" _ItemType=\"1\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
break;
case "itemcount":
/*
@field:cat.itemcount
@description:returns the number of items in the category
@attrib:_itemtype::name of item type to count, or all items if not set
*/
$typestr = $element->GetAttributeByName('_itemtype');
if(strlen($typestr))
{
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$TypeId = $type->Get("ItemType");
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .=" _ListType=\"category\" _CountCurrent=\"1\" _ItemType=\"$TypeId\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
}
else
$ret = "";
}
else
{
$ret = (int)$objCountCache->GetCatListTotal($this->Get("CategoryId"));
}
break;
case "totalitems":
/*
@field:cat.totalitems
@description:returns the number of items in the category and all subcategories
*/
$ret = $this->ItemCount();
break;
case "itemdate":
/*
@field:cat.itemdate
@description:Returns the date the cache count was last updated
@attrib:_itemtype:Item name to check
@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
*/
$typestr = $element->GetAttributeByName('_itemtype');
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$TypeId = $type->Get("ItemType");
$cc = $objCountCache->GetCountObject(1,$TypeId,$this->get("CategoryId"),0);
if(is_object($cc))
{
$date = $cc->Get("LastUpdate");
}
else
$date = "";
//$date = $this->GetCacheCountDate($TypeId);
if( $element->GetAttributeByName('_tz') )
{
$date = GetLocalTime($date,$objSession->Get("tz"));
}
$part = strtolower($element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$date);
}
else
{
if($date<=0)
{
$ret = "";
}
else
$ret = LangDate($date);
}
}
else
$ret = "";
break;
case "new":
/*
@field:cat.new
@description:returns text if category's status is "new"
@attrib:_label:lang: Text to return if status is new
*/
if($this->IsNewItem())
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_new";
$ret = language($ret);
}
else
$ret = "";
break;
case "pick":
/*
@field:cat.pick
@description:returns text if article's status is "hot"
@attrib:_label:lang: Text to return if status is "hot"
*/
if($this->Get("EditorsPick")==1)
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_pick";
$ret = language($ret);
}
else
$ret = "";
break;
case "parsetag":
/*
@field:cat.parsetag
@description:returns a tag output with this categoriy set as a current category
@attrib:_tag:: tag name
*/
$tag = new clsHtmlTag();
$tag->name = $element->GetAttributeByName('_tag');
$tag->attributes = $element->attributes;
$tag->attributes["_catid"] = $this->Get("CategoryId");
$ret = $tag->Execute();
break;
/*
@field:cat.relevance
@description:Displays the category relevance in search results
@attrib:_displaymode:: How the relevance should be displayed<br>
<UL>
<LI>"Numerical": Show the decimal value
<LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
<LI>"Graphical":Show image representing the relevance
</UL>
@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode
*/
}
if( !isset($ret) ) $ret = parent::ParseObject($element);
}
return $ret;
}
function parsetag($tag)
{
global $objConfig,$objUsers, $m_var_list, $m_var_list_update;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "cat_id":
return $this->Get("CategoryId");
break;
case "cat_parent":
return $this->Get("ParentId");
break;
case "cat_fullpath":
return $this->Get("CachedNavbar");
break;
case "cat_name":
return inp_unescape($this->Get("Name"));
break;
case "cat_desc":
return inp_unescape($this->Get("Description"));
break;
case "cat_priority":
if($this->Get("Priority")!=0)
{
return (int)$this->Get("Priority");
}
else
return "";
break;
case "cat_pick":
if ($this->Get("EditorsPick"))
return "pick";
break;
case "cat_status":
return $this->Get("Status");
break;
case "cat_Pending":
return $this->Get("Name");
break;
case "cat_pop":
if($this->IsPopItem())
return "pop";
break;
case "cat_new":
if($this->IsNewItem())
return "new";
break;
case "cat_hot":
if($this->IsHotItem())
return "hot";
break;
case "cat_metakeywords":
return inp_unescape($this->Get("MetaKeywords"));
break;
case "cat_metadesc":
return inp_unescape($this->Get("MetaDescription"));
break;
case "cat_createdby":
return $objUsers->GetUserName($this->Get("CreatedById"));
break;
case "cat_resourceid":
return $this->Get("ResourceId");
break;
case "cat_sub_cats":
return $this->GetSubCats($objConfig->Get("SubCat_ListCount"));
break;
case "cat_link":
return $this->Cat_Link();
break;
case "subcat_count":
return $this->SubCatCount();
break;
case "cat_itemcount":
return (int)$this->GetTotalItemCount();
break;
case "cat_link_admin":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "cat_admin_icon":
$ret = $this->StatusIcon();
return $ret;
break;
case "cat_link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
break;
case "cat_link_edit":
$m_var_list_update["id"] = $this->Get("CategoryId");
$ret = "addcategory.php?env=" . BuildEnv();
unset($m_var_list_update["id"]);
return $ret;
break;
case "cat_date":
return LangDate($this->Get("CreatedOn"));
break;
case "cat_num_cats":
return $this->Get("CachedDescendantCatsQty");
break;
case "cell_back":
if ($m_var_list_update["cat_cell"]=="#cccccc")
{
$m_var_list_update["cat_cell"]="#ffffff";
return "#ffffff";
}
else
{
$m_var_list_update["cat_cell"]="#cccccc";
return "#cccccc";
}
break;
default:
return "Undefined:$tagname";
}
}
function ParentNames()
{
global $objCatList;
if(strlen($this->Get("CachedNavbar"))==0)
{
$nav = "";
//echo "Rebuilding Navbar..<br>\n";
if(strlen($this->Get("ParentPath"))==0)
{
$this->UpdateCachedPath();
}
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
foreach($cats as $catid)
{
$cat =& $objCatList->GetCategory($catid);
if(is_object($cat))
{
if(strlen($cat->Get("Name")))
$names[] = $cat->Get("Name");
}
}
$nav = implode(">", $names);
$this->Set("CachedNavbar",$nav);
$this->Update();
}
$res = explode(">",$this->Get("CachedNavbar"));
return $res;
}
function UpdateCacheCounts()
{
global $objItemTypes;
$CatId = $this->Get("CategoryId");
if($CatId>0)
{
//echo "Updating count for ".$this->Get("CachedNavbar")."<br>\n";
UpdateCategoryCount(0,$CatId);
}
}
}
class clsCatList extends clsItemList //clsItemCollection
{
//var $Page; // no need because clsItemList class used instead of clsItemCollection
//var $PerPageVar;
function clsCatList()
{
global $m_var_list;
$this->clsItemCollection();
$this->classname="clsCategory";
$this->AdminSearchFields = array("Name","Description");
$this->Page = (int)$m_var_list["p"];
$this->PerPageVar = "Perpage_Category";
$this->SourceTable = GetTablePrefix()."Category";
$this->BasePermission="CATEGORY";
$this->DefaultPerPage = 20;
}
function SaveNewPage()
{
global $m_var_list;
$m_var_list["p"] = $this->Page;
}
function GetCountSQL($PermName,$CatId=NULL, $GroupId=NULL, $AdditonalWhere="")
{
global $objSession, $objPermissions, $objCatList;
$ltable = $this->SourceTable;
$acl = $objSession->GetACLClause();
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$VIEW = $objPermissions->GetPermId($PermName);
$sql = "SELECT count(*) as CacheVal FROM $ltable ";
$sql .="INNER JOIN $ptable ON ($ltable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ($acl AND PermId=$VIEW AND $ltable.Status=1) ";
if(strlen($AdditonalWhere)>0)
{
$sql .= "AND (".$AdditonalWhere.")";
}
return $sql;
}
function CountCategories($attribs)
{
global $objSession;
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $this->CurrentCategoryID();
}
if((int)$cat>0)
$c = $this->GetCategory($cat);
if($attribs["_subcats"] && $cat>0)
{
$ParentWhere = "(ParentPath LIKE '".$c->Get("ParentPath")."%' AND ".$this->SourceTable.".CategoryId != $cat)";
}
if($attribs["_today"])
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$TodayWhere = "(CreatedOn>=$today)";
}
if($attribs["_grouponly"])
{
$GroupList = $objSession->Get("GroupList");
}
else
$GroupList = NULL;
$where = "";
if(strlen($ParentWhere))
{
$where = $ParentWhere;
}
if(strlen($TodayWhere))
{
if(strlen($where))
$where .=" AND ";
$where .= $TodayWhere;
}
$sql = $this->GetCountSQL("CATEGORY.VIEW",$cat,$GroupList,$where);
// echo "SQL: ".$sql."<BR>";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["CacheVal"];
}
else
$ret = 0;
return $ret;
}
function CurrentCategoryID()
{
global $m_var_list;
return (int)$m_var_list["cat"];
}
function NumCategories()
{
return $this->NumItems();
}
function &CurrentCat()
{
//return $this->GetCategory($this->CurrentCategoryID());
return $this->GetItem($this->CurrentCategoryID());
}
function &GetCategory($CatID)
{
return $this->GetItem($CatID);
}
function GetByResource($ResId)
{
return $this->GetItemByField("ResourceId",$ResId);
}
function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)
{
global $objSession;
if($UseTableName)
{
$TableName = $this->SourceTable.".";
}
else
$TableName = "";
$Orders = array();
if($EditorsPick)
{
$Orders[] = $TableName."EditorsPick DESC";
}
if($Priority)
{
$Orders[] = $TableName."Priority DESC";
}
$FieldVar = "Category_Sortfield";
$OrderVar = "Category_Sortorder";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
$FieldVar = "Category_Sortfield2";
$OrderVar = "Category_Sortorder2";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
if(count($Orders)>0)
{
$OrderBy = "ORDER BY ".implode(", ",$Orders);
}
else
$OrderBy="";
return $OrderBy;
}
function LoadCategories($where="", $orderBy = "", $no_limit = true, $fix_method = 'set_first')
{
// load category list using $where clause
// apply ordering specified in $orderBy
// show all cats ($no_limit = true) or only from current page ($no_limit = false)
// in case if stored page is greather then page count issue page_fixing with
// method specified (see "FixInvalidPage" method for details)
$PerPage = $this->GetPerPage();
$this->QueryItemCount = TableCount($this->SourceTable,$where,0);
if($no_limit == false)
{
$this->FixInvalidPage($fix_method);
$Start = ($this->Page-1) * $PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $this->Query_Category($where, $orderBy, $limit);
}
function Query_Category($whereClause="",$orderByClause="",$limit=NULL)
{
global $m_var_list, $objSession, $Errors, $objPermissions;
$GroupID = $objSession->Get("GroupID");
$resultset = array();
$table = $this->SourceTable;
$ptable = GetTablePrefix()."PermCache";
$CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
if(!$objSession->HasSystemPermission("ADMIN"))
{
$sql = "SELECT * FROM $table INNER JOIN $ptable ON ($ptable.CategoryId=$table.CategoryId)";
$acl_where = $objSession->GetACLClause();
if(strlen($whereClause))
{
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW AND ".$whereClause;
}
else
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW ";
}
else
{
$sql ="SELECT * FROM $table ".($whereClause ? "WHERE $whereClause" : '');
}
$sql .=" ".$orderByClause;
if(isset($limit) && strlen(trim($limit)))
$sql .= " ".$limit;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql;
return $this->Query_item($sql);
}
function CountPending()
{
return TableCount($this->SourceTable,"Status=".STATUS_PENDING,0);
}
function GetPageLinkList($dest_template=NULL,$page="",$PagesToList=10,$HideEmpty=TRUE)
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$PerPage = $this->GetPerPage();
$NumPages = ceil( $this->GetNumPages($PerPage) );
if($NumPages == 1 && $HideEmpty) return '';
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $var_list["t"];
$o = "";
if($this->Page>$NumPages)
$this->Page=$NumPages;
$StartPage = (int)$this->Page - ($PagesToList/2);
if($StartPage<1)
$StartPage=1;
$EndPage = $StartPage+($PagesToList-1);
if($EndPage>$NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage-($PagesToList-1);
if($StartPage<1)
$StartPage=1;
}
$o = "";
if($StartPage>1)
{
$m_var_list_update["p"] = $this->Page-$PagesToList;
$prev_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = $page."?env=".BuildEnv();
$o .= " <A HREF=\"$href\" >$p</A> ";
}
else
{
$o .= "$p";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
$m_var_list_update["p"]=$this->Page+$PagesToList;
$next_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
}
unset($m_var_list_update,$var_list_update["t"] );
return $o;
}
function GetAdminPageLinkList($url)
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
$PerPage = $this->GetPerPage();
$NumPages = ceil($this->GetNumPages($PerPage));
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
}
for($p=1;$p<=$NumPages;$p++)
{
if($p != $this->Page)
{
$m_var_list_update["p"]=$p;
$href = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
}
else
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
if($this->Page < $NumPages)
$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\">>></A>";
return $o;
}
function Search_Category($orderByClause)
{
global $objSession, $objConfig, $Errors;
$PerPage = $this->GetPerPage();
$Start = ($this->Page-1) * $PerPage;
$objResults = new clsSearchResults("Category","clsCategory");
$this->Clear();
$this->Categories = $objResults->LoadSearchResults($Start,$PerPage);
return $this->Categories;
}
function GetSubCats($ParentCat)
{
return $this->Query_Category("ParentId=".$ParentCat,"");
}
function AllSubCats($ParentCat)
{
$c =& $this->GetCategory($ParentCat);
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ParentPath LIKE '".$c->Get("ParentPath")."%'";
$rs = $this->adodbConnection->Execute($sql);
$subcats = array();
while($rs && !$rs->EOF)
{
if($rs->fields["CategoryId"]!=$ParentCat)
{
$subcats[] = $rs->fields["CategoryId"];
}
$rs->MoveNext();
}
if($ParentCat>0)
{
if($c->Get("CachedDescendantCatsQty")!=count($subcats))
{
$c->Set("CachedDescendantCatsQty",count($subcats));
}
}
return $subcats;
}
function cat_navbar($admin=0, $cat, $target_template, $separator = " > ", $LinkLeaf = FALSE,
$root = 0,$RootTemplate="",$modcat=0, $ModTemplate="", $LinkRoot = FALSE)
{
// draw category navigation bar (at top)
global $Errors, $var_list_update, $var_list, $m_var_list_update, $m_var_list, $objConfig;
$selector = isset($_REQUEST['Selector']) ? '&Selector='.$_REQUEST['Selector'] : '';
$new = isset($_REQUEST['new']) ? '&new='.$_REQUEST['new'] : '';
$nav = "";
$m_var_list_update["p"]=1;
if(strlen($target_template)==0)
$target_template = $var_list["t"];
if($cat == 0)
{
$cat_name = language($objConfig->Get("Root_Name"));
if ($LinkRoot)
{
$var_list_update["t"] = strlen($RootTemplate)? $RootTemplate : $target_template;
$nav = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">$cat_name</a>"; }
else
$nav = "<span class=\"NAV_CURRENT_ITEM\">$cat_name</span>";
}
else
{
$nav = array();
$c =& $this->GetCategory($cat);
$nav_unparsed = $c->Get("ParentPath");
if(strlen($nav_unparsed)==0)
{
$c->UpdateCachedPath();
$nav_unparsed = $c->Get("ParentPath");
}
//echo " Before $nav_unparsed ";
if($root)
{
$r =& $this->GetCategory($root);
$rpath = $r->Get("ParentPath");
$nav_unparsed = substr($nav_unparsed,strlen($rpath),-1);
$cat_name = $r->Get("Name");
$m_var_list_update["cat"] = $root;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
{
$var_list_update["t"] = $target_template;
}
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
}
}
else
{
$nav_unparsed = substr($nav_unparsed,1,-1);
$cat_name = language($objConfig->Get("Root_Name"));
$m_var_list_update["cat"] = 0;
if($cat == 0)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
$var_list_update["t"] = $target_template;
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
}
}
//echo " After $nav_unparsed <br>\n";
if(strlen($target_template)==0)
$target_template = $var_list["t"];
$cats = explode("|", $nav_unparsed);
foreach($cats as $catid)
{
if($catid)
{
$c =& $this->GetCategory($catid);
if(is_object($c))
{
$cat_name = $c->Get("Name");
$m_var_list_update["cat"] = $catid;
if($catid==$modcat && strlen($ModTemplate)>0)
{
$t = $ModTemplate;
}
else
$t = $target_template;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
}
else
{
$var_list_update["t"] = $t;
$nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
unset($var_list_update["t"]);
}
}
unset($m_var_list_update["cat"]);
}
}
}
$nav = implode($separator, $nav);
}
return $nav;
}
function &Add($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, $Pop,
$Priority, $MetaKeywords,$MetaDesc)
{
global $objSession;
$UserId = $objSession->Get("UserId");
$d = new clsCategory(NULL);
$d->tablename = $this->SourceTable;
if($d->UsingTempTable())
$d->Set("CategoryId",-1);
$d->idfield = "CategoryId";
$d->Set(array("ParentId", "Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem",
"NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById"),
array($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New,
$Pop, $Priority, $MetaKeywords,$MetaDesc, $UserId));
$d->Create();
if($Status==1)
{
$d->SendUserEventMail("CATEGORY.ADD",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD");
}
else
{
$d->SendUserEventMail("CATEGORY.ADD.PENDING",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD.PENDING");
}
$d->UpdateCachedPath();
//RunUp($ParentId, "Increment_Count");
return $d;
}
function &Edit_Category($CategoryId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot,
$NewItem, $Pop, $Priority, $MetaKeywords,$MetaDesc)
{
$d =& $this->GetCategory($CategoryId);
$d->Set(array("Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem",
"NewItem", "PopItem", "Priority", "MetaKeywords","MetaDescription"),
array($Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $NewItem,
$Pop, $Priority, $MetaKeywords,$MetaDesc));
$d->Update();
$d->UpdateCachedPath();
return $d;
}
function Move_Category($Id, $ParentTo)
{
global $objCatList;
$d =& $this->GetCategory($Id);
$oldparent = $d->Get("ParentId");
$ChildList = $d->GetSubCatIds();
/*
echo "Target Parent Id: $ParentTo <br>\n";
echo "<PRE>";print_r($ChildList); echo "</PRE>";
echo "Old Parent: $oldparent <br>\n";
echo "ID: $Id <br>\n";
*/
/* sanity checks */
if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id &&
$Id != $ParentTo)
{
$d->Set("ParentId", $ParentTo);
$d->Update();
$d->UpdateCachedPath();
RunUp($oldparent, "Decrement_Count");
RunUp($ParentTo, "Increment_Count");
RunDown($ParentTo, "UpdateCachedPath");
return TRUE;
}
else
{
global $Errors;
$Errors->AddAdminUserError("la_error_move_subcategory");
return FALSE;
}
die();
}
function Copy_CategoryTree($Id, $ParentTo)
{
global $PastedCatIds;
$new = $this->Copy_Category($Id, $ParentTo);
if($new)
{
$PastedCatIds[$Id] = $new;
$sql = "SELECT CategoryId from ".GetTablePrefix()."Category where ParentId=$Id";
$result = $this->adodbConnection->Execute($sql);
if ($result && !$result->EOF)
{
while(!$result->EOF)
{
$this->Copy_CategoryTree($result->fields["CategoryId"], $new);
$result->MoveNext();
}
}
}
return $new;
}
function Copy_Category($Id, $ParentTo)
{
global $objGroups;
$src = $this->GetCategory($Id);
$Children = $src->GetSubCatIds();
if($Id==$ParentTo || in_array($ParentTo,$Children))
{
/* sanity error here */
global $Errors;
$Errors->AddAdminUserError("la_error_copy_subcategory");
return 0;
}
$dest = $src;
$dest->Set("ParentId", $ParentTo);
if ($src->get("ParentId") == $ParentTo)
{
$OldName = $src->Get("Name");
if(substr($OldName,0,5)=="Copy ")
{
$parts = explode(" ",$OldName,4);
if($parts[2]=="of" && is_numeric($parts[1]))
{
$Name = $parts[3];
}
else
if($parts[1]=="of")
{
$Name = $parts[2]." ".$parts[3];
}
else
$Name = $OldName;
}
else
$Name = $OldName;
//echo "New Name: $Name<br>";
$dest->Set("Name", $Name);
$Names = CategoryNameCount($ParentTo,$Name);
//echo "Names Count: ".count($Names)."<br>";
if(count($Names)>0)
{
$NameCount = count($Names);
$found = FALSE;
$NewName = "Copy of $Name";
if(!in_array($NewName,$Names))
{
//echo "Matched on $NewName in:<br>\n";
$found = TRUE;
}
else
{
for($x=2;$x<$NameCount+2;$x++)
{
$NewName = "Copy ".$x." of ".$Name;
if(!in_array($NewName,$Names))
{
$found = TRUE;
break;
}
}
}
if(!$found)
{
$NameCount++;
$NewName = "Copy $NameCount of $Name";
}
//echo "New Name: $NewName<br>";
$dest->Set("Name",$NewName);
}
}
$dest->UnsetIdField();
$dest->Set("CachedDescendantCatsQty",0);
$dest->Set("ResourceId",NULL);
$dest->Create();
$dest->UpdateCachedPath();
$p = new clsPermList();
$p->Copy_Permissions($src->Get("CategoryId"),$dest->Get("CategoryId"));
$glist = $objGroups->GetAllGroupList();
$view = $p->GetGroupPermList($dest, "CATEGORY.VIEW", $glist);
$dest->SetViewPerms("CATEGORY.VIEW",$view,$glist);
RunUp($ParentTo, "Increment_Count");
return $dest->Get("CategoryId");
}
function Delete_Category($Id)
{
global $objSession;
$d =& $this->GetCategory($Id);
if(is_object($d))
{
if($d->Get("CategoryId")==$Id)
{
$d->SendUserEventMail("CATEGORY.DELETE",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.DELETE");
$p =& $this->GetCategory($d->Get("ParentId"));
RunDown($d->Get("CategoryId"), "Delete");
RunUp($p->Get("CategoryId"), "Decrement_Count");
RunUp($d->Get("CategoryId"),"ClearCacheData");
}
}
}
function PasteFromClipboard($TargetCat)
{
global $objSession;
$clip = $objSession->GetVariable("ClipBoard");
if(strlen($clip))
{
$ClipBoard = ParseClipboard($clip);
$IsCopy = (substr($ClipBoard["command"],0,4)=="COPY") || ($ClipBoard["source"] == $TargetCat);
$item_ids = explode(",",$ClipBoard["ids"]);
for($i=0;$i<count($item_ids);$i++)
{
$ItemId = $item_ids[$i];
$item = $this->GetItem($item_ids[$i]);
if(!$IsCopy)
{
$this->Move_Category($ItemId, $TargetCat);
$clip = str_replace("CUT","COPY",$clip);
$objSession->SetVariable("ClipBoard",$clip);
}
else
{
$this->Copy_CategoryTree($ItemId,$TargetCat);
}
}
}
}
function NumChildren($ParentID)
{
$cat_filter = "m_cat_filter";
global $$cat_filter;
$filter = $$cat_filter;
$adodbConnection = GetADODBConnection();
$sql = "SELECT COUNT(Name) as children from ".$this->SourceTable." where ParentId=" . $ParentID . $filter;
$result = $adodbConnection->Execute($sql);
return $result->fields["children"];
}
function UpdateMissingCacheData()
{
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE ParentPath IS NULL or ParentPath=''");
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CachedNavbar IS NULL or CachedNavBar=''");
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
}
function CopyFromEditTable($idfield)
{
global $objGroups, $objSession, $objPermList;
$objPermList = new clsPermList();
$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->Dirty();
if($c->Get("CategoryId")>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."Permissions SET CatId=".$c->Get("CategoryId")." WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
$c->UpdateCachedPath();
$c->UpdateACL();
$c->SendUserEventMail("CATEGORY.MODIFY",$objSession->Get("PortalUserId"));
$c->SendAdminEventMail("CATEGORY.MODIFY");
$c->Related = new clsRelationshipList();
if(is_object($c->Related))
{
$r = $c->Related;
$r->CopyFromEditTable($c->Get("ResourceId"));
}
//RunDown($c->Get("CategoryId"),"UpdateCachedPath");
//RunDown($c->Get("CategoryId"),"UpdateACL");
unset($c);
unset($r);
$rs->MoveNext();
}
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
//$this->UpdateMissingCacheData();
}
function PurgeEditTable($idfield)
{
parent::PurgeEditTable($idfield);
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
function GetExclusiveType($CatId)
{
global $objItemTypes, $objConfig;
$itemtype = NULL;
$c =& $this->GetItem($CatId);
$path = $c->Get("ParentPath");
foreach($objItemTypes->Items as $Type)
{
$RootVar = $Type->Get("ItemName")."_Root";
$RootId = $objConfig->Get($RootVar);
if((int)$RootId)
{
$rcat = $this->GetItem($RootId);
$rpath = $rcat->Get("ParentPath");
$p = substr($path,0,strlen($rpath));
//echo $rpath." vs. .$p [$path]<br>\n";
if($rpath==$p)
{
$itemtype = $Type;
break;
}
}
}
return $itemtype;
}
}
function RunUp($Id, $function, $Param=NULL)
{
global $objCatList;
$d = $objCatList->GetCategory($Id);
$ParentId = $d->Get("ParentId");
if ($ParentId == 0)
{
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
else
{
RunUp($ParentId, $function, $Param);
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
}
function RunDown($Id, $function, $Param=NULL)
{
global $objCatList;
$adodbConnection = GetADODBConnection();
$sql = "select CategoryId from ".GetTablePrefix()."Category where ParentId='$Id'";
$rs = $adodbConnection->Execute($sql);
//echo $sql."<br>\n";
while($rs && !$rs->EOF)
{
RunDown($rs->fields["CategoryId"], $function, $Param);
$rs->MoveNext();
}
$d = $objCatList->GetCategory($Id);
if($Param == NULL)
{
$d->$function();
}
else
$d->$function($Param);
}
?>
Property changes on: trunk/kernel/include/category.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/itemreview.php
===================================================================
--- trunk/kernel/include/itemreview.php (revision 270)
+++ trunk/kernel/include/itemreview.php (revision 271)
@@ -1,615 +1,615 @@
<?php
function ip_exists($ip,$id,$SourceTable)
{
$count = 0;
$sql = "SELECT count(*) as DupCount FROM $SourceTable WHERE IPAddress='$ip' and ItemId=$id";
$adodbConnection = GetADODBConnection();
$rs = $adodbConnection->Execute($sql);
if($rs)
{
$count = $rs->fields["DupCount"];
}
return ($count>0);
}
RegisterPrefix("clsItemReview","review","kernel/include/itemreview.php");
class clsItemReview extends clsParsedItem
{
function clsItemReview($ReviewId=NULL,$table="ItemReview")
{
$this->clsParsedItem();
$this->tablename = $table;
$this->id_field = "ReviewId";
$this->type=-20;
$this->NoResourceId=1;
$this->TagPrefix = "review";
if($ReviewId!=NULL)
$this->LoadFromDatabase($ReviewId);
}
function Validate()
{
global $Errors;
$dataValid = true;
if(!isset($this->m_CreatedOn))
{
$Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_ReviewText))
{
$Errors->AddError("error.fieldIsRequired",'ReviewText',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Pending))
{
$Error->AddError("error.fieldIsRequired",'Pending',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_IPAddress))
{
$Error->AddError("error.fieldIsRequired",'IPAddress',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_ItemId))
{
$Error->AddError("error.fieldIsRequired",'ItemId',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_CreatedById))
{
$Error->AddError("error.fieldIsRequired",'CreatedBy',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function LoadFromDatabase($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ReviewId = '%s'",$Id);
if((int)$_GLOBALS["debuglevel"])
echo $sql."<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $objUsers;
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
/*
@field:review.id
@description: review id
*/
$ret = $this->Get("ReviewId");
break;
case "item_id":
/*
@field:review.item_id
@description: ID of the item being reviewed
*/
$ret = inp_unescape($this->Get("ItemId"));
break;
case "text":
/*
@field:review.text
@description:Review text
*/
if($this->Get("TextFormat")==0 || $element->attribues["_textonly"])
{
$ret = inp_escape($this->Get("ReviewText"),0);
}
else
{
$ret = $this->Get("ReviewText");
}
break;
case "ip":
/*
@field:review.ip
@description:IP address of remote host submitting the review
*/
$ret = $this->Get("IPAddress");
break;
case "pending":
/*
@field:review.pending
@description: Returns the review pening status
*/
$ret = $this->Get("Pending");
break;
case "item_type":
/*
@field:review.item_type
@description:Returns the name of the reviewed item type
*/
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
if(is_object($type))
$ret = $type->Get("ItemName");
break;
case "date":
/*
@field:review.date
@description:Returns the date/time the review was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "reviewer":
/*
@field:revier.reviewer
@description:Parse a user tag for the user submitting the review
@attrib:_usertag::User tag to parse, defaults to the users login name
*/
$userfield = $element->attributes["_usertag"];
if(!strlen($userfield))
{
$userfield = "login";
}
if($this->Get("CreatedById")>0)
{
$u =& $objUsers->GetItem($this->Get("CreatedById"));
$e = new clsHtmlTag();
$e->name = $u->TagPrefix;
$e->attributes = $element->attributes;
$e->attributes["_field"] = $userfield;
$ret = $u->ParseObject($e);
}
else
if($userfield=="login")
$ret = "root";
break;
default:
$tag = $this->TagPrefix."_".$field;
$ret = "Undefined: ".$tag->name;
break;
}
}
else
{
$ret = $element->Execute();
}
return $ret;
}
function parsetag($tag)
{
global $objConfig, $objUsers, $objItemTypes;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "review_id":
return $this->Get("ReviewId");
break;
case "review_item_id":
return inp_unescape($this->Get("ItemId"));
break;
case "review_text":
return $this->Get("ReviewText");
break;
case "review_ip_address":
return $this->Get("IPAddress");
break;
case "review_pending":
return $this->Get("Pending");
break;
case "review_item_type":
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
return $res;
break;
case "review_created_date":
return LangDate($this->Get("CreatedOn"));
break;
case "review_created_time":
if($this->Get("CreatedOn")<=0)
return "";
return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn"));
break;
case "review_created_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "review_created_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "review_created_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
default:
if (substr($tagname, 0, 16) == "review_createdby")
{
/* parse the created by user */
$u = $objUsers->GetUser($this->Get("CreatedById"));
$usertag = substr($tag,17);
return $u->parsetag($usertag);
}
else
return "Undefined:$tagname";
break;
}
}
function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL)
{
global $objItemTypes, $objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendToUser($ToUserId);
}
}
}
function SendAdminEventMail($EventName,$LangId=NULL)
{
global $objItemTypes,$objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendAdmin($ToUserId);
}
}
}
} /*clsIItemReview*/
class clsItemReviewList extends clsItemCollection
{
var $itemID;
var $Page;
var $PerPageVar;
function clsItemReviewList($id=NULL)
{
$this->clsItemCollection();
$this->classname = "clsItemReview";
$this->SourceTable = GetTablePrefix()."ItemReview";
$this->Page = 1;
$this->PerPageVar = "Perpage_Review";
if(isset($id))
$this->itemID=$id;
$this->AdminSearchFields = array("ReviewText");
}
function ItemCount()
{
return $this->NumItems();
}
function GetReview($ID)
{
return $this->GetItem($ID);
}
function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL)
{
$this->Clear();
$where = "ItemId=".$this->itemID;
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ";
if(strlen($StatusWhere))
$where .= " AND ".$StatusWhere;
$sql .= $where;
if(strlen($OrderBy))
$sql .= " ORDER BY ".$OrderBy;
$Limit = $this->GetLimitSQL();
if(strlen($Limit))
$sql .= " ".$Limit;
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
return $this->Query_item($sql);
}
function GetItemReviewCount($TodayOnly = FALSE)
{
$sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1";
if($TodayOnly)
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND CreatedOn>=$today";
}
$rs = $this->adodbConnection->execute($sql);
$count=0;
if($rs)
$count = $rs->fields["ItemCount"];
return (int)$count;
}
function ip_exists($ip,$id)
{
return ip_exists($ip,id,$this->SourceTable);
}
function GetLimitSQL()
{
global $objConfig;
if($this->Page<1)
$this->Page=1;
$PerPage = $objConfig->Get($this->PerPageVar);
if(is_numeric($PerPage))
{
$Start = ($this->Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function Query_Review($whereClause=NULL,$orderByClause=NULL)
{
global $Errors;
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(isset($whereClause) && strlen(trim($whereClause))>0)
$sql = sprintf("%s WHERE %s",$sql,$whereClause);
if(isset($orderByClause) && strlen(trim($orderByClause))>0)
$sql = sprintf("%s ORDER BY %s",$sql,$orderByClause);
return $this->Query_Item($sql);
}
function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module)
{
global $objSession;
$r = new clsItemReview(NULL,$this->SourceTable);
$ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText);
//$r->debuglevel = 1;
$r->Set(array("CreatedOn","ReviewText","Status", "IPAddress",
"Priority","ItemId","ItemType","CreatedById","TextFormat","Module"),
array($CreatedOn,$ReviewText,$Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Create();
array_push($this->Items,$r);
if($Status==1)
{
$r->SendUserEventMail("REVIEW.ADD",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD");
}
else
{
$r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD.PENDING");
}
return $r;
}
function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)
{
global $objSession;
$r = $this->GetItem($ReviewId);
if($CreatedById==0)
$CreatedById = $r->Get("CreatedById");
$r->Set(array("ReviewId","CreatedOn","ReviewText","Status",
"IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"),
array($ReviewId,$CreatedOn,$ReviewText,$Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Update();
//$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId"));
$r->SendAdminEventMail("REVIEW.MODIFY");
return $r;
}
function DeleteReview($ReviewId)
{
$r = $this->GetItem($ReviewId);
$r->Delete();
}
function CopyToItemId($OldId,$NewId)
{
$this->Clear();
$this->Query_Review("ItemId=$OldId","");
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->Set("ItemId",$NewId);
$i->UnsetIdField();
$i->Create();
}
}
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["ReviewId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("ReviewId");
$rs->MoveNext();
}
$sql = "DELETE FROM ".$this->SourceTable." WHERE ItemId=$ResourceId AND ReviewId NOT IN (".implode(",",$idlist).")";
$this->adodbConnection->Execute($sql);
- @$this->adodbConnection->Execute("DROP TABLE ".$edit_table);
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$edit_table);
}
function GetPageLinkList(&$UpdateVar,$dest_template=NULL,$page = NULL,$PagesToList=10,$HideEmpty=TRUE)
{
global $objConfig, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$PerPage = $objConfig->Get($this->PerPageVar);
if($PerPage<1)
$PerPage=20;
$NumPages = ceil($this->GetNumPages($PerPage));
if($NumPages==1 && $HideEmpty)
return "";
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $var_list["t"];
$o = "";
if($this->Page>$NumPages)
$this->Page=$NumPages;
$StartPage = (int)$this->Page - ($PagesToList/2);
if($StartPage<1)
$StartPage=1;
$EndPage = $StartPage+($PagesToList-1);
if($EndPage>$NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage-($PagesToList-1);
if($StartPage<1)
$StartPage=1;
}
$o = "";
if($StartPage>1)
{
$UpdateVar["rp"] = $this->Page-$PagesToList;
$prev_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
$UpdateVar["rp"]=$p;
$href = $page."?env=".BuildEnv();
$o .= " <A HREF=\"$href\" >$p</A> ";
}
else
{
$o .= "$p";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
$UpdateVar["rp"]=$this->Page+$PagesToList;
$next_url = $page."?env=".BuildEnv();
$o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
}
unset($UpdateVar,$var_list_update["t"] );
return $o;
}
} /*clsItemReviewList*/
?>
Property changes on: trunk/kernel/include/itemreview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/include/portaluser.php
===================================================================
--- trunk/kernel/include/portaluser.php (revision 270)
+++ trunk/kernel/include/portaluser.php (revision 271)
@@ -1,1004 +1,1004 @@
<?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();
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 = $this->Get("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->SourceTable = 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));
if($CheckBanned)
{
$BrokenRule = $u->CheckBanned();
}
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 $edit_table");
+ @$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.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/kernel/include/relationship.php
===================================================================
--- trunk/kernel/include/relationship.php (revision 270)
+++ trunk/kernel/include/relationship.php (revision 271)
@@ -1,411 +1,434 @@
<?php
class clsRelationship extends clsItemDB
{
var $expanded;
function clsRelationship($id=NULL,$expanded=FALSE)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Relationship";
$this->id_field = "RelationshipId";
$this->NoResourceId = 1;
$this->expanded=FALSE;
+ GetModuleArray();
if($id)
{
if(!$expanded)
{
$this->LoadFromDatabase($id);
}
else
$this->LoadExpanded($id);
}
}
function LoadExpanded($id)
{
+ global $objModules;
$pre = GetTablePrefix();
$reltable = $this->tablename;
- $sql = "SELECT trim(concat(ifnull(".$pre."Category.name,' '), ifnull(".$pre."Link.name,' '),ifnull(".$pre."News.title,' '), ifnull(".$pre."Topic.TopicText,' '))) as ItemName,";
- $sql .=" ELT(rel.targettype, '".admin_language("la_Text_Category")."' ,'".admin_language("la_Text_Article");
- $sql .="' ,'".admin_language("la_Text_Topic")."','".admin_language("la_Text_Link")."') as ItemType,";
- $sql .=" ELT(rel.type+1,'".admin_language("la_Text_OneWay")."','".admin_language("la_Text_Reciprocal")."') as RelationType,";
- $sql .=" RelationshipId, rel.TargetId,rel.TargetType,rel.SourceId,rel.SourceType, rel.Type, rel.Enabled, rel.Priority, ";
- $sql .=" ELT(rel.enabled+1,'Disabled','Enabled') as Status FROM ".$reltable." as rel ";
- $sql .=" LEFT JOIN ".$pre."Category ON ".$pre."Category.ResourceId=rel.TargetId ";
- $sql .="LEFT JOIN ".$pre."Link ON ".$pre."Link.ResourceId=rel.TargetId ";
- $sql .="LEFT JOIN ".$pre."News ON ".$pre."News.ResourceId=rel.TargetId ";
- $sql .="LEFT JOIN ".$pre."Topic ON ".$pre."Topic.ResourceId=rel.TargetId ";
- $sql .="WHERE rel.RelationshipId=".$id;
- $rs=$this->adodbConnection->Execute($sql);
+ // ==== build sql depending on modules installed: begin ====
+ $prefix = GetTablePrefix();
+ $modules = $objModules->GetModuleList();
+ $sql_source = $objModules->ExecuteFunction('GetModuleInfo', 'rel_list');
+
+ $sql_templates['ItemName'] = 'IFNULL('.$prefix."%s.%s,' ')";
+ $sql_templates['TableJoin'] = 'LEFT JOIN '.$prefix."%1\$s ON ".$prefix."%1\$s.ResourceId = rel.TargetId";
+ $sql_templates['TargetName'] = "IF(rel.TargetType = %s, '%s', %s)";
+
+ $sql = "SELECT TRIM(CONCAT(%s)) AS ItemName, %s AS ItemType,".
+ GetELT('rel.Type+1', Array('la_Text_OneWay','la_Text_Reciprocal')).' AS RelationType,'.
+ "RelationshipId, rel.Priority AS Priority, rel.Type as Type, rel.Enabled as Enabled,".
+ "rel.TargetId, rel.TargetType, rel.SourceId, rel.SourceType,".
+ GetELT('rel.Enabled+1', Array('la_Text_Disabled','la_Text_Enabled')).' AS Status '.
+ 'FROM '.$reltable.' AS rel %s WHERE rel.RelationshipId = '.$id;
+
+ $sql_parts = Array();
+ $sql_parts['TargetName'] = "''";
+ foreach($modules as $module)
+ {
+ $sql_parts['ItemName'][] = sprintf($sql_templates['ItemName'], $sql_source[$module]['MainTable'], $sql_source[$module]['ItemNameField']);
+ $sql_parts['TableJoin'][] = sprintf($sql_templates['TableJoin'], $sql_source[$module]['MainTable']);
+
+ $sql_parts['TargetName'] = sprintf( $sql_templates['TargetName'],
+ $sql_source[$module]['TargetType'],
+ admin_language($sql_source[$module]['ItemNamePhrase']),
+ $sql_parts['TargetName']);
+ }
+ $sql = sprintf($sql, implode(', ',$sql_parts['ItemName']), $sql_parts['TargetName'], implode(' ',$sql_parts['TableJoin']));
+ // ==== build sql depending on modules installed: end ====
+
+ //echo "SQL: ".$sql.'<br>';
+
+ $rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
$this->expanded=TRUE;
return TRUE;
}
else
return FALSE;
}
function LoadFromDatabase($id)
{
$table = $this->tablename;
$sql = "SELECT * FROM $table";
$sql .= " WHERE ".$this->id_field."=".$id;
$rs=$this->adodbConnection->execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$this->SetFromArray($data);
$this->Clean();
$this->expanded=FALSE;
return TRUE;
}
else
return FALSE;
}
function GetTargetItemData()
{
global $objItemTypes;
/*returns the table row in an array for the item this relationship points to */
- $type=$this->Get("TargetType");
-
+ $type = $this->Get("TargetType");
$Item = $objItemTypes->GetItem($type);
$table = $Item->Get("SourceTable");
$titlefield = $Item->Get("TitleField");
if(strlen($table))
{
$sql = "SELECT * FROM ".GetTablePrefix().$table." WHERE ResourceId=".$this->Get("TargetId");
$rs = $this->adodbConnection->execute($sql);
if($rs)
{
$res = $rs->fields;
$res["SourceTable"]=$table;
$res["TitleField"]=$titlefield;
return $res;
}
else
return FALSE;
}
else
return FALSE;
}
function Admin_Icon()
{
global $imagesURL;
$type = "reciprocal";
if($this->Get("Type")==0)
{
$type = "one-way";
}
$icon = $imagesURL."/itemicons/icon16_relation_".$type;
if($this->Get("Enabled")!=1)
{
$icon .= "_disabled";
}
$icon .= ".gif";
return $icon;
}
function parse_template()
{
$item = $this->GetTargetItemData();
$type=$this->Get("TargetType");
switch($type)
{
case 1:
$c = new clsCategory();
$t = "cat_relate_element";
break;
case 2:
$c = new clsNews();
$t = "innews/news_relate_element";
break;
case 3:
$c = new clsTopic();
$t="inbulletin/bb_relate_element";
break;
case 4:
$c = new clsLink();
$t="inlink/link_relate_element";
break;
case 5:
$c = new clsSurvey();
$t="insurvey/s_relate_element";
break;
default:
$c=NULL;
}
if(is_object($c))
{
foreach($item as $key=>$value)
{
$c->Set($key,$value);
}
$o = $c->parse_template(parse($t));
}
return $o;
}
function &GetTargetItemClass()
{
global $objItemTypes;
$objType = $objItemTypes->GetItem($this->Get("TargetType"));
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$c = new $classname;
}
else
$c = NULL;
if(is_object($c))
{
$c->LoadFromResourceId($this->Get("TargetId"));
}
return $c;
}
function &GetSourceItemClass()
{
global $objItemTypes;
$objType = $objItemTypes->GetItem($this->Get("SourceType"));
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$c = new $classname;
}
else
$c = NULL;
if(is_object($c))
{
$c->LoadFromResourceId($this->Get("SourceId"));
}
return $c;
}
//Changes priority
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
} /*clsRelationship*/
class clsRelationshipList extends clsItemCollection
{
var $Page;
var $PerPage;
function clsRelationshipList($CategoryId=-1,$ItemId=-1)
{
$this->clsItemCollection();
$this->classname="clsRelationship";
$this->SourceTable = GetTablePrefix()."Relationship";
$this->Page=1;
$this->PerPage=20;
$this->AdminSearchFields = array("ItemName","ItemType","RelationType","Status");
$this->TargetItems = new clsItemCollection();
$this->TargetItems->classname="clsItemDB";
}
function GetNumPages()
{
global $objConfig;
return ceil($this->NumItems()/$this->PerPage);
}
function GetAdminPageLinkList($link_template,$url)
{
global $objConfig, $bb_var_list_update, $var_list_update, $var_list;
$NumPages = $this->GetNumPages();
$o = "";
if($this->Page>1)
{
$prev_url = $url."?env=".BuildEnv()."&lpn=".$this->Page-1;
$o = "<A HREF=\"$prev_url\"><<</A>";
}
for($p=1;$p<=$NumPages;$p++)
{
$t = admintemplate($link_template);
if($p!=$this->Page)
{
$href = $url."?env=".BuildEnv()."&lpn=".$p;
$o = "-<A HREF=\"$href\">$p</A>-";
}
else
{
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
}
if($this->Page<$NumPages)
{
$next_url = $url."?env=".BuildEnv()."&lpn=".$this->Page+1;
}
return $o;
}
function GetLimitSQL()
{
if($this->Page<1)
$this->Page=1;
if(is_numeric($this->PerPage))
{
$Start = ($this->Page-1)*$this->PerPage;
$limit = "LIMIT ".$Start.",".$this->PerPage;
}
else
$limit = NULL;
return $limit;
}
function LoadRelated($where,$orderBy,$custom_sql = null)
{
global $objSession;
$sql = isset($custom_sql) ? sprintf($custom_sql,$this->SourceTable) : "SELECT * FROM ".$this->SourceTable;
if(strlen(trim($orderBy))>0)
{
$orderBy = "Priority, ".$orderBy;
}
else
$orderBy = "Priority ";
if(strlen($where))
$sql = sprintf('%s WHERE %s',$sql,$where);
$sql = sprintf('%s ORDER BY %s',$sql,$orderBy);
$sql .= " ".$this->GetLimitSQL();
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
return $this->Query_Item($sql);
}
function CountRelated($where)
{
$res = 0;
$sql = "SELECT count(*) as mycount from ".$this->SourceTable." WHERE $where ";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$res = $rs->fields["mycount"];
return $res;
}
function Add($SourceId,$SourceType,$TargetId,$TargetType,
$Priority=0,$Enabled=1,$Type=0, $RelationId = -999)
{
$r = new clsRelationship();
$r->Set(array("SourceId","SourceType","TargetId","TargetType","Priority","Type","Enabled"),
array($SourceId,$SourceType,$TargetId,$TargetType,$Priority,$Type,$Enabled));
if ($RelationId != -999)
{
$r->Set("RelationshipId", $RelationId);
}
$r->tablename = $this->SourceTable;
$r->Create();
return $r;
}
function CopyToResource($OldSource,$NewSource)
{
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." WHERE SourceId=$OldSource";
$this->Query_Item($sql);
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->UnsetIdField();
$i->Set("SourceId",$NewSource);
$i->Create();
}
}
}
function PurgeEditTable($idfield = "")
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
- $sql = "DROP TABLE $edit_table";
+ $sql = "DROP TABLE IF EXISTS $edit_table";
$this->adodbConnection->Execute($sql);
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table WHERE SourceId='$ResourceId'";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["RelationshipId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
}
$idlist[] = $c->Get("RelationshipId");
$rs->MoveNext();
}
if(count($idlist)>0)
{
$sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId AND RelationshipId NOT IN (".implode(",",$idlist).")";
}
else
{
$sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId";
}
if((int)$GLOBALS["debuglevel"])
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
-// $this->adodbConnection->Execute("DROP TABLE $edit_table");
+// $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
}
?>
Property changes on: trunk/kernel/include/relationship.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/include/theme.php
===================================================================
--- trunk/kernel/include/theme.php (revision 270)
+++ trunk/kernel/include/theme.php (revision 271)
@@ -1,735 +1,735 @@
<?php
define('THEME_ERROR_1', 'Theme folder not writable');
define('THEME_ERROR_2', 'Template File Not Found');
class clsThemeFile extends clsItem
{
var $Contents;
var $Root;
var $Errors = Array(); // global template error messages (not db related)
function clsThemeFile($id=NULL)
{
$this->clsItem();
$this->tablename = GetTablePrefix()."ThemeFiles";
$this->id_field = "FileId";
$this->NoResourceId=1;
$this->Root = "";
$this->Contents = '';
if($id) $this->LoadFromDatabase($id);
}
function ThemeRoot()
{
if( !$this->Root )
{
$t = new clsTheme( $this->Get("ThemeId") );
$this->Root = $t->Get("Name");
}
return $this->Root;
}
function FullPath()
{
// need to rewrite (by Alex)
global $objConfig, $pathchar,$pathtoroot;
$path = $pathtoroot."themes".$pathchar.$this->ThemeRoot();
if(strlen(trim($this->Get("FilePath"))))
$path .= $pathchar.$this->Get("FilePath");
$path .= $pathchar.$this->Get("FileName");
//echo "Full Path is $path <br>\n";
return str_replace('//','/',$path);
}
function Get($name)
{
if($name == 'Contents')
return $this->Contents;
else
return parent::Get($name);
}
function Set($name, $value)
{
if( !is_array($name) )
{
$name = Array($name);
$value = Array($value);
}
$i = 0; $field_count = count($name);
while($i < $field_count)
{
if($name[$i] == 'Contents')
$this->Contents = $value[$i];
else
parent::Set($name[$i], $value[$i]);
$i++;
}
}
/*
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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 Delete()
{
$path = $this->FullPath();
if($this->debuglevel) echo "Trying to delete file [$path]<br>";
if( file_exists($path) ) @unlink($path);
parent::Delete();
}
function LoadFileContents($want_return = true)
{
global $objConfig,$pathchar;
$this->Contents = '';
$path = $this->FullPath();
if( file_exists($path) )
$this->Contents = file_get_contents($path);
else
$this->SetError(THEME_ERROR_2, 2); // template not found
if($want_return) return $this->Contents;
}
function SetError($msg, $code, $field = 'global_error')
{
$this->Errors[$field]['msg'] = $msg;
$this->Errors[$field]['code'] = $code;
}
function HasError()
{
return count($this->Errors) ? 1 : 0;
}
function ErrorMsg()
{
return $this->Errors['global_error']['msg'];
}
function SaveFileContents($filecontents, $new_file = false)
{
$path = $this->FullPath();
if( is_array($filecontents) ) $filecontents = implode("\n",$filecontents);
if( $this->IsWriteablePath($new_file) )
{
$fp = fopen($path,"w");
if($fp)
{
fwrite($fp,$filecontents);
fclose($fp);
return true;
}
}
return false;
}
function IsWriteablePath($new_file = false)
{
$path = $this->FullPath();
$path = str_replace('//','/',$path);
$ret = $new_file ? is_writable(dirname($path)): is_writable($path);
if(!$ret)
{
$this->SetError(THEME_ERROR_1, 1);
return false;
}
return $ret;
}
}
class clsThemeFileList extends clsItemCollection
{
var $Page;
var $PerPageVar;
var $ThemeId;
function clsThemeFileList($theme_id=NULL)
{
global $m_var_list;
$this->clsItemCollection();
$this->classname = "clsThemeFile";
$this->Page=(int)$m_var_list["p"];
$this->PerPageVar = "Perpage_ThemeFiles";
$this->SourceTable = GetTablePrefix()."ThemeFiles";
$this->AdminSearchFields = array("FileName","FilePath","Description");
$this->ThemeId=$theme_id;
//if($theme_id)
// $this->LoadFiles($theme_id);
}
function LoadFiles($id,$where="",$orderBy="")
{
global $objConfig;
$this->Clear();
$this->ThemeId=$id;
$sql = "SELECT * FROM ".$this->SourceTable. " WHERE ThemeId=$id ";
if(strlen(trim($where)))
$sql .= $where." ";
if(strlen(trim($orderBy)))
$sql .= "ORDER BY $orderBy";
if(strlen($this->PerPageVar))
{
$sql .= GetLimitSQL($this->Page,$objConfig->Get($this->PerPageVar));
}
//echo $sql;
return $this->Query_Item($sql);
}
function GetFileByName($path,$name,$LoadFromDB=TRUE)
{
$found = FALSE;
$f = FALSE;
//echo "Looking through ".$this->NumItems()." Files <br>\n";
if($this->NumItems()>0)
{
foreach($this->Items as $f)
{
if(($f->Get("FilePath")== $path) && ($f->Get("FileName")==$name))
{
$found = TRUE;
break;
}
}
}
if(!$found && $LoadFromDB)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ThemeId=".$this->ThemeId." AND FileName LIKE '$name' AND FilePath LIKE '$path'";
$rs = $this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$f =& $this->AddItemFromArray($data);
}
else
$f = FALSE;
}
return $f;
}
function AddFile($Path,$Name,$ThemeId,$Type,$Description,$contents=NULL)
{
$f = new clsThemeFile();
$f->Set(array("FilePath","FileName","ThemeId","FileType","Description"),
array($Path,$Name,$ThemeId,$Type,$Description));
$f->Create();
if($Contents!=NULL)
$f->SaveFileContents($Contents);
//echo $f->Get("FilePath")."/".$f->Get("FileName")."<br>\n";
return $f;
}
function EditFile($FileId,$Path,$Name,$ThemeId,$Type,$Description,$contents=NULL)
{
$f = $this->GetItem($FileId);
$f->Set(array("FilePath","FileName","ThemeId","FileType","Description"),
array($Path,$Name,$ThemeId,$Type,$Description));
$f->Update();
if($Contents!=NULL)
$f->SaveFileContents($Contents);
return $f;
}
function DeleteFile($FileId)
{
$f = $this->GetItem($FileId);
$f->Delete();
}
function DeleteAll()
{
$this->Clear();
$this->LoadFiles($this->ThemeId);
foreach($this->Items as $f)
$f->Delete();
$this->Clear();
}
function SetFileContents($FileId,$Contents)
{
$f = $this->GetItem($FileId);
$f->SaveFileContents($Contents);
}
function GetFileContents($FileId)
{
$f = $this->GetItem($FileId);
return $f->LoadFileContents();
}
function FindMissingFiles($path)
{
global $objConfig, $pathchar, $pathtoroot, $ttt_time;
$this->Clear();
$fullpath = $pathtoroot."themes/".$path;
$this->LoadFiles($this->ThemeId);
//assemble directoy file list
$files = filelist($fullpath, NULL, "tpl");
//assemble DB file list
$tt_inc=0;
$db_file_array=array(0 => '0');
foreach($this->Items as $f)
{
$db_file_array[$tt_inc]=$f->Get("FilePath").$f->Get("FileName");
$tt_inc++;
}
//iterate through all files in the directory
for($i=0;$i<count($files);$i++)
{
$file_path = dirname($files[$i]);
$file_path = substr($file_path,strlen($fullpath));
$file_base = basename($files[$i]);
//check if there is a matching file in the db
$res=array_search($file_path.$file_base,$db_file_array);
if(is_null($res) || $res === FALSE)
{ //add file to the DB if there isn't one there
if(strlen($file_base))
$this->AddFile($file_path,$file_base,$this->ThemeId,0,"");
}
}
}
}
RegisterPrefix("clsTheme","theme","kernel/include/theme.php");
class clsTheme extends clsParsedItem
{
var $Files;
var $FileCache;
var $IdCache;
var $ParseCacheDate;
var $ParseCacheTimeout;
function clsTheme($Id = NULL)
{
$this->clsParsedItem($Id);
$this->tablename = GetTablePrefix()."Theme";
$this->id_field = "ThemeId";
$this->NoResourceId=1;
$this->TagPrefix="theme";
$this->Files = new clsThemeFileList($Id);
$this->FileCache = array();
$this->IdCache = array();
$this->ParseCacheDate=array();
$this->ParseCacheTimeout = array();
if($Id)
$this->LoadFromDatabase($Id);
}
function ThemeDirectory()
{
global $objConfig, $pathchar, $pathtoroot;
$path = $pathtoroot."themes/".strtolower($this->Get("Name"));
return $path;
}
function UpdateFileCacheData($id,$CacheDate)
{
$sql = "UPDATE ".GetTablePrefix()."ThemeFiles SET CacheDate=$CacheDate WHERE FileId=$id";
$this->adodbConnection->Execute($sql);
}
function LoadFileCache()
{
$sql = "SELECT * FROM ".GetTablePrefix()."ThemeFiles WHERE ThemeId=".$this->Get("ThemeId");
$rs = $this->adodbConnection->Execute($sql);
while($rs && ! $rs->EOF)
{
//$this->Files->AddItemFromArray($rs->fields,TRUE);
$f = $rs->fields["FileName"];
$t = $rs->fields["FilePath"];
if(strlen($t))
$t .= "/";
$parts = pathinfo($f);
$fname = substr($f,0,(strlen($parts["extension"])+1)*-1);
// echo "Name: $fname<br>\n";
$t .= $fname;
$this->FileCache[$t] = $rs->fields["FileId"];
$this->IdCache[$rs->fields["FileId"]] = $t;
/*
if($rs->fields["EnableCache"]) // no such field in this table (commented by Alex)
{
$this->ParseCacheDate[$rs->fields["FileId"]] = $rs->fields["CacheDate"];
$this->ParseCacheTimeout[$rs->fields["FileId"]] = $rs->fields["CacheTimeout"];
}
*/
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
adodb_movenext($rs);
else
$rs->MoveNext();
}
//echo "<PRE>"; print_r($this->IdCache); echo "</PRE>";
}
function GetTemplateById($FileId)
{
if(count($this->FileCache)==0)
$this->LoadFileCache();
$f = $this->IdCache[$FileId];
return $f;
}
function GetTemplateId($t)
{
if( count($this->IdCache) == 0 ) $this->LoadFileCache();
$f = isset( $this->FileCache[$t] ) ? $this->FileCache[$t] : '';
return is_numeric($f) ? $f : $t;
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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();
$this->Files = new clsThemeFileList($Id);
return true;
}
function GetFileList($where,$OrderBy)
{
global $objConfig, $pathchar;
$this->Files->PerPageVar="";
$this->Files->ThemeId = $this->Get("ThemeId");
$this->Files->LoadFiles($this->Get("ThemeId"),$where,$OrderBy);
}
function VerifyTemplates()
{
if(!is_object($this->Files))
$this->Files = new clsThemeFileList($this->Get("ThemeId"));
$this->Files->ThemeId = $this->Get("ThemeId");
$this->Files->FindMissingFiles(strtolower($this->Get("Name")));
}
function EditTemplateContents($FileId,$Contents)
{
$this->Files->SetFileContents($FileId,$Contents);
}
function ReadTemplateContents($FileId)
{
return $this->Files->GetFileContents($FileId);
}
function CreateDirectory()
{
$dir = $this->ThemeDirectory();
if(!is_dir($dir))
mkdir($dir);
}
function Delete()
{
$this->Files->DeleteAll();
$dir = $this->ThemeDirectory();
if(is_writable($dir))
@rmdir($dir);
parent::Delete();
}
function AdminIcon()
{
global $imagesURL;
$file = $imagesURL."/itemicons/icon16_theme";
if($this->Get("PrimaryTheme")==1)
{
$file .= "_primary.gif";
}
else
{
if($this->Get("Enabled")==0)
{
$file .= "_disabled";
}
$file .= ".gif";
}
return $file;
}
function ParseObject($element)
{
global $var_list_update, $objSession;
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
$ret = $this->Get("ThemeId");
break;
case "name": // was "nane"
$ret = $this->Get("Name");
break;
case "description":
$ret = $this->Get("Description");
break;
case "adminicon":
$ret = $this->AdminIcon();
break;
case "directory":
$ret = $this->ThemeDirectory();
break;
case "select_url":
$var_list_update["t"] = "index";
$ret = GetIndexURL()."?env=".BuildEnv()."&Action=m_set_theme&ThemeId=".$this->Get("ThemeId");
break;
case "selected":
$ret = "";
if($this->Get("Name")==$objSession->Get("Theme"))
$ret = "SELECTED";
break;
default:
$tag = $this->TagPrefix."_".$field;
$ret = ""; $this->parsetag($tag);
break;
}
}
return $ret;
}
}
class clsThemeList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsThemeList($id=NULL)
{
$this->clsItemCollection();
$this->classname="clsTheme";
$this->SourceTable=GetTablePrefix()."Theme";
$this->PerPageVar = "Perpage_Themes";
$this->AdminSearchFields = array("Name","Description");
}
function LoadThemes($where="",$order="")
{
global $objConfig;
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(strlen(trim($where)))
$sql .= "WHERE ".$where." ";
if(strlen(trim($orderBy)))
$sql .= "ORDER BY $orderBy";
$sql .= GetLimitSQL($this->Page,$objConfig->Get($this->PerPageVar));
return $this->Query_Item($sql);
}
function AddTheme($Name,$Description,$Enabled,$Primary,$CacheTimeout=3600)
{
$t = new clsTheme();
$t->tablename = $this->SourceTable;
$t->Set(array("Name","Description","Enabled","PrimaryTheme","CacheTimeout"),
array($Name,$Description,$Enabled,$Primary,$CacheTimeout));
$t->Create();
if($Primary==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0 WHERE ThemeId != ".$t->Get("ThemeId");
$this->adodbConnection->Execute($sql);
}
return $t;
}
function EditTheme($ThemeId,$Name,$Description,$Enabled,$Primary, $CacheTimeout)
{
$t = $this->GetItem($ThemeId);
$t->Set(array("Name","Description","Enabled","PrimaryTheme","CacheTimeout"),
array($Name, $Description, $Enabled, $Primary, $CacheTimeout));
$t->Dirty();
$t->Update();
if($Primary==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0 WHERE ThemeId!=$ThemeId";
$this->adodbConnection->Execute($sql);
}
return $t;
}
function DeleteTheme($ThemeId)
{
$t = $this->GetItem($ThemeId);
$t->Delete();
}
function SetPrimaryTheme($ThemeId)
{
$theme = $this->GetItem($ThemeId);
if($theme->Get("Enabled")==1)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryTheme=0";
$this->adodbConnection->Execute($sql);
$theme->Set("PrimaryTheme","1");
$theme->Update();
}
}
function GetPrimaryTheme($field="ThemeId")
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE PrimaryTheme=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$l = $rs->fields[$field];
}
else
$l = 0;
return $l;
}
function CreateMissingThemes()
{
global $objConfig,$pathchar, $pathtoroot;
$path = $pathtoroot."themes";
$themes = array();
if ($dir = @opendir($path))
{
while (($file = readdir($dir)) !== false)
{
if($file !="." && $file !=".." && substr($file,0,1)!="_")
{
if(is_dir($path."/".$file))
{
$file = strtolower($file);
$themes[$file]=0;
}
}
}
}
closedir($dir);
$this->Clear();
$this->Query_Item("SELECT * FROM ".$this->SourceTable);
foreach($this->Items as $i)
{
$n = strtolower($i->Get("Name"));
$themes[$n] = $i->Get("ThemeId");
}
$names = array_keys($themes);
for($i=0;$i<count($names);$i++)
{
$name = $names[$i];
$value = $themes[$name];
if($value==0)
{
$t = $this->AddTheme($name,"New Theme",0,0);
$themes[$name] = $t->Get("ThemeId");
}
}
$where = implode(",",array_values($themes));
$sql = "DELETE FROM ".$this->SourceTable." WHERE ThemeId NOT IN ($where)";
}
function CopyFromEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["ThemeId"]>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
$c->CreateDirectory();
}
if($c->Get("PrimaryTheme"))
{
$this->SetPrimaryTheme($c->Get("ThemeId"));
}
$rs->MoveNext();
}
$this->adodbConnection->Execute($sql);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- $this->adodbConnection->Execute("DROP TABLE $edit_table");
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
}
?>
Property changes on: trunk/kernel/include/theme.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/include/portalgroup.php
===================================================================
--- trunk/kernel/include/portalgroup.php (revision 270)
+++ trunk/kernel/include/portalgroup.php (revision 271)
@@ -1,497 +1,497 @@
<?php
class clsPortalGroup extends clsParsedItem
{
var $UserCount;
function clsPortalGroup($GroupId=NULL)
{
$this->clsParsedItem($Groupid);
$this->tablename=GetTablePrefix()."PortalGroup";
$this->type=7;
$this->BasePermission="GROUP";
$this->id_field = "GroupId";
if($GroupId)
$this->LoadFromDatabase($GroupId);
}
function Validate()
{
global $objSession, $Errors;
$dataValid = true;
if(!isset($this->m_Name) || $this->m_Name == "")
{
$Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function HasSystemPermission($PermissionName)
{
$GroupId = $this->Get("GroupId");
$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE GroupId=$GroupId AND Permission='$PermissionName' AND type=1";
$result = $this->adodbConnection->Execute($sql);
if($result && !$result->EOF)
{
$this->SysPermCache[$PermissionName] = (int)$result->fields["PermissionValue"];
return (int)$result->fields["PermissionValue"];
}
else
return -1;
}
/* set $Value to -1 to delete the permission row from the DB */
function SetSystemPermission($PermName,$Value)
{
//echo "Setting $PermName to $Value<br>\n";
$oldval = $this->HasSystemPermission($PermName);
if($Value != $oldval)
{
if($Value>-1)
{
if($oldval>-1)
{
$sql = "UPDATE ".GetTablePrefix()."Permissions SET PermissionValue=$Value ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
}
else
{
$sql = "INSERT INTO ".GetTablePrefix()."Permissions (Permission, GroupId, PermissionValue, Type, CatId) ";
$sql .="VALUES ('$PermName',".$this->Get("GroupId").",$Value,1,0)";
}
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
}
else
{
$sql = "DELETE FROM ".GetTablePrefix()."Permissions ";
$sql .=" WHERE Type=1 AND Permission='$PermName' AND GroupId=".$this->Get("GroupId");
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
}
}
}
function CheckPermission($permissionName)
{
//Check permission and if needs approval set approval
global $objSession, $Errors;
if(!$objSession->HasSystemPermission($permissionName))
{
//$Errors->AddError("error.AccessDenied","","","",get_class($this),"CheckPermission");
return false;
}
return true;
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = "SELECT * FROM ".$this->tablename." WHERE GroupId = $Id";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
$this->Clean();
return true;
}
function AddUser($UserId,$PrimaryGroup=0)
{
// add user to group OR just updates it's status there
$db =& $this->adodbConnection;
$table = GetTablePrefix().'UserGroup';
$group_id = $this->Get('GroupId');
$sql_patterns['check'] = 'SELECT PortalUserId FROM %s WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['reset_primary'] = 'UPDATE %s SET PrimaryGroup = 0 WHERE PortalUserId = %s';
$sql_patterns['set_primary'] = 'UPDATE %s SET PrimaryGroup = 1 WHERE GroupId = %s AND PortalUserId = %s';
$sql_patterns['add_to_group'] = 'INSERT INTO %s (PortalUserId,GroupId,PrimaryGroup) VALUES (%s, %s, %s)';
$tmp_sql = sprintf($sql_patterns['check'], $table, $group_id, $UserId);
$check_result = $db->GetOne($tmp_sql);
if(!$check_result)
{
// user is not a memeber of this group
$GroupCount = TableCount($table,"PortalUserId = $UserId", 0);
if(!$PrimaryGroup) $PrimaryGroup = ($GroupCount == 0) ? 1 : 0; // reset primary status if not already
$tmp_sql = sprintf($sql_patterns['add_to_group'], $table, $UserId, $group_id, $PrimaryGroup);
$db->Execute($tmp_sql);
}
if($PrimaryGroup)
{
$tmp_sql = sprintf($sql_patterns['reset_primary'], $table, $UserId);
$db->Execute($tmp_sql);
$tmp_sql = sprintf($sql_patterns['set_primary'], $table, $group_id, $UserId);
$db->Execute($tmp_sql);
}
}
function DeleteUser($UserId)
{
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=$UserId AND GroupId=".$this->Get("GroupId");
$this->adodbConnection->Execute($sql);
}
function GetCustomField( $fieldName)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Get field is required in order to set custom field values","","clsPortalGroup","GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_UserId,"portaluser",$fieldName);
}
function SetCustomField( $fieldName, $value)
{
global $Errors;
if(!isset($this->m_UserId))
{
$Errors->AddError("error.AppError",NULL,"Set field is required in order to set custom field values","","clsPortalGroup","SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_UserId,"portaluser",$fieldName,$value);
}
function GetUserCount()
{
if(!is_numeric($this->UserCount))
{
$sql = "SELECT count(*) as UserCount FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
$users = $rs->fields["UserCount"];
$this->UserCount = (int)$users;
}
return $this->UserCount;
}
function GetUserList()
{
$sql = "SELECT * FROM ".GetTablePrefix()."UserGroup WHERE GroupId=".$this->Get("GroupId");
$rs = $this->adodbConnection->Execute($sql);
$res = array();
while($rs && !$rs->EOF)
{
$res[] = $rs->fields["PortalUserId"];
$rs->MoveNext();
}
return $res;
}
function parsetag($tag)
{
global $var_list_update, $objConfig;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "group_id":
return $this->Get("GroupId");
break;
case "group_name":
return $this->Get("Name");
break;
case "group_desc":
return $this->Get("Description");
break;
case "group_date":
return LangDate($this->Get("CreatedOn"));
break;
case "group_name":
return $this->Get("Name");
break;
case "group_enabled":
return $this->Get("Enabled");
break;
case "group_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "group_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "group_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
case "group_system":
if ($this->Get("System") == 1)
return "System";
else
return "User Defined";
break;
case "group_status":
if ($this->Get("Enabled") == 1)
return "Enabled";
else
return "Disabled";
break;
default:
if (substr($tag, 0, 6) == "custom")
return Users_Custom($this->Get("ResourceId"), $tag);
else
return "Undefined:$tagname";
break;
}
}
}
class clsGroupList extends clsItemCollection
{
var $Page;
function clsGroupList()
{
$this->clsItemCollection();
$this->classname = "clsPortalGroup";
$this->SetTable('live', GetTablePrefix()."PortalGroup");
$this->AdminSearchFields = array("name");
$this->id_field = "GroupId";
}
function NumGroups()
{
return $this->NumItems();
}
function GetGroup($GroupID)
{
return $this->GetItem($GroupID);
}
function GetPersonalGroup($UserLogin)
{
$n = "_".$UserLogin;
$g = $this->GetItemByField("Name",$n);
return $g;
}
function LoadGroups($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Groups")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Groups");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Groups");
}
else
$limit = NULL;
if(strlen($where)==0)
$where = "1";
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
//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)
{
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);
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 $edit_table");
+ @$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.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/include/image.php
===================================================================
--- trunk/kernel/include/image.php (revision 270)
+++ trunk/kernel/include/image.php (revision 271)
@@ -1,1130 +1,1132 @@
<?php
class clsImage extends clsParsedItem
{
var $Pending;
function clsImage($id=NULL)
{
global $objSession;
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."Images";
$this->Pending = FALSE;
$this->id_field = "ImageId";
$this->type=-30;
$this->TagPrefix = "image";
$this->NoResourceId=1;
if($id)
$this->LoadFromDatabase($id);
//$this->SetDebugLevel(0);
}
function GetFileName($thumb = 0)
{
global $pathtoroot;
if($thumb)
{
$p = $this->Get("ThumbPath");
}
else
{
$p = $this->Get("LocalPath");
if(!strlen($p) && $this->Get("SameImages"))
{
$p = $this->Get("ThumbPath");
}
}
if(strlen($p))
{
$parts = pathinfo($pathtoroot.$p);
$filename = $parts["basename"];
}
else
$filename = "";
return $filename;
}
function GetImageDir()
{
global $pathtoroot;
$p = $this->Get("ThumbPath");
if(strlen($p))
{
$parts = pathinfo($pathtoroot.$p);
$d = $parts["dirname"]."/";
}
if($this->Pending)
$d .= "pending/";
return $d;
}
function Delete()
{
$this->DeleteLocalImage();
parent::Delete();
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ImageId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false || $result->EOF)
{
$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 LoadFromResource($Id,$ImageIndex)
{
global $Errors;
if(!isset($Id) || !isset($ImageIndex))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResource");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'AND ImageIndex = '%s'",$Id,$ImageIndex);
$result = $this->adodbConnection->Execute($sql);
if ($result === false || $result->EOF)
{
// $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResource");
return false;
}
$data = $result->fields;
$this->SetFromArray($data);
return true;
}
function LocalImageExists()
{
global $objConfig, $pathtoroot;
$result=FALSE;
if($this->Get("LocalImage")==1 && $this->Get("SameImages")==0)
{
//$imagepath = $pathtoroot.$this->Get("LocalPath");
$imagepath = $this->GetImageDir().$this->GetFileName();
// echo "PATH: ".$this->GetImageDir()."; FILE: ".$this->GetFileName()."<BR>";
if(strlen($imagepath)>0)
{
$result = file_exists($imagepath);
}
}
return $result;
}
function LocalThumbExists()
{
$result=FALSE;
global $objConfig, $pathtoroot;
if($this->Get("LocalThumb")==1)
{
//$imagepath = $pathtoroot.$this->Get("ThumbPath");
$imagepath = $this->GetImageDir().$this->GetFileName(1);
if(strlen($imagepath)>0)
{
$result = file_exists($imagepath);
}
}
return $result;
}
function DeleteLocalImage($Thumb=TRUE,$Full=TRUE)
{
global $pathtoroot;
if($Full)
{
if($this->LocalImageExists())
{
$filename = $this->GetImageDir().$this->GetFileName();
// echo "FULL: $filename<BR>\n";
@unlink($filename);
}
}
if($Thumb)
{
if($this->LocalThumbExists())
{
$filename = $this->GetImageDir().$this->GetFileName(1);
// echo "THUMB: $filename<BR>\n";
@unlink($filename);
}
}
}
function StoreUploadedImage($file, $rewrite_name=1,$DestDir,$IsThumb=0,$IsUpload=TRUE)
{
/* move the uploaded image to its final location and update the LocalPath property */
/* returns the destination filename on success */
global $objConfig,$pathtoroot;
$Dest_Dir = $DestDir;
if($this->Pending)
$Dest_Dir .= "pending/";
if(((int)$file["error"]==0) && (substr($file["type"],0,6)=="image/"))
{
$parts = pathinfo($file["name"]);
$ext = strtolower($parts["extension"]);
if((int)$_GLOBALS["debuglevel"])
echo "Processing ".$file["tmp_name"]."<br>\n";
if($rewrite_name==1)
{
if($IsThumb)
$filename = "th_";
$filename .= $this->Get("ResourceId")."_".$this->Get("ImageIndex").".".$ext;
}
else
{
$filename = $file["name"];
}
$destination = $pathtoroot.$Dest_Dir.$filename;
if((int)$_GLOBALS["debuglevel"])
echo $file["tmp_name"]."=>".$destination."<br>\n";
if(IsUpload==TRUE)
{
$result = @move_uploaded_file($file["tmp_name"],$destination);
}
else
$result = copy($file["tmp_name"],$destination);
if($result)
{
return $Dest_Dir.$filename;
}
else
return "";
}
else
return "";
}
function CopyToPending()
{
global $pathtoroot;
$ThumbPath = (strlen($this->Get("ThumbPath"))>0) ? $pathtoroot.$this->Get("ThumbPath") : '';
$FullPath = strlen($this->Get("LocalPath")) ? $pathtoroot.$this->Get("LocalPath") : '';
$dest = $this->GetImageDir()."pending/";
// echo "DESTIN DIR: $dest<BR>";
// echo "THUMB PATH: $ThumbPath <BR>";
if(strlen($ThumbPath))
{
if(file_exists($ThumbPath))
{
$p = pathinfo($ThumbPath);
$d = $dest.$p["basename"];
if(file_exists($d))
unlink($d);
copy($ThumbPath,$d);
}
}
if(strlen($FullPath))
{
if(file_exists($FullPath))
{
$p = pathinfo($FullPath);
$d = $dest.$p["basename"];
if(file_exists($d))
unlink($d);
copy($FullPath,$d);
}
}
}
function CopyFromPending()
{
global $pathtoroot,$pathchar;
$ThumbPath = $this->Get("ThumbPath");
$FullPath = $this->Get("LocalPath");
// $src = $this->GetImageDir()."pending/";
$src = $this->GetImageDir();
if(strlen($ThumbPath))
{
if(strpos($ThumbPath,"pending/"))
{
if(file_exists($pathtoroot.$ThumbPath))
{
$path = pathinfo($pathtoroot.$ThumbPath);
$p = explode("/",$ThumbPath);
unset($p[count($p)-2]);
$d = $pathtoroot.implode("/",$p);
if(file_exists($d))
unlink($d);
copy($pathtoroot.$ThumbPath,$d);
unlink($pathtoroot.$ThumbPath);
}
}
}
if(strlen($FullPath))
{
if(file_exists($pathtoroot.$FullPath))
{
if(strpos($FullPath,"pending/"))
{
$path = pathinfo($pathtoroot.$FullPath);
$p = explode("/",$FullPath);
unset($p[count($p)-2]);
$d = $pathtoroot.implode("/",$p);
if(file_exists($d))
unlink($d);
copy($pathtoroot.$FullPath,$d);
unlink($pathtoroot.$FullPath);
}
}
}
}
function DeleteFromPending()
{
+ global $pathtoroot;
$ThumbPath = $pathtoroot.$this->Get("ThumbPath");
$FullPath = $pathtoroot.$this->Get("LocalPath");
$src = $this->GetImageDir()."pending/";
$p = pathinfo($ThumbPath);
$d = $src.$p["basename"];
if(file_exists($d))
@unlink($d);
$p = pathinfo($FullPath);
$d = $src.$p["basename"];
if(file_exists($d))
@unlink($d);
}
function RenameFiles($OldResId,$NewResId)
{
global $pathtoroot;
if($this->Pending)
{
$ThumbPath = $this->GetImageDir().$this->GetFileName(TRUE);
}
else
$ThumbPath = $pathtoroot.$this->Get("ThumbPath");
$parts = pathinfo($ThumbPath);
$ext = $parts["extension"];
$pending="";
if($this->Pending)
{
$pending="pending/";
$FullPath = $this->GetImageDir().$this->GetFileName(FALSE);
}
else
$FullPath = $pathtoroot.$this->Get("LocalPath");
$NewThumb = $pathtoroot."kernel/images/".$pending."th_$NewResId_".$this->Get("ImageIndex").".$ext";
$NewFull = $pathtoroot."kernel/images/".$pending."$NewResId_".$this->Get("ImageIndex").".$ext";
if(file_exists($ThumbPath))
{
@rename($ThumbPath,$NewThumb);
}
if(file_exists($FullPath))
{
@rename($FullPath,$NewFull);
}
}
function ReplaceImageFile($file)
{
global $objConfig;
if($file["error"]==0)
{
$this->DeleteLocalImage();
move_uploaded_file($file,$this->Get("LocalPath"));
}
}
function FullURL($ForceNoThumb=FALSE,$Default="kernel/images/noimage.gif")
{
global $rootURL, $objConfig,$pathtoroot;
if($this->Get("SameImages") && !$ForceNoThumb)
return $this->ThumbURL();
if(strlen($this->Get("Url")))
return $this->Get("Url");
if($this->Get("LocalImage")=="1")
{
$url = $this->Get("LocalPath");
//$url = $this->GetImageDir().$this->GetFileName();
if(file_exists($pathtoroot.$url))
{
if(strlen($url))
{
$url = $rootURL.$url;
return $url;
}
else
{
if(strlen($Default))
$url = $rootURL.$Default;
return $url;
}
}
else
{
if(strlen($Default))
{
return $rootURL.$Default;
}
else
return "";
}
}
else
{
if(strlen($Default))
{
return $rootURL.$Default;
}
else
return "";
}
}
function ThumbURL()
{
global $rootURL, $pathtoroot, $objConfig;
if(strlen($this->Get("ThumbUrl")))
return $this->Get("ThumbUrl");
if($this->Get("LocalThumb")=="1")
{
$url = $this->Get("ThumbPath");
//$url = $this->GetImageDir().$this->GetFileName();
if(file_exists($pathtoroot.$url))
{
if(strlen($url))
{
$url = $rootURL.$url;
}
else
$url = $rootURL."kernel/images/noimage.gif";
return $url;
}
else
return $rootURL."kernel/images/noimage.gif";
}
else
return $rootURL."kernel/images/noimage.gif";
}
function ParseObject($element)
{
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "name":
$ret = $this->Get("Name");
break;
case "alt":
$ret = $this->Get("AltName");
break;
case "full_url":
$ret = $this->FullURL();
break;
case "thumb_url":
$ret = $this->ThumbURL();
break;
}
}
else
$ret = $element->Execute();
return $ret;
}
function parsetag($tag)
{
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "image_name":
$ret = $this->Get("Name");
break;
case "image_alt":
$ret = $this->Get("AltName");
break;
case "image_url":
$ret = $this->FullURL();
break;
case "thumb_url":
$ret = $this->ThumbURL();
break;
}
return $ret;
}
//Changes priority
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
function GetMaxPriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function GetMinPriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MIN(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function UpdatePriority()
{
$SourceId = $this->Get("ResourceId");
$sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ReourceId=$SourceId";
$result = $this->adodbConnection->Execute($sql);
$this->Set("Priority", $result->fields["p"]+1);
}
}
class clsImageList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsImageList()
{
$this->clsItemCollection();
$this->PerPageVar = "Perpage_Images";
$this->SourceTable = GetTablePrefix()."Images";
$this->classname = "clsImage";
}
function LoadImages($where="",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Images")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Images");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Images");
}
else
$limit = NULL;
$this->QueryItemCount=TableCount("Images",$where,0);
//echo $this->QueryItemCount."<br>\n";
if(strlen(trim($orderBy))>0)
{
$orderBy = "Priority DESC, ".$orderBy;
}
else
$orderBy = "Priority DESC";
return $this->Query_Images($where,$orderBy,$limit);
}
function Query_Images($whereClause,$orderByClause=NULL,$limit=NULL)
{
global $objSession, $Errors;
$sql = "SELECT * FROM ".$this->SourceTable;
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause) && strlen(trim($orderByClause))>0)
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if(isset($limit) && strlen(trim($limit)))
$sql .= " ".$limit;
//echo $sql;
return $this->Query_Item($sql);
}
function &Add($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
$SameImages=0, $ImageId=-999)
{
if($DefaultImg==1)
{
$sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=$ResourceId";
$this->adodbConnection->Execute($sql);
}
$img = new clsImage();
$img->tablename = $this->SourceTable;
$img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
"Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
array($Name,$Alt,$ResourceId,$LocalImage,$LocalThumb,
$Url,$ThumbUrl,$Enabled,$Priority,$DefaultImg,$ImageIndex,$SameImages));
if ($ImageId != -999)
{
$img->Set("ImageId", $ImageId);
}
if((int)$ImageIndex==0)
$img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
$img->Create();
array_push($this->Items,$img);
return $img;
}
function Edit($ImageId,$Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
$SameImages=0)
{
$img = $this->GetItem($ImageId);
if((int)$ImageIndex==0)
$ImageIndex = $img->Get("ImageIndex");
if(!strlen($ThumbUrl) && !$LocalThumb)
$ThumbUrl = $img->Get("ThumbUrl");
$img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
"Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
array($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
$Url, $ThumbUrl, $Enabled, $Priority, $DefaultImg, $ImageIndex,$SameImages));
if((int)$ImageIndex==0)
$img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
$img->Update();
if($DefaultImg==1)
{
$sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=".$ResourceId." AND ImageId !=$ImageId";
$this->adodbConnection->Execute($sql);
}
array_push($this->Items,$img);
return $img;
}
function Delete_Image($ImageId)
{
$i = $this->GetItem($ImageId);
$i->Delete();
}
function DeleteResource($ResourceId)
{
$this->Clear();
$images = $this->Query_Images("ResourceId=".$ResourceId);
if(is_array($images))
{
foreach($images as $i)
{
$i->Delete();
}
}
}
function LoadResource($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId";
$this->Query_Item($sql);
}
function CopyResource($SourceId,$DestId)
{
global $pathtoroot;
$this->Clear();
$this->LoadResource($SourceId);
foreach($this->Items as $i)
{
if($i->Get("LocalThumb"))
{
$f = $pathtoroot.$i->Get("ThumbPath");
if(file_exists($f))
{
$p = pathinfo($f);
$dir = $p["dirname"];
$ext = $p["extension"];
$newfile = $dir."/th_".$DestId."_".$i->Get("ImageIndex").".".$ext;
if(file_exists($newfile))
@unlink($newfile);
// echo $f." -> ".$newfile;
copy($f,$newfile);
}
}
if($i->Get("LocalImage"))
{
$f = $pathtoroot.$i->Get("LocalPath");
if(file_exists($f))
{
$p = pathinfo($f);
$dir = $p["dirname"];
$ext = $p["extension"];
$newfile = $dir."/".$DestId."_".$i->Get("ImageIndex").".".$ext;
if(file_exists($newfile))
@unlink($newfile);
// echo $f." -> ".$newfile;
copy($f,$newfile);
}
}
}
parent::CopyResource($SourceId,$DestId);
$this->Clear();
$this->LoadResource($DestId);
foreach($this->Items as $img)
{
if($img->Get("LocalThumb"))
{
$f = str_replace("th_$SourceId","th_$DestId",$img->Get("ThumbPath"));
$img->Set("ThumbPath",$f);
}
if($img->Get("LocalImage"))
{
$f = str_replace("/".$SourceId."_","/".$DestId."_",$img->Get("LocalPath"));
$img->Set("LocalPath",$f);
}
$img->Update();
}
}
function GetImageByResource($ResourceId,$Index)
{
$found=FALSE;
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
if($i->Get("ResourceID")==$ResourceId and ($i->Get("ImageIndex")==$Index))
{
$found=TRUE;
break;
}
}
}
if(!$found)
{
$i = NULL;
$i = new clsImage();
if($i->LoadFromResource($ResourceId,$Index))
{
array_push($this->Items, $i);
}
else
unset($i);
}
if(is_object($i))
{
return $i;
}
else
return FALSE;
}
function &GetDefaultImage($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND DefaultImg=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && ! $rs->EOF)
{
$data = $rs->fields;
$img= new clsImage();
$img->SetFromArray($data);
$img->Clean();
return $img;
}
else
return FALSE;
}
function HandleImageUpload($FILE,$ResourceId,$RelatedTo,$DestDir, $Name="",$AltName="",$IsThumb=0)
{
global $objConfig;
$img = $this->GetImageByResource($ResourceId,$RelatedTo);
if(is_object($img) && $RelatedTo>0)
{
$img->Set("LocalImage",1);
$img->Set("Name",$Name);
$img->Set("AltName",$AltName);
$img->Set("IsThumbnail",$IsThumb);
$dest = $img->StoreUploadedImage($FILE,1,$DestDir);
if(strlen($dest))
{
$img->Set("Url", $objConfig->Get("Site_Path").$dest);
$img->Update();
}
}
else
{
$img=$this->NewLocalImage($ResourceId,$RelatedTo,$Name,$AltName,$IsThumb,$FILE,$DestDir);
}
return $img;
}
function GetResourceImages($ResourceId)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$img = new clsImage();
$img->LoadFromResource($ResourceId,$rs->fields["RelatedTo"]);
array_push($this->Images,$img);
$rs->MoveNext();
}
}
function GetResourceThumbnail($ResourceId)
{
$found=FALSE;
foreach($this->Images as $img)
{
if($img->Get("ResourceId")==$ResourceId && $img->Get("IsThumbnail")==1)
{
$found=TRUE;
break;
}
}
if($found)
{
return $img;
}
else
return FALSE;
}
function &GetImageByName($ResourceId,$name)
{
$found = FALSE;
foreach($this->Items as $img)
{
if($img->Get("ResourceId")==$ResourceId && $img->Get("Name")==$name)
{
$found=TRUE;
break;
}
}
if($found)
{
return $img;
}
else
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND Name LIKE '$name'";
//echo $sql;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$img = $this->AddItemFromArray($rs->fields);
return $img;
}
else
return FALSE;
}
}
function CopyToPendingFiles()
{
$sql = "SELECT * FROM ".$this->SourceTable;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
if(strlen($i->Get("LocalImage")) || strlen($i->Get("LocalThumb")))
{
$i->CopyToPending();
}
}
}
function CopyFromPendingFiles($edit_table)
{
$sql = "SELECT * FROM ".$edit_table;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
## Delete original Images
$OrgImage = new clsImage($i->Get("ImageId"));
$OrgImage->DeleteLocalImage();
if($i->Get("LocalImage") || $i->Get("LocalThumb"))
{
$i->CopyFromPending();
- $t = $i->Get("LocalPath");
+ $t = $i->Get("LocalPath");
+
$p = pathinfo($t);
$p_arr = explode("/", $p['dirname']);
if (eregi("pending", $p_arr[count($p_arr)-1]))
{
unset($p_arr[count($p_arr)-1]);
$p['dirname'] = implode("/", $p_arr);
$LocalPath = $p['dirname']."/".$p['basename'];
$i->Set("LocalPath", $LocalPath);
}
$t = $i->Get("ThumbPath");
$p = pathinfo($t);
$p_arr = explode("/", $p['dirname']);
if (eregi("pending", $p_arr[count($p_arr)-1]))
{
unset($p_arr[count($p_arr)-1]);
$p['dirname'] = implode("/", $p_arr);
$ThumbPath = $p['dirname']."/".$p['basename'];
$i->Set("ThumbPath", $ThumbPath);
}
$i->tablename = $edit_table;
$update = 1;
}
## Empty the fields if are not used
if (!$i->Get("LocalImage"))
{
$i->Set("LocalPath", "");
$update = 1;
}
if (!$i->Get("LocalThumb"))
{
$i->Set("ThumbPath", "");
$update = 1;
}
if ($update)
$i->Update();
}
}
function DeletePendingFiles($edit_table)
{
$sql = "SELECT * FROM ".$edit_table;
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
$i->DeleteFromPending();
}
}
function CopyToEditTable($idfield, $idlist)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
if(is_array($idlist))
{
$list = implode(",",$idlist);
}
else
$list = $idlist;
$query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
$insert = "CREATE TABLE ".$edit_table." ".$query;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($insert);
$this->SourceTable = $edit_table;
$this->CopyToPendingFiles();
$this->UpdateFilenamesToPendings();
}
function UpdateFilenamesToPendings()
{
global $objSession;
$edit_table = $this->SourceTable;
$sql = "SELECT * FROM ".$edit_table." WHERE (LocalPath!='' AND LocalPath IS NOT NULL) OR (ThumbPath!='' AND ThumbPath IS NOT NULL)";
$this->Clear();
$this->Query_Item($sql);
foreach($this->Items as $i)
{
$set = "";
$ImageId = $i->Get("ImageId");
## Update Local Image Path -> add "pending/" to PATH
if (strlen($i->Get("LocalPath")))
{
$p = pathinfo($i->Get("LocalPath"));
if (!eregi("/pending $", $p['dirname']))
{
$LocalPath = $p['dirname']."/pending/".$p['basename'];
$set = "SET LocalPath='$LocalPath'";
}
}
// echo "LocalImage: ".$i->Get("LocalImage").", PATH: ".$i->Get("LocalPath")."<BR>";
## Update Local Thumb Path -> add "pending/" to PATH
if (strlen($i->Get("ThumbPath")))
{
$p = pathinfo($i->Get("ThumbPath"));
if (!eregi("/pending $", $p['dirname']))
{
$LocalThumb = $p['dirname']."/pending/".$p['basename'];
if (strlen($set))
$set.= ", ThumbPath='$LocalThumb'";
else
$set = "SET ThumbPath='$LocalThumb'";
}
}
// echo "LocalThumb: ".$i->Get("LocalThumb").", PATH: ".$i->Get("ThumbPath")."<BR>";
if (strlen($set))
{
$sql = "UPDATE $edit_table $set WHERE ImageId=$ImageId";
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
$this->adodbConnection->Execute($sql);
}
}
}
function CopyFromEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$dummy =& $this->GetDummy();
if( !$dummy->TableExists($edit_table) )
{
echo 'ERROR: Table "<b>'.$edit_table.'</b>" missing (class: <b>'.get_class($this).'</b>)<br>';
//exit;
return;
}
$rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table WHERE ResourceId=0");
while($rs && !$rs->EOF)
{
$id = $rs->fields["ImageId"];
if($id>0)
{
$img = $this->GetItem($id);
$img->Delete();
}
$rs->MoveNext();
}
$this->adodbConnection->Execute("DELETE FROM $edit_table WHERE ResourceId=0");
$this->CopyFromPendingFiles($edit_table);
parent::CopyFromEditTable($idfield);
}
function PurgeEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$this->DeletePendingFiles($edit_table);
- @$this->adodbConnection->Execute("DROP TABLE $edit_table");
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function GetNextImageIndex($ResourceId)
{
$sql = "SELECT MAX(ImageIndex) as MaxVal FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
$rs = $this->adodbConnection->Execute($sql);
if($rs)
{
$val = (int)$rs->fields["MaxVal"];
$val++;
}
return $val;
}
function GetMaxPriority($ResourceId)
{
$sql = "SELECT MAX(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
function GetMinPriority($ResourceId)
{
$sql = "SELECT MIN(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
$result = $this->adodbConnection->Execute($sql);
return $result->fields["p"];
}
} /*clsImageList*/
?>
Property changes on: trunk/kernel/include/image.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/kernel/include/usersession.php
===================================================================
--- trunk/kernel/include/usersession.php (revision 270)
+++ trunk/kernel/include/usersession.php (revision 271)
@@ -1,1129 +1,1129 @@
<?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['SERVER_NAME'].$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 %s%s_search",GetTablePrefix(), $this->Get("SessionKey"));
+ $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['SERVER_NAME'].$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 ".$tables[$i]);
+ @$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.")";
//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;
$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(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()
{
$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.9
\ No newline at end of property
+1.10
\ No newline at end of property
Index: trunk/kernel/include/language.php
===================================================================
--- trunk/kernel/include/language.php (revision 270)
+++ trunk/kernel/include/language.php (revision 271)
@@ -1,756 +1,756 @@
<?php
class clsPhrase extends clsItemDB
{
function clsPhrase($id=NULL)
{
$this->clsItemDB();
$this->tablename = GetTablePrefix()."Phrase";
$this->id_field = "PhraseId";
$this->NoResourceId=1;
if($id)
$this->LoadFromDatabase($id);
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
if($Id)
{
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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;
}
else
return FALSE;
}
function AdminIcon()
{
global $imagesURL;
return $imagesURL."/itemicons/icon16_language_var.gif";
}
}
class clsPhraseList extends clsItemCollection
{
var $Page;
var $PerPageVar;
function clsPhraseList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."Phrase";
$this->classname = "clsPhrase";
$this->PerPageVar = "Perpage_Phrase";
$this->AdminSearchFields = array("p.Phrase","p.Translation");
}
function &AddPhrase($Phrase,$LangId,$Translation,$Type)
{
$tmpphrase = $this->GetPhrase($Phrase, $LangId);
if (!$tmpphrase) {
$p = new clsPhrase();
$p->tablename = $this->SourceTable;
$p->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$p->Dirty();
$p->Create();
return $p;
}
else {
$add_error = "Error";
return $add_error;
/* $tmpphrase->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$tmpphrase->Dirty();
$tmpphrase->Update();
return $tmpphrase;*/
}
}
function &EditPhrase($id,$Phrase,$LangId,$Translation,$Type)
{
$p = $this->GetItem($id);
$p->Set(array("Phrase","LanguageId","Translation","PhraseType"),
array($Phrase,$LangId,$Translation,$Type));
$p->Dirty();
$p->Update();
return $p;
}
function DeletePhrase($id)
{
$p = $this->GetItem($id);
$p->Delete();
}
function DeleteLanguage($LangId)
{
$sql = "DELETE FROM ".$this->SourceTable." WHERE LanguageId=$LangId";
if((int)$_GLOBALS["debuglevel"])
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function CopyFromEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT l.PhraseId AS pid FROM ".GetTablePrefix()."Phrase AS l LEFT JOIN $edit_table AS e ON e.PhraseId = l.PhraseId WHERE e.PhraseId IS NULL ORDER BY l.PhraseId";
$rs = $this->adodbConnection->Execute($sql);
$ids = '';
while ($rs && !$rs->EOF) {
$ids .= $rs->fields['pid'].',';
$rs->MoveNext();
}
$ids = substr($ids, 0, strlen($ids) - 1);
if (strlen($ids) > 0) {
$sql = "DELETE FROM ".GetTablePrefix()."Phrase WHERE PhraseId IN (".$ids.")";
$this->adodbConnection->Execute($sql);
}
//$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["PhraseId"]>0)
{
$c->Update();
}
else
{
$c->debuglevel=0;
$c->UnsetIdField();
$c->Create();
}
$rs->MoveNext();
}
if((int)$_GLOBALS["debuglevel"])
echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- $this->adodbConnection->Execute("DROP TABLE $edit_table");
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function GetPhrase($Phrase,$Lang, $no_db=FALSE)
{
$found = FALSE;
foreach($this->Items as $i)
{
if($i->Get("Phrase")==$Phrase && $i->Get("LanguageId")==$Lang)
{
$found = TRUE;
break;
}
}
if(!$found && !$no_db)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE Phrase='$Phrase' AND LanguageId='$Lang'";
//echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$i = $this->AddItemFromArray($data);
}
else
$i = FALSE;
}
return $i;
}
}
RegisterPrefix("clsLanguage","lang","kernel/include/language.php");
class clsLanguage extends clsParsedItem
{
function clsLanguage($id=NULL)
{
$this->clsParsedItem();
$this->tablename = GetTablePrefix()."Language";
$this->id_field = "LanguageId";
$this->NoResourceId=1;
$this->TagPrefix="lang";
if($id)
$this->LoadFromDatabase($id);
}
function LoadFromDatabase($Id)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$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 Delete()
{
$p = new clsPhraseList();
//$id = $this->Get("LanguageId");
//$p->DeleteLanguage($id);
parent::Delete();
}
function ParseObject($element)
{
global $m_var_list,$m_var_list_update, $var_list,$var_list_update, $TemplateRoot;
//echo "<PRE>"; print_r($element); echo "</PRE>";
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
$ret = $this->Get("LanguageId");
break;
case "packname":
$ret = $this->Get("PackName");
break;
case "localname":
$ret = $this->Get("LocalName");
break;
case "link":
$t = $element->attributes["_template"];
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
$var_list_update["t"] = $var_list["t"];
$m_var_list_update["lang"] = $this->Get("LanguageId");
$ret = GetIndexURL()."?env=".BuildEnv();
unset($var_list_update["t"],$m_var_list_update["lang"]);
break;
case "primary":
$ret = "";
if($this->Get("PrimaryLang")==1)
$ret = "1";
break;
case "icon":
$ret = "";
$icon = $this->Get("IconUrl");
if(strlen($icon)>0)
{
$file = $TemplateRoot."/".$icon;
//echo "File:$file <br>\n";
if(file_exists($file))
$ret = $icon;
}
if(!strlen($ret))
$ret = $element->attributes["_default"];
//echo $ret;
break;
}//switch
}//if
return $ret;
}
function AdminIcon()
{
global $imagesURL;
$file = $imagesURL."/itemicons/icon16_language";
if($this->Get("PrimaryLang")==1)
{
$file .= "_primary.gif";
}
else
{
if($this->Get("Enabled")==0)
{
$file .= "_disabled";
}
$file .= ".gif";
}
return $file;
}
}
class clsLanguageList extends clsItemCollection
{
var $m_Primary;
function clsLanguageList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."Language";
$this->classname = "clsLanguage";
$this->AdminSearchFields = array("PackName","LocalName");
}
function SetPrimary($lang_id)
{
$sql = "UPDATE ".$this->SourceTable." SET PrimaryLang=0 ";
$this->adodbConnection->Execute($sql);
$l = $this->GetItem($lang_id);
$l->Set("PrimaryLang","1");
$l->Update();
$this->m_Primary =$lang_id;
}
function GetPrimary($Field="LanguageId")
{
if(!$this->m_Primary)
{
$sql = "SELECT * FROM ".$this->SourceTable." WHERE PrimaryLang=1";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$l = $rs->fields[$Field];
}
else
$l = 0;
$this->m_Primary=$l;
}
else
$l = $this->m_Primary;
return $l;
}
function LoadAllLanguages()
{
$sql = "SELECT * FROM ".$this->SourceTable;
$this->Query_Item($sql);
}
function &AddLanguage($PackName,$LocalName,$Enabled,$Primary, $IconUrl="",$Datefmt,$TimeFmt,$Dec,$Thousand)
{
$l = new clsLanguage();
$l->tablename = $this->SourceTable;
$l->Set(array("PackName","LocalName","Enabled","PrimaryLang","IconUrl","DateFormat","TimeFormat",
"DecimalPoint","ThousandSep"),
array($PackName,$LocalName,$Enabled,$Primary,$IconUrl,$Datefmt,$TimeFmt,$Dec,$Thousand));
$l->Dirty();
$l->Create();
return $l;
}
function EditLanguage($id,$PackName,$LocalName,$Enabled,$Primary, $IconUrl="",$Datefmt,$TimeFmt,$Dec,$Thousand)
{
$l = $this->GetItem($id);
$l->Set(array("PackName","LocalName","Enabled","PrimaryLang","IconUrl","DateFormat","TimeFormat",
"DecimalPoint","ThousandSep"),
array($PackName,$LocalName,$Enabled,$Primary,$IconUrl,$Datefmt,$TimeFmt,$Dec,$Thousand));
$l->Update();
return $l;
}
function DeleteLanguage($id)
{
$l = $this->GetItem($id);
$l->Delete();
}
function CopyFromEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$idlist = array();
$sql = "SELECT * FROM $edit_table";
$this->Clear();
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = $this->AddItemFromArray($data);
$c->Dirty();
if($data["LanguageId"]>0)
{
$c->Update();
}
else
{
$oldid = $c->Get("LanguageId");
$c->UnsetIdField();
$c->Create();
$id = $c->Get("LanguageId");
$phrase_table = $objSession->GetEditTable("Phrase");
$sql = "UPDATE $phrase_table SET LanguageId=$id WHERE LanguageId=$oldid";
$this->adodbConnection->Execute($sql);
}
$rs->MoveNext();
}
}
function ExportPhrases($file,$LangIds=NULL,$PhraseTypes=null)
{
$output = array();
$this->Clear();
$where_parts = Array();
if( isset($LangIds) ) $where_parts[] = 'LanguageId IN ('.$LangIds.')';
$where = count($where_parts) ? ' WHERE '.implode(' AND ', $where_parts) : '';
$this->Query_Item($sql = 'SELECT * FROM '.$this->SourceTable.$where);
$objXML = new xml_doc();
$RootNode =& $objXML->getTagByID($objXML->createTag("LANGUAGES"));
$ret = 0;
if($this->NumItems()>0)
{
$phrase_where = isset($PhraseTypes) ? ' AND PhraseType IN ('.$PhraseTypes.')' : '';
$event_where = isset($PhraseTypes) ? ' AND Type+1 IN ('.$PhraseTypes.')' : '';
foreach($this->Items as $l)
{
$LangRoot =& $objXML->getTagByID($RootNode->addChild($objXML,"LANGUAGE",array("PackName"=>$l->Get("PackName")),""));
$LangRoot->addChild($objXML,"DATEFORMAT",array(),$l->Get("DateFormat"));
$LangRoot->addChild($objXML,"TIMEFORMAT",array(),$l->Get("TimeFormat"));
$LangRoot->addChild($objXML,"DECIMAL",array(),$l->Get("DecimalPoint"));
$LangRoot->addChild($objXML,"THOUSANDS",array(),$l->Get("ThousandSep"));
$PhraseRoot =& $objXML->getTagByID($LangRoot->addChild($objXML,"PHRASES"));
$sql = "SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$l->Get("LanguageId").$phrase_where;
$rs=$this->adodbConnection->Execute($sql);
while($rs && ! $rs->EOF)
{
$PhraseRoot->addChild($objXML,"PHRASE",array("Label"=>$rs->fields["Phrase"],"Type"=>$rs->fields["PhraseType"]),base64_encode($rs->fields["Translation"]));
$rs->MoveNext();
}
$EventRoot =& $objXML->getTagByID($LangRoot->addChild($objXML,"EVENTS"));
$ev = GetTablePrefix()."Events";
$em = GetTablePrefix()."EmailMessage";
$sql = "SELECT $em.*,$ev.Event,$ev.Type FROM $em INNER JOIN $ev ON ($em.EventId=$ev.EventId) WHERE LanguageId=".$l->Get("LanguageId").$event_where;
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$EventRoot->AddChild($objXML,"EVENT",array("MessageType"=>$rs->fields["MessageType"],"Event"=>$rs->fields["Event"],"Type"=>$rs->fields["Type"]),base64_encode($rs->fields["Template"]));
$rs->MoveNext();
}
}
$objXML->generate();
$objXML->xml = str_replace("&","&amp;",$objXML->xml);
$fp = @fopen($file,"w");
@fputs($fp,$objXML->xml);
@fclose($fp);
}
return file_exists($file);
}
function ReadImportTable($TableName,$SetEnabled=0,$Types="0,1",$OverwitePhrases=FALSE,
$MaxInserts=100,$Offset=0)
{
global $objPhraseList;
if(!is_object($objPhraseList))
$objPhraseList = new clsPhraseList();
$PhraseList = new clsPhraseList();
$TypeArray = explode(",",$Types);
$Inserts = 0;
$sql = "SELECT * FROM $TableName WHERE PhraseType IN ($Types) LIMIT $Offset,$MaxInserts";
//echo $sql;
//$PhraseList->EnablePaging = false;
$PhraseList->Query_Item($sql);
if($PhraseList->NumItems()>0)
{
foreach($PhraseList->Items as $i)
{
$p = $objPhraseList->GetPhrase($i->Get("Phrase"),$i->Get("LanguageId"));
//echo "<pre>"; print_r($p); echo "</pre>";
if(is_object($p))
{
if($OverwitePhrases)
{
//$p->debuglevel=1;
$p->Set("Translation",$i->Get("Translation"));
//echo $i->Get("Translation")."<br>";
$p->Set("PhraseType",$i->Get("PhraseType"));
$p->Dirty();
$p->Update();
}
}
else {
//$i->debuglevel=1;
$i->Create();
}
$Inserts++;
}
}
$Offset = $Offset + $Inserts;
return $Offset;
}
function PurgeEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
- $this->adodbConnection->Execute("DROP TABLE $edit_table");
+ $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
}
class clsLanguageCache
{
var $m_CachedLanguage;
var $FullLoad = FALSE;
var $cache;
var $adodbConnection;
var $TemplateName;
var $TemplateCache;
var $TemplateDate;
var $ThemeId;
function clsLanguageCache($LangId=NULL)
{
global $objConfig;
$this->m_CachedLanguage = $LangId;
$this->adodbConnection =& GetADODBConnection();
$this->Clear();
}
function Clear()
{
unset($this->cache);
$this->cache = array();
$this->TemplateCache = array();
}
function LoadLanguage($LangId,$Type)
{
$this->Clear();
$this->m_CachedLanguage = $LangId;
$this->FullLoad = TRUE;
$sql = "SELECT Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE LanguageId=$LangId AND PhraseType=$Type";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$this->cache[$rs->fields["Phrase"]] = $rs->fields["Translation"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
return (count($this->cache)>0);
}
function GetPhrase($Phrase,$Lang)
{
$t = "";
$sql = "SELECT PhraseId,Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE Phrase='$Phrase' AND LanguageId='$Lang'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$t = $rs->fields["Translation"];
$this->TemplateCache[] = $rs->fields["PhraseId"];
}
return $t;
}
function LoadTemplateCache($t, $timeout, $ThemeId)
{
$this->TemplateName = $t;
$this->TemplateDate = 0;
$this->ThemeId = $ThemeId;
if($timeout > 0)
{
$sql = "SELECT * FROM ".GetTablePrefix()."PhraseCache WHERE Template='$t' AND ThemeId=$ThemeId";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$this->TemplateCache = explode(',', $rs->fields['PhraseList']);
$t_length = strlen($rs->fields['PhraseList']) ? 1 : 0;
$this->TemplateDate = $rs->fields["CacheDate"];
if(date("U") < $this->TemplateDate + $timeout || !$t_length)
{
$this->TemplateCache = Array();
$this->TemplateDate=0;
}
}
else
$this->TemplateDate = -1;
}
else
$this->TemplateDate=-2;
}
function LoadCachedVars($LangId)
{
if(count($this->TemplateCache))
{
$values = implode(",",$this->TemplateCache);
$this->FullLoad = FALSE;
$this->m_CachedLanguage = $LangId;
$sql = "SELECT Phrase,Translation FROM ".GetTablePrefix()."Phrase WHERE LanguageId=$LangId AND PhraseId IN ($values)";
$rs = $this->adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$this->cache[$rs->fields["Phrase"]] = $rs->fields["Translation"];
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
adodb_movenext($rs);
else
$rs->MoveNext();
}
}
}
function SaveTemplateCache()
{
if($this->TemplateDate==0 || $this->TemplateDate==-1)
{
$value = implode(",",$this->TemplateCache);
if($this->TemplateDate==0)
{
$sql = "UPDATE ".GetTablePrefix()."PhraseCache SET PhraseList='$value',CacheDate=".date("U");
$sql .=" WHERE Template='".$this->TemplateName."' AND ThemeId=".$this->ThemeId;
}
else
{
$sql = "INSERT INTO ".GetTablePrefix()."PhraseCache (Template,PhraseList,CacheDate,ThemeId) VALUES ('";
$sql .= $this->TemplateName."','$value',".date("U").",".$this->ThemeId.")";
}
$this->adodbConnection->Execute($sql);
}
}
//This function returns a translation for a particular phrase
//if translation is not found then !phrase! is returned.
function GetTranslation($phrase,$language)
{
global $objSession, $LogPhraseLookups,$LangList, $MissingList;
$missing = FALSE;
if(!$this->FullLoad)
{
$this->RefreshCacheStatus($language);
if(!isset($this->cache[$phrase]))
{
$this->cache[$phrase] = $this->GetPhrase($phrase,$language);
$translation = $this->cache[$phrase];
//$translation = "";
}
else
$translation = $this->cache[$phrase];
}
else
{
$translation = $this->cache[$phrase];
}
if(!strlen($translation))
{
$missing = TRUE;
if($language != 1)
{
$translation=$this->GetTranslation($phrase,1);
}
else
{
$translation = "!".$phrase."!";
}
}
if($LogPhraseLookups==TRUE)
{
//if(!is_array($LangList))
// $LangList = array();
//$LangList[$phrase] = $LangList;
if($missing)
{
if(!is_array($MissingList))
{
$MissingList = array();
}
if(!in_array($phrase,$MissingList))
$MissingList[] = $phrase;
}
}
return $translation;
}
//This function checks if cache is current for current language
//if not clear it out
function RefreshCacheStatus($language)
{
//First remember what language we are caching
// if(!isset($this->m_CachedLanguage))
// $this->m_CachedLanguage = $language;
//If this is the different language, then clear the cache
// if($this->m_CachedLanguage != $language)
// {
// $this->Clear();
// $this->m_CachedLanguage = $language;
// }
}
}
?>
Property changes on: trunk/kernel/include/language.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/itemtypes.php
===================================================================
--- trunk/kernel/include/itemtypes.php (revision 270)
+++ trunk/kernel/include/itemtypes.php (revision 271)
@@ -1,236 +1,236 @@
<?php
class clsItemType extends clsItemDB
{
function clsItemType($ItemType=NULL)
{
$this->clsItemDB();
$this->NoResourceId=1;
$this->table = GetTablePrefix()."ItemTypes";
$this->id_field="ItemType";
if($ItemType)
$this->LoadFromDatabase($ItemType);
}
function LoadFromDatabase($ItemType)
{
global $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'", $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;
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
function GetEditURL()
{
global $rootURL;
$url = $this->Get("EditUrl");
if(strlen($url))
{
$ret = $rootURL.$url;
}
else
$ret = "";
return $ret;
}
function GetTemplatePath()
{
$m = $this->Get("Module");
}
}
class clsItemTypeList extends clsItemCollection
{
function clsItemTypeList()
{
$this->clsItemCollection();
$this->SourceTable = GetTablePrefix()."ItemTypes";
$this->classname="clsItemType";
$this->LoadAllItems();
}
function LoadAllItems()
{
$t = $this->SourceTable;
$m = GetTablePrefix()."Modules";
$sql = "SELECT * FROM $t INNER JOIN $m ON ($t.Module=$m.Name) WHERE Loaded=1 ORDER BY LoadOrder";
$this->Query_Item($sql);
}
function LoadPrimaryItems()
{
$t = $this->SourceTable;
$m = GetTablePrefix()."Modules";
$sql = "SELECT * FROM $t INNER JOIN $m ON ($t.Module=$m.Name) WHERE Loaded=1 ORDER BY LoadOrder WHERE PrimaryItem=1";
$this->Query_Item($sql);
}
function BuildUserItemTable($UserId,$ClearTable=1)
{
global $objSession;
$dest_table = $objSession->GetEditTable("UserItems"); // $objSession->GetSessionKey()."_UserItems";
if($ClearTable)
{
- @$this->adodbConnection->Execute("DROP TABLE ".$dest_table);
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$dest_table);
$sql = "CREATE TABLE ".$dest_table." (";
$sql .="PortalUserId INT, ";
$sql .="ResourceId INT, ";
$sql .="ItemType INT)";
$this->adodbConnection->Execute($sql);
}
foreach($this->Items as $t)
{
$Source = GetTablePrefix().$t->Get("SourceTable");
$Field = $t->Get("CreatorField");
$Type = $t->Get("ItemType");
$sel = "SELECT ResourceId FROM $Source WHERE $Field=$UserId";
$rs = $this->adodbConnection->Execute($sel);
while($rs && !$rs->EOF)
{
$ins = "INSERT INTO $dest_table VALUES ($UserId,".$rs->fields["ResourceId"].",$Type)";
$this->adodbConnection->Execute($ins);
$rs->MoveNext();
}
}
return $dest_table;
}
function GetTypeByClassName($name)
{
$ret = NULL;
foreach($this->Items as $i)
{
if($i->Get("ClassName")==$name)
{
$ret = $i;
break;
}
}
return $ret;
}
function GetTypeByName($name)
{
$ret = NULL;
foreach($this->Items as $i)
{
if(strtolower($i->Get("ItemName"))==strtolower($name))
{
$ret = $i;
break;
}
}
return $ret;
}
function GetItemTypeValue($name)
{
$ret = NULL;
foreach($this->Items as $i)
{
if(strtolower($i->Get("ItemName"))==strtolower($name))
{
$ret = $i;
break;
}
}
$value = 0;
if(is_object($ret))
$value = $i->Get("ItemType");
return $value;
}
function GetItem($id,$db=FALSE)
{
foreach($this->Items as $i)
{
if($i->Get("ItemType")==$id)
{
$ret = $i;
break;
}
}
return $ret;
}
function GetTypeEditUrl($type)
{
foreach($this->Items as $i)
{
if($i->Get("ItemType")==$type)
{
$ret = $i->GetEditURL();
break;
}
}
return $ret;
}
}
class clsMultiTypeList extends clsItemCollection
{
function clsMultiTypeList()
{
$this->clsItemCollection();
$this->classname = "clsItem";
}
function Query_Item($sql, $offset=-1,$rows=-1,$Type="")
{
global $Errors;
if($rows>-1 && $offset>-1)
{
//echo "Executing SelectLimit $sql Offset: $offset,$rows<br>\n";
$result = $this->adodbConnection->SelectLimit($sql, $rows,$offset);
}
else
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item");
return false;
}
LogEntry("SQL Loop Start\n");
$count = 0;
while ($result && !$result->EOF)
{
$count++;
$data = $result->fields;
$i =& $this->AddItemFromArray($data,TRUE);
if(is_numeric($Type))
$i->type = $Type;
if(ADODB_EXTENSION>0)
{
adodb_movenext($result);
}
else
$result->MoveNext();
}
LogEntry("SQL Loop End ($count iterations)\n");
return $this->Items;
}
}
Property changes on: trunk/kernel/include/itemtypes.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/kernel/startup.php
===================================================================
--- trunk/kernel/startup.php (revision 270)
+++ trunk/kernel/startup.php (revision 271)
@@ -1,144 +1,145 @@
<?php
/*
startup.php: this is the primary startup sequence for in-portal services
*/
+
if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
if( !defined('DEBUG_MODE') ) error_reporting(0);
ini_set('memory_limit', '16M');
$kernel_version = "1.0.0";
$FormError = array();
$FormValues = array();
/* include PHP version compatibility functions */
require_once($pathtoroot."compat.php");
/* set global variables and module lists */
require_once($pathtoroot."globals.php");
LogEntry("Initalizing System..\n");
/* for 64 bit timestamps */
require_once($pathtoroot."kernel/include/adodb/adodb-time.inc.php");
require_once($pathtoroot."kernel/include/dates.php");
/* create the global error object */
require_once($pathtoroot."kernel/include/error.php");
$Errors = new clsErrorManager();
require_once($pathtoroot."kernel/include/itemdb.php");
require_once($pathtoroot."kernel/include/config.php");
/* create the global configuration object */
LogEntry("Creating Config Object..\n");
$objConfig = new clsConfig();
$objConfig->Load(); /* Populate our configuration data */
LogEntry("Done Loading Configuration\n");
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
LogEntry("ADO Extension: ".ADODB_EXTENSION."\n");
require_once($pathtoroot."kernel/include/parseditem.php");
require_once($pathtoroot."kernel/include/item.php");
require_once($pathtoroot."kernel/include/syscache.php");
require_once($pathtoroot."kernel/include/modlist.php");
require_once($pathtoroot."kernel/include/searchconfig.php");
require_once($pathtoroot."kernel/include/banrules.php");
$objModules = new clsModList();
$objSystemCache = new clsSysCacheList();
$objSystemCache->PurgeExpired();
$objBanList = new clsBanRuleList();
require_once($pathtoroot."kernel/include/image.php");
require_once($pathtoroot."kernel/include/itemtypes.php");
$objItemTypes = new clsItemTypeList();
require_once($pathtoroot."kernel/include/theme.php");
$objThemes = new clsThemeList();
require_once($pathtoroot."kernel/include/language.php");
$objLanguages = new clsLanguageList();
$objImageList = new clsImageList();
/* Load session and user class definitions */
//require_once("include/customfield.php");
//require_once("include/custommetadata.php");
require_once($pathtoroot."kernel/include/usersession.php");
require_once($pathtoroot."kernel/include/favorites.php");
require_once($pathtoroot."kernel/include/portaluser.php");
require_once($pathtoroot."kernel/include/portalgroup.php");
/* create the user management class */
$objFavorites = new clsFavoriteList();
$objUsers = new clsUserManager();
$objGroups = new clsGroupList();
require_once($pathtoroot."kernel/include/cachecount.php");
require_once($pathtoroot."kernel/include/customfield.php");
require_once($pathtoroot."kernel/include/custommetadata.php");
require_once($pathtoroot."kernel/include/permissions.php");
require_once($pathtoroot."kernel/include/relationship.php");
require_once($pathtoroot."kernel/include/category.php");
require_once($pathtoroot."kernel/include/statitem.php");
/* category base class, used by all the modules at some point */
$objPermissions = new clsPermList();
$objPermCache = new clsPermCacheList();
$objCatList = new clsCatList();
$objCustomFieldList = new clsCustomFieldList();
$objCustomDataList = new clsCustomDataList();
$objCountCache = new clsCacheCountList();
require_once($pathtoroot."kernel/include/smtp.php");
require_once($pathtoroot."kernel/include/emailmessage.php");
require_once($pathtoroot."kernel/include/events.php");
LogEntry("Creating Mail Queue..\n");
$objMessageList = new clsEmailMessageList();
$objEmailQueue = new clsEmailQueue();
LogEntry("Done creating Mail Queue Objects\n");
require_once($pathtoroot."kernel/include/searchitems.php");
require_once($pathtoroot."kernel/include/advsearch.php");
require_once($pathtoroot."kernel/include/parse.php");
require_once($pathtoroot."kernel/include/socket.php");
/* responsible for including module code as required
This script also creates an instance of the user session onject and
handles all session management. The global session object is created
and populated, then the global user object is created and populated
each module's parser functions and action code is included here
*/
LogEntry("Startup complete\n");
include_once("include/modules.php");
/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/
$objEmailQueue->SendMailQeue();
$ado=GetADODBConnection();
$rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0");
$kernel_version = $rs->fields['Version'];
$adminDir = $objConfig->Get("AdminDirectory");
if ($adminDir == '') {
$adminDir = 'admin';
}
if (strstr($_SERVER['SCRIPT_FILENAME'], $adminDir) && !GetVar('logout') && !strstr($_SERVER['SCRIPT_FILENAME'], "install") && !strstr($_SERVER['SCRIPT_FILENAME'], "index")) {
//echo "testz [".admin_login()."]<br>";
if (!admin_login())
{
if( !headers_sent() ) setcookie("sid"," ",time()-3600);
$objSession->Logout();
$url_add = isset($_GET['expired']) && $_GET['expired'] ? '?expired=1' : '';
header("Location: ".$adminURL.'/login.php'.$url_add);
die();
//require_once($pathtoroot."admin/login.php");
}
}
?>
Property changes on: trunk/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/admin/email/do_send.php
===================================================================
--- trunk/admin/email/do_send.php (revision 270)
+++ trunk/admin/email/do_send.php (revision 271)
@@ -1,312 +1,312 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
//$pathtoroot="";
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
require_once($pathtoroot."kernel/startup.php");
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
$browseURL = $adminURL."/browse";
//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."/browse/toolbar.php");
//Set Section
$section = 'in-portal:sendmail';
//Set Environment Variable
$envar = "env=" . BuildEnv();
$State = $_POST["EmailState"];
if(!strlen($State))
{
$State = $_GET["EmailState"];
}
$ado = GetADODBConnection();
$table = "ses_".$objSession->GetSessionKey()."_sendmail";
$MessagesPerPage =2;
$SendQueue = new clsEmailQueue($table,$MessagesPerPage);
$FromUser = $objUsers->GetItem($objSession->Get("PortalUserId"));
$FromAddr = $FromUser->Get("Email");
$FromName = $FromUser->Get("FirstName")." ".$FromUser->Get("LastName");
if(!strlen(trim($FromAddr)))
{
$FromAddr = $objConfig->Get("Default_FromAddr");
}
if(!strlen(trim($FromName)))
{
$FromName = "System Administrator";
}
$TargetURL = $_SERVER["PHP_SELF"]."?".$envar.'&destform=popup';
$CancelURL = $TargetURL."&EmailState=email_user_cancel";
/*Initialize page*/
switch($State)
{
case "email_single_send": /*single user send */
$PageTitle = admin_language("la_Title_SendInit");
$Subject = $_POST["subject"];
$Html = $_POST["messageHTML"];
$Text = strip_tags($_POST["messageTEXT"]);
if(is_array($_FILES))
{
$attatch = $_FILES["attatchment"];
if(strlen($attatch["name"]) >0 && $attatch["size"]>0)
{
$FileName = $attatch["name"];
$FileLoc = $attatch["tmp_name"];
}
else
{
$FileName = NULL;
$FileLoc = NULL;
}
}
else
{
$FileName = NULL;
$FileLoc = NULL;
}
$charset = "";
$TargetURL .= "&EmailState=email_send_complete";
break;
case "email_multi_send": /*Init multiuser send*/
$UserList = explode(",",$_POST["sendaddrs"]);
//echo $_POST["sendaddrs"]."<br>\n";
$Subject = $_POST["subject"];
$Html = $_POST["messageHTML"];
$Text = strip_tags($_POST["messageTEXT"]);
if(is_array($_FILES))
{
$attatch = $_FILES["attatchment"];
if(strlen($attatch["name"]) >0 && $attatch["size"]>0)
{
$FileName = $attatch["name"];
$FileLoc = $attatch["tmp_name"];
}
else
{
$FileName = NULL;
$FileLoc = NULL;
}
}
else
{
$FileName = NULL;
$FileLoc = NULL;
}
$charset = "";
$PageTitle = admin_language("la_Title_SendMailInit");
$TargetURL .="&EmailState=email_send_progress&Start=0&Total=".count($UserList);
break;
case "email_send_progress":
$total = $_GET["Total"];
$start = $_GET["Start"];
if($start < $total)
{
$pct = (int)(($start/$total)*100);
$NewStart = $start+$MessagesPerPage;
$TargetURL .= "&EmailState=email_send_progress&Start=$NewStart&Total=$total";
$PageTitle = admin_language("la_Title_SendMailProgress")." - ".$pct."% ".admin_language("la_Text_Complete");
}
else
{
$PageTitle = admin_language("la_Title_SendMailProgress");
$TargetURL .= "&EmailState=email_send_complete";
}
break;
case "email_send_complete":
$PageTitle = admin_language("la_Title_SendMailComplete");
$TargetURL="";
break;
case "email_user_cancel":
$PageTitle = admin_language("la_Title_SendMailCancel");
$TargetURL = "";
break;
}
int_header(NULL,NULL,admin_language("la_Title_PleaseWait"));
echo "\n";
/*do page functions */
// echo "Current State:". $State."<br>\n";
echo "<TABLE border=0 width=\"100%\" height=\"90%\"><TR><TD valign=\"top\" align=\"middle\">";
switch($State)
{
case "email_single_send": /*single user send */
$PageTitle = admin_language($Pagetitle);
$ToAddr = $_POST["sendaddrs"];
$SendQueue->SendMail($FromAddr,$FromName,$ToAddr,"",$Subject,$Text,$Html,$charset,$FileName,$FileLoc,0, NULL);
$o = "<TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .= int_subsection_title_ret($PageTitle);
$o .= "<TD COLSPAN=2>".admin_language("la_prompt_EmailInitMessage")."</TD></TR>";
$o .= "<TD ALIGN=\"middle\" COLSPAN=2></TD></TR>";
$o .= "</TABLE><input type=button CLASS=\"button\" VALUE=\"".admin_language("la_Cancel")."\" ONCLICK=\"document.location='".$CancelURL."';\">";
echo $o."\n";
break;
case "email_multi_send": /*Init multiuser send*/
/*Create storage Table for Queue */
$o = "<TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .= int_subsection_title_ret($PageTitle);
$o .= "<tr><TD COLSPAN=2>".admin_language("la_prompt_EmailInitMessage")."</TD></TR>";
$o .= "<TD ALIGN=\"middle\" COLSPAN=2></TD></TR>";
$o .= "</TABLE><input type=button CLASS=\"button\" VALUE=\"".admin_language("la_Cancel")."\" ONCLICK=\"document.location='".$CancelURL."';\">";
echo $o."\n";
$sql = "CREATE TABLE $table SELECT * FROM ".$objEmailQueue->SourceTable." WHERE queued=99";
$ado->Execute($sql);
//echo $sql."<br>\n";
for($i=0;$i<count($UserList);$i++)
{
$ToAddr = $UserList[$i];
//$From,$FromName,$To,$ToName,$Subject,$Text,$Html,$charset,$AttmFiles,$QueueOnly=0
$SendQueue->SendMail($FromAddr,$FromName,$ToAddr,"",$Subject,$Text,$Html,$charset,$FileName,$FileLoc,1, NULL);
}
break;
case "email_send_progress":
$sql = "SELECT * FROM $table LIMIT $start,".$MessagesPerPage;
// echo $sql."<br>\n";
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$SendQueue->DeliverMail($data["toaddr"],$data["fromaddr"],$data["Subject"],$data["message"],$data["headers"],1);
$rs->MoveNext();
}
$o = "<TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .= int_subsection_title_ret($PageTitle);
$o .="<TR border=1><TD width=\"".$pct."%\" STYLE=\"background:url('".$adminURL."/images/progress_bar_segment.gif');\">&nbsp;</TD>";
$comp_pct = 100-$pct;
$o .= "<TD bgcolor=#FFFFFF width=\"".$comp_pct."%\"></TD></TR>";
$o .= "</TABLE>";
$o .= "<input type=button VALUE=\"".admin_language("la_Cancel")."\" CLASS=\"button\" ONCLICK=\"document.location='".$CancelURL."';\">";
echo $o."\n";
break;
case "email_send_complete":
- $sql = "DROP TABLE $table";
+ $sql = "DROP TABLE IF EXISTS $table";
$ado->Execute($sql);
$o = "<TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .= int_subsection_title_ret($PageTitle);
$o .= "<TR><TD COLSPAN=2>".admin_language("la_prompt_EmailCompleteMessage")."</TD></TR>";
$o .= "<TD ALIGN=\"middle\" COLSPAN=2></TD></TR>";
$o .= "</TABLE><input type=button VALUE=\"".admin_language("la_Close")."\" CLASS=\"button\" ONCLICK=\"window.close();\">";
echo $o."\n";
break;
case "email_user_cancel":
$o = "<TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .= int_subsection_title_ret($PageTitle);
$o .= "<TR><TD COLSPAN=2>".admin_language("la_prompt_EmailCancelMessage")."</TD></TR>";
$o .= "</TABLE><input type=button VALUE=\"".admin_language("la_Close")."\" CLASS=\"button\" ONCLICK=\"window.close();\">";
echo $o."\n";
break;
}
echo "</TD></TR></TABLE>";
if(strlen($TargetURL))
{
?>
<SCRIPT LANGUAGE="JavaScript">
document.location = '<?php echo $TargetURL; ?>';
</SCRIPT>
<?php
}
?>
<?php int_footer(); ?>
Property changes on: trunk/admin/email/do_send.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/admin/category/category_maint.php
===================================================================
--- trunk/admin/category/category_maint.php (revision 270)
+++ trunk/admin/category/category_maint.php (revision 271)
@@ -1,248 +1,248 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path = dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if( strlen($path) )
{
// determine the OS type for path parsing
$pos = strpos($path, ':');
$gOS_TYPE = ($pos === false) ? 'unix' : 'win';
$pathchar = ($gOS_TYPE == 'unix') ? '/' : "\\";
$p = $path.$pathchar;
// Start looking for the root flag file
while( !strlen($pathtoroot) && strlen($p) )
{
$sub = substr($p, strlen($pathchar) * -1);
$filename = $p.( ($sub == $pathchar) ? '' : $pathchar).'root.flg';
if( !file_exists($filename) )
{
$parent = realpath($p.$pathchar."..".$pathchar);
$p = ($parent != $p) ? $parent : '';
}
else
$pathtoroot = $p;
}
if( !strlen($pathtoroot) ) $pathtoroot = '.'.$pathchar;
}
else
$pathtoroot = '.'.$pathchar;
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if( $sub != $pathchar) $pathtoroot = $pathtoroot.$pathchar;
//echo $pathtoroot;
$FrontEnd=2;
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
//$pathtolocal = $pathtoroot."in-news/";
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");
require_once($pathtoroot.$admin."/listview/listview.php");
$section = "in-portal:category_maint";
$CatsPerLoad = 10;
$ado = GetADODBConnection();
if(!is_numeric($_GET["CatIndex"]))
{
unset($objEditItems);
$objEditItems = new clsCatList();
$objEditItems->SourceTable = $objSession->GetEditTable("Category");
$table = $objEditItems->SourceTable;
//echo "Dropping Table..<br>\n";
- @$ado->Execute("DROP TABLE $table");
+ @$ado->Execute("DROP TABLE IF EXISTS $table");
if($objCatList->CurrentCategoryID()>0)
{
$c = $objCatList->GetItem($objCatList->CurrentCategoryID());
$path = $c->Get("ParentPath");
$sql = "SELECT CategoryId,ParentPath FROM ".$objCatList->SourceTable." WHERE ParentPath LIKE '".$path."%'";
$ado->Execute("CREATE TABLE $table ".$sql);
}
else
{
$sql = "SELECT CategoryId,ParentPath FROM ".$objCatList->SourceTable;
$objEditTable->SourceTable = $objCatList->SourceTable;
$table = $objCatList->SourceTable;
}
$NumCats = TableCount($table,"",0);
}
// init vars
if( !isset($NumCats) ) $NumCats = 0;
if( !isset($CatIndex) ) $CatIndex = 0;
if(is_numeric($_GET["CatIndex"]))
{
$NumCats = $_REQUEST['NumCats'];
$CatIndex = (int)$_REQUEST['CatIndex'];
$table = ($objCatList->CurrentCategoryID() > 0) ? $objSession->GetEditTable("Category") : $objCatList->SourceTable;
//echo $NumCats." Loaded <br>\n";
$title = prompt_language("la_prompt_updating")." ".prompt_language("la_Text_Categories");
$title .= " $CatIndex / $NumCats ".prompt_language("la_Text_complete");
}
else
$title = prompt_language("la_prompt_updating")." ".prompt_language("la_Text_Categories");
$sql = "SELECT * FROM $table ORDER BY ParentPath ASC LIMIT $CatIndex,$CatsPerLoad";
$start = getmicrotime();
//echo $sql."<br>\n";
$objCatList->Query_Item($sql);
//echo getmicrotime() - $start." QUERY ".$x."<br>\n";
$x = 0;
foreach($objCatList->Items as $cat)
{
// echo getmicrotime() - $start." START ".$x."<br>\n";
$cat->UpdateACL();
// echo getmicrotime() - $start." ACL ".$x."<br>\n";
$cat->UpdateCachedPath();
// echo getmicrotime() - $start." PATH ".$x."<br>\n";
$x++;
// echo "<br>\n";
// echo $cat->Get("ParentPath")."<br>\n";
// $cat->UpdateCacheCounts();
// $objSystemCache->PurgeCategory($cat->Get("CategoryId"));
}
$no_url = $adminURL.'/'.$objSession->GetVariable('ReturnScript').'?env='.BuildEnv();
$yes_url = $_SERVER['PHP_SELF'].'?env='.BuildEnv().'&CatIndex=0&NumCats='.$NumCats;
$cat_update = $objSession->GetVariable('PermCache_UpdateRequired');
int_header(NULL,NULL,$title);
?>
<TABLE cellspacing="0" cellpadding="2" width="100%" border="0" class="tableborder">
<script language="javascript">
function goto_url(url)
{
document.location = url;
}
<?php if( !$cat_update )
{
$objSession->SetVariable('PermCache_UpdateRequired', 0);
echo "goto_url('$no_url');\n";
}
?>
</script>
<?php
if(!is_numeric($_GET["CatIndex"]) && $NumCats > $CatsPerLoad)
{
int_subsection_title(prompt_language("la_confirm_maintenance"));
?>
<tr>
<td align="center" colspan="3" bgcolor="#FFFFFF"><?php echo prompt_language("la_prompt_perform_now"); ?></td>
</tr>
<tr>
<td align="right" width="50%">
<input type="button" name="yes_btn" value="<?php echo admin_language("lu_yes"); ?>" onclick="javascript:goto_url('<?php echo $yes_url; ?>');" class="button">
</td>
<td><img src="<?php echo $imagesURL; ?>/spacer.gif" width="10"></td>
<td align="left" width="50%">
<input type="button" name="yes_btn" value="<?php echo admin_language("lu_no"); ?>" onclick="javascript:goto_url('<?php echo $no_url; ?>');" class="button">
</td>
</tr>
</table>
<?php
int_footer();
die();
}
?>
<?php int_subsection_title(""); ?>
<?php
if($NumCats==0)
{
$percent=100;
}
else
{
$percent = (int)(($CatIndex/$NumCats) * 100);
}
if(is_numeric($_GET["CatIndex"]))
{
if ($percent == 0)
{
echo "<TR>";
echo "<TD BGCOLOR=\"#FFFFFF\" width=\"100%\" >$percent";
echo "%</td></TR>";
}
else if ($percent < 60)
{
echo "<TR><TD BGCOLOR=\"#4682B2\" width=\"".$percent."%\" >";
$row2 = 100-$percent;
echo "</td> <TD BGCOLOR=\"#FFFFFF\" width=\"".$row2."%\" > $percent";
echo "%</td></TR>";
}
else if ($percent == 100)
{
echo "<TR><TD BGCOLOR=\"#4682B2\" align=\"right\" width=\"100%\" ><FONT COLOR=\"#FFFFFF\">$percent%</FONT></td>";
}
else
{
echo "<TR><TD BGCOLOR=\"#4682B2\" align=\"right\" width=\"".$percent."%\" ><FONT COLOR=\"#FFFFFF\">$percent%</FONT>";
$row2 = 100-$percent;
echo "</td> <TD BGCOLOR=\"#FFFFFF\" width=\"".$row2."%\" ></td></TR>";
}
}
flush();
?>
</TABLE>
<?php
if($CatIndex+1 >$NumCats)
{
$objSession->SetVariable('PermCache_UpdateRequired', 0);
$target = $adminURL."/".$objSession->GetVariable('ReturnScript').'?env='.BuildEnv(); //$adminURL."/browse.php?env=".BuildEnv();
}
else
{
$next = $CatIndex+$CatsPerLoad;
if($next > $NumCats)
{
$objSession->SetVariable('PermCache_UpdateRequired', 0);
$target = $adminURL."/".$objSession->GetVariable('ReturnScript').'?env='.BuildEnv(); //$adminURL."/browse.php?env=".BuildEnv();
}
else
$target = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&CatIndex=".$next."&NumCats=$NumCats";
}
//print "<A HREF=\"$target\">$target</A>";
print "<script language=\"javascript\">" ;
print "setTimeout(\"document.location='$target';\",40);";
print " </script>";
?>
<?php int_footer(); ?>
Property changes on: trunk/admin/category/category_maint.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/admin/category/addrelation.php
===================================================================
--- trunk/admin/category/addrelation.php (revision 270)
+++ trunk/admin/category/addrelation.php (revision 271)
@@ -1,281 +1,276 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
-//print_r($_GET);
-//print_r($_POST);
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
$cssURL = $adminURL."/include";
$browseURL = $adminURL."/browse";
//$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."/browse/toolbar.php");
require_once($pathtoroot.$admin."/listview/listview.php");
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot. $value."admin/include/parser.php";
if(file_exists($path))
{
include_once($path);
}
}
unset($objEditCat);
$objEditCat = new clsCatList();
$objEditCat->SourceTable = $objSession->GetEditTable("Category");
//Multiedit init
$en = (int)$_GET["en"];
$objEditCat->Query_Item("SELECT * FROM ".$objEditCat->SourceTable);
$itemcount=$objEditCat->NumItems();
$c = $objEditCat->GetItemByIndex($en);
unset($objEditItems);
$objEditItems = new clsRelationshipList();
$objEditItems->SourceTable = $objSession->GetEditTable("Relationship");
if(isset($_POST["itemlist"]))
{
if(is_array($_POST["itemlist"]))
{
$RelationId = $_POST["itemlist"][0];
}
else
{
$RelationId = $_POST["itemlist"];
}
+
$Rel = new clsRelationship();
$Rel->tablename = $objEditItems->SourceTable;
$Rel->LoadExpanded($RelationId);
$action = "m_edit_relation";
}
else
{
$Rel = new clsRelationship();
$Rel->Set("SourceType","1");
$Rel->Set("SourceId",$c->Get("ResourceId"));
$Rel->Set("TargetId",$_POST["TargetId"]);
$Rel->Set("TargetType",$_POST["TargetType"]);
$Rel->Set("Type","0");
$Rel->Set("Enabled","1");
$action = "m_add_relation";
}
$item = $Rel->GetTargetItemData();
-
$envar = "env=" . BuildEnv() . "&en=$en";
-
$section = 'in-portal:editcategory_relation';
$ado = GetADODBConnection();
-
-
/* page header */
print <<<END
<html>
<head>
<title>In-portal</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<meta http-equiv="Pragma" content="no-cache">
<script language="JavaScript">
imagesPath='$imagesURL'+'/';
</script>
<script src="$browseURL/common.js"></script>
<script src="$browseURL/toolbar.js"></script>
<script src="$browseURL/utility.js"></script>
<script src="$browseURL/checkboxes.js"></script>
<script language="JavaScript1.2" src="$browseURL/fw_menu.js"></script>
<link rel="stylesheet" type="text/css" href="$browseURL/checkboxes.css">
<link rel="stylesheet" type="text/css" href="$cssURL/style.css">
<link rel="stylesheet" type="text/css" href="$browseURL/toolbar.css">
END;
$title = prompt_language("la_Text_Editing")." ".prompt_language("la_Text_Category")." '".$c->Get("Name")."' - ".prompt_language("la_Text_Relation");
-$title .= " ".prompt_language("la_Text_to")." '".$item[$item["TitleField"]]."'";
+$title .= " ".prompt_language("la_Text_to")." '".$item["TitleField"]."'";
$objCatToolBar = new clsToolBar();
$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","do_edit_save('category','CatEditStatus','".$admin."/category/addcategory_relations.php',0);",$imagesURL."/toolbar/tool_select.gif");
$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","do_edit_save('category','CatEditStatus','".$admin."/category/addcategory_relations.php',-1);",$imagesURL."/toolbar/tool_cancel.gif");
int_header($objCatToolBar,NULL,$title);
if ($objSession->GetVariable("HasChanges") == 1) {
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
<tr>
<td valign="top">
<?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
</td>
</tr>
</table>
<?php } ?>
<TABLE cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
<FORM ID="category" NAME="category" method="POST" ACTION="">
<?php int_subsection_title("Relation"); ?>
<TR <?php int_table_color(); ?> >
<TD>
<span class="text"><?php echo prompt_language("la_prompt_RelationId"). ":</span></TD><TD>".$Rel->Get("RelationshipId"); ?>
</TD>
<TD>&nbsp;</TD>
</TR>
<TR <?php int_table_color(); ?> >
<TD><span class="text"><?php echo prompt_language("la_prompt_Item"); ?></SPAN></TD>
<TD>
- <IMG src="<?php echo $Rel->Admin_Icon(); ?>" align="absmiddle"><SPAN id="TargetName"><?php echo $item[$item["TitleField"]]; ?></SPAN> <SPAN ID="TargetTypeName">(<?php echo prompt_language("la_Text_".$item["SourceTable"]); ?>)</SPAN>
+ <IMG src="<?php echo $Rel->Admin_Icon(); ?>" align="absmiddle"><SPAN id="TargetName"><?php echo $item["TitleField"]; ?></SPAN> <SPAN ID="TargetTypeName">(<?php echo prompt_language("la_Text_".$item["SourceTable"]); ?>)</SPAN>
</TD>
<TD>&nbsp;</TD>
</TR>
<TR <?php int_table_color(); ?> >
<TD><span class="text"><?php echo prompt_language("la_prompt_Type"); ?></SPAN></TD>
<TD>
<?php
$Recip = "";
$OneWay = "";
if($Rel->Get("Type")=="1")
{
$Recip = " CHECKED";
}
else
$OneWay = " CHECKED";
?>
<input type="radio" name="RelType" VALUE=1 <?php echo $Recip; ?>><?php echo prompt_language("la_Text_Reciprocal"); ?>
<input type="radio" name="RelType" VALUE=0 <?php echo $OneWay; ?>><?php echo prompt_language("la_Text_OneWay"); ?>
</TD>
<TD>&nbsp;</TD>
</TR>
<TR <?php int_table_color(); ?> >
<TD><span class="text"><?php echo prompt_language("la_prompt_Enabled"); ?></SPAN></TD>
<TD>
<?php
$checked = "";
if($Rel->Get("Enabled")=="1")
{
$checked = " CHECKED";
}
?>
<input type="checkbox" VALUE="1" name="Enabled" <?php echo $checked; ?>>
</TD>
<TD>&nbsp;</TD>
</TR>
<TR <?php int_table_color(); ?> >
<TD><span class="text"><?php echo prompt_language("la_prompt_Priority"); ?></SPAN></TD>
<TD>
<INPUT TYPE="TEXT" SIZE="5" NAME="priority" VALUE="<?php echo $Rel->Get("Priority"); ?>">
</TD>
<TD>&nbsp;</TD>
</TR>
<input type="hidden" name="TargetId" value ="<?php echo $Rel->Get("TargetId"); ?>">
<input type="hidden" name="TargetType" value ="<?php echo $Rel->Get("TargetType"); ?>">
<input type="hidden" name="SourceType" value ="<?php echo $Rel->Get("SourceType"); ?>">
<input type="hidden" name="SourceId" value ="<?php echo $c->Get("ResourceId"); ?>">
<INPUT TYPE="hidden" NAME="RelationshipId" VALUE="<?php echo $Rel->Get("RelationshipId"); ?>">
<input type="hidden" name="Action" value="<?php echo $action; ?>">
<input type="hidden" name="CatEditStatus" VALUE="0">
</FORM>
</TABLE>
<FORM NAME="save_edit_buttons" ID="save_edit_buttons" method="POST" ACTION="">
<tr <?php int_table_color(); ?>>
<td colspan="3">
<input type=hidden NAME="Action" VALUE="save_cat_edit">
</td>
</tr>
</FORM>
<!-- CODE FOR VIEW MENU -->
<form method="post" action="user_groups.php?<?php echo $envar; ?>" name="viewmenu">
<input type="hidden" name="fieldname" value="">
<input type="hidden" name="varvalue" value="">
<input type="hidden" name="varvalue2" value="">
<input type="hidden" name="Action" value="">
</form>
<!-- END CODE-->
<?php int_footer(); ?>
Property changes on: trunk/admin/category/addrelation.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/install.php
===================================================================
--- trunk/admin/install.php (revision 270)
+++ trunk/admin/install.php (revision 271)
@@ -1,1920 +1,1920 @@
<?php
error_reporting(0);
//$new_version = '1.0.2';
define("GET_LICENSE_URL", "http://www.intechnic.com/myaccount/license.php");
define('BACKUP_NAME', 'dump(.*).txt'); // how backup dump files are named
$general_error = '';
if ($_POST['install_type'] != '') {
$install_type = $_POST['install_type'];
}
else if ($_GET['install_type'] != '') {
$install_type = $_GET['install_type'];
}
$force_finish = isset($_REQUEST['ff']) ? true : false;
$pathtoroot = "";
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
//$path=dirname(realpath($_SERVER['PATH_TRANSLATED']));
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;
}
}
if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php');
//if( !defined('DEBUG_MODE') ) error_reporting(0);
$path_char = GetPathChar();
//phpinfo(INFO_VARIABLES);
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
$is_install = TRUE;
$admin = substr($path,strlen($pathtoroot));
$state = isset($_GET["state"]) ? $_GET["state"] : '';
if(!strlen($state))
{
$state = $_POST["state"];
}
include($pathtoroot.$admin."/install/install_lib.php");
$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['SERVER_NAME'].$_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(strlen($g_DBType)>0 && 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();
if($ado)
{
$installed = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
}
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")
{
$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 (str_replace('.', '', $g_InPortal) >= 105) {
$act = 'check';
}
$rfile = @fopen(GET_LICENSE_URL."?login=".md5($_POST['UserName'])."&password=".md5($_POST['UserPass'])."&action=$act&license_code=".base64_encode($g_LicenseCode)."&version=".str_replace('.', '', GetMaxPortalVersion($pathtoroot.$admin))."&domain=".base64_encode($_SERVER['SERVER_NAME']), "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 == '') {
$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";
$rs = $ado->Execute($sql);
//echo '<pre>'.print_r($rs->GetRows(), true).'</pre>';
$i = 0;
while ($rs && !$rs->EOF) {
$p = strtolower($rs->fields['Name']);
// $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))
{
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
if ($file != '' && !strstr($file, 'changelog') && !strstr($file, 'readme')) {
$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 && str_replace('.', '', $file) > str_replace('.', '', $rs->fields['Version'])) {
//$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
//$rs2 = $ado->Execute($sql);
if ($Modules[$i-1] == $rs->fields['Name']) {
$Texts[$i-1] = $rs->fields['Name']." (".$rs->fields['Version']." ".prompt_language("la_to")." ".$file.")";
//$Modules[] = $rs->fields['Name'];
$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'];
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);
$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";
if (str_replace('.', '', $try_version) > str_replace('.', '', $current_version)) {
$filename = $pathtoroot.$mod_name."/admin/install/upgrades/inportal_upgrade_v$try_version.sql";
//echo "Trying Version: $try_version<br>";
if(file_exists($filename))
{
RunSQLFile($ado, $filename);
set_ini_value("Module Versions", $p, $try_version);
save_values();
}
}
}
}
}
$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;
if ($_POST['login'] != '' && $_POST['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=".str_replace('.', '', GetMaxPortalVersion($pathtoroot.$admin))."&domain=".base64_encode($_SERVER['SERVER_NAME']), "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=".str_replace('.', '', 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));
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;
switch($_POST["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:
$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))
{
$file = str_replace("inportal_upgrade_v", "", $file);
$file = str_replace(".sql", "", $file);
if ($file != '' && !strstr($file, 'changelog') && !strstr($file, 'readme')) {
if ($p == '') {
$p = 'in-portal';
}
$sql = "SELECT Version FROM ".$g_TablePrefix."Modules WHERE Name = '".$p."'";
$rs = $ado->Execute($sql);
if (str_replace(".", "", $rs->fields['Version']) < str_replace(".", "", $file)) {
$show_upgrade = true;
}
}
}
}
}
if ($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))
{
$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") {
$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");
}
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;
}
if ($_POST['next_step']) {
$next_step = $_POST['next_step'];
}
else if ($_GET['next_step']) {
$next_step = $_GET['next_step'];
}
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)
{
if ($_POST['next_step']) {
$next_step = $_POST['next_step'];
}
else if ($_GET['next_step']) {
$next_step = $_GET['next_step'];
}
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 $PhraseTable");
- $ado->Execute("DROP TABLE $EventTable");
+ $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( !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["SERVER_NAME"]);
//$g_DomainName= $_SERVER["SERVER_NAME"];
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['SERVER_NAME'].$_POST['Site_Path'])."&modules=".base64_encode($modules_str)."&license_code=".base64_encode($g_LicenseCode)."&version=".str_replace('.', '', GetMaxPortalVersion($pathtoroot.$admin))."&domain=".md5($_SERVER['SERVER_NAME']), "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>";
}
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;
}
if ($_POST['next_step']) {
$tmp_step = $_POST['next_step'];
}
else if ($_GET['next_step']) {
$tmp_step = $_GET['next_step'];
}
if (!$tmp_step) {
$tmp_step = 1;
}
if ($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 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 || $_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 == 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 == '') || $_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 == 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 == '') || $_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 } ?>>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 echo $title;?></td>
</tr>
<tr>
<td class="text"><?php 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.35
\ No newline at end of property
+1.36
\ No newline at end of property
Index: trunk/admin/templates/cat_select_element.tpl
===================================================================
--- trunk/admin/templates/cat_select_element.tpl (revision 270)
+++ trunk/admin/templates/cat_select_element.tpl (revision 271)
@@ -1,11 +1,11 @@
<TD>
<div inportaltype="categories">
<input type="checkbox" value="<inp:cat _field="resourceid"/>" name="catlist" ItemType="1">
<a href="<inp:cat _field="link_selector"/>"><img src="<inp:cat _field="admin_icon"/>" border="0"></a>
<span class="priority"><sup><inp:cat _field="priority"/></sup></span>
<a class="cat" href="<inp:cat _field="link_selector"/>"><inp:cat _field="name"/></a>:
<span class="cat_pick"><inp:cat _field="pick"/></SPAN>
<span class="cat_new"><inp:cat _field="new"/></SPAN>
- <span class="cat_desc"><inp:cat _field="desc"/></SPAN>
+ <span class="cat_desc"><inp:cat _field="description"/></SPAN>
</div>
</TD>
\ No newline at end of file
Property changes on: trunk/admin/templates/cat_select_element.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/backup/backup2.php
===================================================================
--- trunk/admin/backup/backup2.php (revision 270)
+++ trunk/admin/backup/backup2.php (revision 271)
@@ -1,328 +1,328 @@
<?php
//@set_time_limit(600);
$backup_inport = 1;
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
require_once($pathtoroot."kernel/startup.php");
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$adminURL = $rootURL.$admin;
$localURL=$rootURL."kernel/";
$imagesURL = $rootURL."admin/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");
global $tables;
unset($tables);
//$m = GetModuleArray();
//foreach($m as $key => $value)
//{
// $mod = $pathtoroot . $value . "admin/include/backup.php";
// require_once($mod);
//}
$section = "in-portal:backup_toolbar";
$envar = "env=" . BuildEnv();
$sec = $objSections->GetSection($section);
$title = admin_language("la_performing_backup")." - ".admin_language("la_Step")." 2";
int_header(NULL,NULL,$title);
/*******************************BEGINNING*********************************/
$conn = GetAdodbConnection();
$tables = $conn->MetaTables(); // array_keys($tables);
//echo "<pre>"; print_r($tables); echo "</pre>";
$prefix = GetTablePrefix();
//if(strlen($prefix))
//{
for($x=0;$x<count($tables);$x++)
{
if(substr($tables[$x],0,strlen($prefix))==$prefix)
{
if (!strstr($tables[$x], 'ses_')) {
$TableNames[] = $tables[$x];
}
}
}
//}
$num_tables = count($TableNames);
$tables = $TableNames;
$TableIndex = (int)$_GET["TableIndex"];
$SqlStart = (int)$_GET["Start"];
$filename=$objSession->GetVariable("backup_filename");
$filepath=$objConfig->Get("Backup_Path");
$filename = $filepath."/".$filename;
$PageTitle = admin_language("la_text_Backup_in_progress");
$CancelURL = $rootURL ."admin/backup/backup1.php?".$envar ;
if ($success==1)
{
finish();
}
$CurrentTable = $TableNames[$TableIndex];
$NumItems = TableCount($CurrentTable,"",0);
$caption = admin_language("la_Text_backing_up")." ".$CurrentTable." (".$NumItems." ".admin_language("la_Text_Rows").") ";
stats($caption,$SqlStart,$NumItems);
$out = array();
$caption = admin_language("la_Text_Table")." ".$TableIndex." ".admin_language("lu_of")." ".$num_tables." ";
stats($caption,$TableIndex,$num_tables);
if($SqlStart==0 && $TableIndex==0)
{
for($x=0;$x<count($TableNames);$x++) {
if (!strstr($TableNames[$x], 'ses_')) {
$out[] = GetTableCreate($conn,$TableNames[$x]);
}
}
}
if (!strstr($CurrentTable, 'ses_')) {
$RowCount = insert_data($CurrentTable,$SqlStart,50,"");
}
$fp = fopen($filename,"a");
if (filesize($filename) == 0) {
$ado = GetADODBConnection();
$sql = "SELECT Name, Version FROM ".GetTablePrefix()."Modules";
$r = $ado->Execute($sql);
while ($r && !$r->EOF) {
$version = $r->fields['Version'];
fwrite($fp, "# ".$r->fields['Name']." Version: $version;\n");
$r->MoveNext();
}
fwrite($fp, "#------------------------------------------\n\n");
}
if($fp)
{
fwrite($fp,implode("\n",$out));
fwrite($fp,"\n");
fclose($fp);
}
else
{
echo "Error opening $filename <br>\n";
exit();
}
$SqlStart += $RowCount;
if($SqlStart>=$NumItems)
{
$SqlStart = 0;
$TableIndex++;
}
if($TableIndex < $num_tables)
{
$url = $adminURL."/backup/backup2.php?".$envar."&TableIndex=$TableIndex&Start=$SqlStart";
}
else
{
$url = $adminURL."/backup/backup3.php?".$envar;
}
reload($url);
echo "</BODY></HTML>\n";
//extracts the rows of data from tables using limits
function insert_data($table, $start, $limit, $mywhere)
{
global $out;
$conn = GetAdodbConnection();
if ($mywhere !="")
{
$whereclause= " WHERE ".$mywhere." ";
}
else
{
$whereclause = "";
}
$rs = $conn->Execute("SELECT * from $table $whereclause LIMIT $start, $limit");
$prefix = GetTablePrefix();
$rowcount = 0;
while($rs && !$rs->EOF)
{
$temp=$conn->GetInsertSQL($rs,$rs->fields);
$temp=ereg_replace("\n","\\n", $temp);
$temp=ereg_replace("\r","\\r", $temp);
if(strlen($prefix))
{
$temp = str_replace("INSERT INTO $prefix","INSERT INTO ",$temp);
}
$out[] = $temp;
$rs->MoveNext();
$rowcount++;
}
return $rowcount;
}
function GetTableCreate($conn, $table, $crlf="\n")
{
- $schema_create = 'DROP TABLE ' . $table . ';' . $crlf;
+ $schema_create = 'DROP TABLE IF EXISTS ' . $table . ';' . $crlf;
$schema_create .="# --------------------------------------------------------".$crlf;
$conn->Execute("SET SQL_QUOTE_SHOW_CREATE = 0");
$result = $conn->Execute("SHOW CREATE TABLE $table");
if($result && !$result->EOF)
{
$tmpres = $result->fields; // mysql_fetch_array($result);
$pos = strpos($tmpres["Create Table"], ' (');
$pos2 = strpos($tmpres["Create Table"], '(');
if ($pos2 != $pos + 1)
{
$pos = $pos2;
$tmpres["Create Table"] = str_replace(",", ",\n ", $tmpres["Create Table"]);
}
$tmpres["Create Table"] = substr($tmpres["Create Table"], 0, 13)
. (($use_backquotes) ? $tmpres["Table"] : $tmpres["Table"])
. substr($tmpres["Create Table"], $pos);
$tmpres["Create Table"] = str_replace("\n", $crlf, $tmpres["Create Table"]);
if (preg_match_all('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', $tmpres["Create Table"], $regs)) {
if (!isset($sql_constraints)) {
if (isset($GLOBALS['no_constraints_comments'])) {
$sql_constraints = '';
} else {
$sql_constraints = $crlf . '#' . $crlf
. '# ' . $GLOBALS['strConstraintsForDumped'] . $crlf
. '#' . $crlf;
}
}
if (!isset($GLOBALS['no_constraints_comments'])) {
$sql_constraints .= $crlf .'#' . $crlf .'# ' . $GLOBALS['strConstraintsForTable'] . ' ' . $table . $crlf . '#' . $crlf;
}
$sql_constraints .= 'ALTER TABLE $table $crlf '
. preg_replace('/(,\r?\n|^)([\s]*)(CONSTRAINT|FOREIGN[\s]*KEY)/', '\1\2ADD \3', substr($regs[0][0], 2))
. ";\n";
$tmpres["Create Table"] = preg_replace('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', '', $tmpres["Create Table"]);
}
$schema_create .= $tmpres["Create Table"];
}
unset($rs);
if(strlen($schema_create))
{
- $schema_create = str_replace("DROP TABLE ".GetTablePrefix(),"DROP TABLE ",$schema_create);
+ $schema_create = str_replace("DROP TABLE IF EXISTS ".GetTablePrefix(),"DROP TABLE ",$schema_create);
$schema_create = str_replace("CREATE TABLE ".GetTablePrefix(),"CREATE TABLE ",$schema_create);
while(strlen($schema_create && substr($schema_create,-1)!=")"))
{
$schema_create = substr($schema_create,0,-1);
}
}
$schema_create .= "\n# --------------------------------------------------------\n";
return $schema_create;
}
function stats($caption,$myprogress,$totalnum)
{
global $rootURL, $CancelURL,$PageTitle;
if($totalnum>0)
{
$pct=round(($myprogress/ $totalnum)*100);
}
else
$pct = 100;
$o .="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">";
echo "\n";
$o .= int_subsection_title_ret($caption."-".$pct."%");
$o .= "<TR><TD align=\"middle\"><br />";
$o .= " <TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .=" <TR border=1><TD width=\"".$pct."%\" STYLE=\"background:url('".$rootURL."admin/images/progress_bar_segment.gif');\">&nbsp;</TD>";
$comp_pct = 100-$pct;
$o .= " <TD bgcolor=#FFFFFF width=\"".$comp_pct."%\"></TD></TR>";
$o .= " </TABLE>";
$o .= " <BR /><input type=button VALUE=\"".admin_language("la_Cancel")."\" CLASS=\"button\" ONCLICK=\"document.location='".$CancelURL."';\">";
echo $o."\n";
echo "</TD></TR></TABLE>";
}
function reload($url)
{
print "<script language=\"javascript\">" ;
print "setTimeout(\"document.location='$url';\",40);";
print " </script>";
//echo "<A HREF=\"$url\">Next </A>";
}
?>
\ No newline at end of file
Property changes on: trunk/admin/backup/backup2.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/config/missing_label_search.php
===================================================================
--- trunk/admin/config/missing_label_search.php (revision 270)
+++ trunk/admin/config/missing_label_search.php (revision 271)
@@ -1,270 +1,270 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
$FrontEnd=2;
require_once($pathtoroot."kernel/startup.php");
class clsLangParser extends clsTemplateList
{
function clsLangParser($TemplateRoot)
{
$this->clsTemplateList($TemplateRoot);
}
function ParseTag($raw)
{
$res = "";
//echo "Tag:".htmlentities($raw).":<br>\n";
if(strlen(trim($raw))>0)
{
$tag = new clsHtmlTag($raw);
switch($tag->name)
{
case "include":
case "perm_include":
$res = "<!-- include skipped -->";
break;
case "mod_include":
$res = "<!-- include skipped -->";
break;
default:
//if($tag->name=="m_language")
$res = $tag->Execute();
break;
}
unset($tag);
}
return $res;
}
}
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
$pathtolocal = $pathtoroot."in-news/";
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");
require_once($pathtoroot.$admin."/listview/listview.php");
$section = "in-portal:missing_label_search";
$FilesPerLoad = 20;
$ado = GetADODBConnection();
if($_GET["LangId"])
{
$LangId = $_GET["LangId"];
$ThemeId = $_GET["theme"];
$table = $objSession->GetSessionTable("_".$ThemeId."_labels");
- @$ado->Execute("DROP TABLE $table ");
+ @$ado->Execute("DROP TABLE IF EXISTS $table ");
$Phrases = new clsPhraseList();
$query = "SELECT * FROM ".$Phrases->SourceTable." WHERE PhraseId = -1";
$insert = "CREATE TABLE ".$table." ".$query;
$ado->Execute($insert);
$FileIndex = 0;
$objThemeFiles = new clsThemeFileList($ThemeId);
$NumFiles = TableCount($objThemeFiles->SourceTable,"ThemeId=$ThemeId",0);
$objSession->SetVariable("Missing_ThemeId",$ThemeId);
$objSession->SetVariable("Missing_LangId",$LangId);
}
else
{
$ThemeId = $objSession->GetVariable("Missing_ThemeId");
$table = $objSession->GetSessionKey()."_".$ThemeId."_labels";
$objThemeFiles = new clsThemeFileList($ThemeId);
$LangId = $objSession->GetVariable("Missing_LangId");
$FileIndex = $_GET["File"];
$NumFiles = $_GET["NumFiles"];
}
$l = $objLanguages->GetItem($LangId);
$name = $l->Get("PackName");
$objThemeList = new clsThemeList();
$Theme = $objThemeList->GetItem($ThemeId);
$theme_name = $Theme->Get("Name");
$sql = "SELECT * FROM $table";
$rs = $ado->Execute($sql);
$found = array();
while($rs && !$rs->EOF)
{
$p = $rs->fields["Phrase"];
if(!in_array($p,$found))
$found[] = $p;
$rs->MoveNext();
}
$subtitle = prompt_language("la_prompt_Theme").": ".$theme_name;
$title = prompt_language("la_Text_Scanning")." ".prompt_language("la_Text_Templates");
int_header(NULL,NULL,$title);
?>
<TABLE cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
<?php int_subsection_title($subtitle); ?>
<?php
if($NumFiles==0)
{
$percent=100;
}
else
{
$percent = (int)(($FileIndex/$NumFiles) * 100);
}
if ($percent == 0)
{
echo "<TR>";
echo "<TD BGCOLOR=\"#FFFFFF\" width=\"100%\" >$percent";
echo "%</td></TR>";
}
else if ($percent < 60)
{
echo "<TR><TD BGCOLOR=\"#4682B2\" width=\"".$percent."%\" >";
$row2 = 100-$percent;
echo "</td> <TD BGCOLOR=\"#FFFFFF\" width=\"".$row2."%\" > $percent";
echo "%</td></TR>";
}
else if ($percent == 100)
{
echo "<TR><TD BGCOLOR=\"#4682B2\" align=\"right\" width=\"100%\" ><FONT COLOR=\"#FFFFFF\">$percent%</FONT></td>";
}
else
{
echo "<TR><TD BGCOLOR=\"#4682B2\" align=\"right\" width=\"".$percent."%\" ><FONT COLOR=\"#FFFFFF\">$percent%</FONT>";
$row2 = 100-$percent;
echo "</td> <TD BGCOLOR=\"#FFFFFF\" width=\"".$row2."%\" ></td></TR>";
}
$sql = "SELECT * FROM ".$objThemeFiles->SourceTable." WHERE ThemeId=$ThemeId LIMIT $FileIndex,$FilesPerLoad";
$TemplateRoot = $Theme->ThemeDirectory()."/";
$objTemplate = new clsLangParser($TemplateRoot);
$objTemplate->SkipIncludes=1;
//$ForceLanguage = $LangId;
$LogPhraseLookups = TRUE;
$rs = $ado->Execute($sql);
while($rs && !$rs->EOF)
{
$path = "";
$p = $rs->fields["FilePath"];
if(strlen(trim($p)))
$path .= $p."/";
$path .= $rs->fields["FileName"];
$path = substr($path,0,-4);
//echo "Parsing $path <br>\n";
$html = $objTemplate->ParseTemplate($path);
//echo htmlentities($html)."<br>\n";
$rs->MoveNext();
}
if(is_array($MissingList))
{
for($x=0;$x<count($MissingList);$x++)
{
$next = $x + $FileIndex;
if(!in_array($MissingList[$x],$found))
{
$sql = "INSERT INTO $table (PhraseId,Phrase,Translation,PhraseType,LanguageId) VALUES (";
$sql .= $next.",'".$MissingList[$x]."','',1,$LangId)";
//echo $sql."<br>\n";
$ado->Execute($sql);
}
}
}
if($FileIndex >=$NumFiles)
{
$target = $adminURL."/config/missing_label_edit.php?env=".BuildEnv()."&lpn=1";
}
else
{
$next = $FileIndex+$FilesPerLoad;
$target = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&File=".$next."&NumFiles=$NumFiles";
}
?>
</TABLE>
<?php int_footer(); ?>
<?php
flush();
print "<script language=\"javascript\">";
print " location.href='$target';";
print " </script>";
//print "<A HREF=\"$target\">$target</A>";
?>
Property changes on: trunk/admin/config/missing_label_search.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/config/importlang_progress.php
===================================================================
--- trunk/admin/config/importlang_progress.php (revision 270)
+++ trunk/admin/config/importlang_progress.php (revision 271)
@@ -1,329 +1,329 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
$FrontEnd=2;
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
// $pathtolocal = $pathtoroot."in-link/";
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");
require_once($pathtoroot.$admin."/listview/listview.php");
include_once($pathtoroot."kernel/include/xml.php");
$section = "in-portal:lang_import";
$ado = GetADODBConnection();
$MaxInserts = 200;
$PhraseTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportPhrases";
$EventTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportEvents";
$OverWrite = $_POST['overwrite'];
if(count($_POST)>0)
{
$Offset = 0;
$CurrentLang=0;
$file = $_FILES["lang_file"];
if(is_array($file))
{
if((int)$file["size"]>0)
{
move_uploaded_file($file["tmp_name"],$pathtoroot.$admin."/export/".$file["name"]);
$filename = $pathtoroot.$admin."/export/".$file["name"];
if(file_exists($filename))
{
/* parse xml file */
$fp = @fopen($filename,"r");
$xml = @fread($fp,filesize($filename));
@fclose($fp);
$objInXML = new xml_doc($xml);
$objInXML->parse();
$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 = "ALTER TABLE $EventTable ADD `Type` INT(11) default 0";
//$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();
}
$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");
}
else
{
$l = new clsLanguage();
$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();
}
}
}
$Types = implode(",",$_POST["langtypes"]);
$objSession->SetVariable("lang_types",$Types);
$objSession->SetVariable("lang_overwrite",(int)$_POST["overwrite"]);
$Total = TableCount($PhraseTable,"PhraseType IN ($Types)",0);
$objSession->SetVariable("phrase_total",$Total);
$Total = TableCount($EventTable,"",0);
$objSession->SetVariable("event_total",$Total);
$Offset = 0;
$Status = 0;
//unlink($filename);
}
}
}
}
}
else
{
$Offset = (int)$_GET["Offset"];
$Status = (int)$_GET["Status"];
$OverWrite = $objSession->GetVariable("lang_overwrite");
$Types = $objSession->GetVariable("lang_types");
if($Status==0)
{
$Total = $objSession->GetVariable("phrase_total");
}
else
$Total = $objSession->GetVariable("event_total");
}
//echo $Total;
if ($Total == "") {
$url = $adminURL."/config/importlang.php?env=".BuildEnv()."&importerror=1";
Header("Location: $url");
//reload($url);
}
$title = admin_language("la_Text_LangImport")." - ".admin_language("la_Step")." 2";
int_header(NULL,NULL, $title);
?>
<TABLE cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
<?php
if($Status==0)
{
$Total = $objSession->GetVariable("phrase_total");
stats(prompt_language("la_lang_import_progress"),$Offset,$Total);
$Offset = $objLanguages->ReadImportTable($PhraseTable,1,$Types,$OverWrite,$MaxInserts,$Offset);
if($Offset<$Total)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=$Offset&Status=0";
}
else
{
if($objSession->GetVariable("event_total")>0)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=0&Status=1";
}
else
$url = $adminURL."/config/config_lang.php?env=".BuildEnv();
}
reload($url);
}
else
{
$Total = $objSession->GetVariable("event_total");
$Offset = $objMessageList->ReadImportTable($EventTable,$OverWrite,$MaxInserts,$Offset);
if($Offset<$Total)
{
$url = $_SERVER["PHP_SELF"]."?env=".BuildEnv()."&Offset=$Offset&Status=1";
}
else
{
- $ado->Execute("DROP TABLE $PhraseTable");
- $ado->Execute("DROP TABLE $EventTable");
+ $ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+ $ado->Execute("DROP TABLE IF EXISTS $EventTable");
$url = $adminURL."/config/config_lang.php?env=".BuildEnv();
}
stats(prompt_language("la_event_import_progress"),$Offset,$Total);
reload($url);
}
function stats($caption,$myprogress,$totalnum)
{
global $rootURL, $CancelURL, $PageTitle;
if($totalnum>0)
{
$pct=round(($myprogress/ $totalnum)*100);
}
else
$pct = 100;
$o .="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">";
echo "\n";
$o .= int_subsection_title_ret($caption." - ".$pct."%");
$o .= "<TR><TD align=\"middle\"><br />";
$o .= " <TABLE CLASS=\"tableborder_full\" width=\"75%\">";
$o .=" <TR border=1><TD width=\"".$pct."%\" STYLE=\"background:url('".$rootURL."admin/images/progress_bar_segment.gif');\">&nbsp;</TD>";
$comp_pct = 100-$pct;
$o .= " <TD bgcolor=#FFFFFF width=\"".$comp_pct."%\"></TD></TR>";
$o .= " </TABLE>";
$o .= " <BR /><input type=button VALUE=\"".admin_language("la_Cancel")."\" CLASS=\"button\" ONCLICK=\"document.location='".$CancelURL."config_lang.php?env=".BuildEnv()."&action=cancel';\">";
echo $o."\n";
echo "</TD></TR></TABLE>";
}
function reload($url)
{
print "<script language=\"javascript\">" ;
print "setTimeout(\"document.location='$url';\",100);";
print " </script>";
//echo "<A HREF=\"$url\">Next </A>";
}
?>
<?php int_footer(); ?>
Property changes on: trunk/admin/config/importlang_progress.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/config/config_lang.php
===================================================================
--- trunk/admin/config/config_lang.php (revision 270)
+++ trunk/admin/config/config_lang.php (revision 271)
@@ -1,240 +1,240 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo $pathtoroot;
require_once($pathtoroot."kernel/startup.php");
//admin only util
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
//$pathtolocal = $pathtoroot."in-news/";
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");
require_once($pathtoroot.$admin."/listview/listview.php");
$section = "in-portal:configure_lang";
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot. $value."admin/include/parser.php";
if(file_exists($path))
{
include_once($path);
}
}
unset($objEditItems);
$envar = "env=".BuildEnv();
$formaction = $_SERVER["PHP_SELF"]."?".$envar;
$sec = $objSections->GetSection($section);
$objListToolBar = new clsToolBar();
$objListToolBar->Set("section",$section);
$objListToolBar->Set("load_menu_func","");
$objListToolBar->Set("CheckClass","LangChecks");
$objListToolBar->Set("CheckForm","languages");
$listImages = array();
//$img, $alt, $link, $onMouseOver, $onMouseOut, $onClick
$objListToolBar->Add("new_lang", "la_ToolTip_New_LangPack",$adminURL."/config/addlang.php?$envar&new=1","swap('new_lang','toolbar/tool_new_language_f2.gif');",
"swap('new_lang', 'toolbar/tool_new_language.gif');","",$imagesURL."/toolbar/tool_new_language.gif");
$objListToolBar->Add("import_lang", "la_ToolTip_Import_LangPack",$adminURL."/config/importlang.php?$envar","swap('import_lang','toolbar/tool_import_language_f2.gif');",
"swap('import_lang', 'toolbar/tool_import_language.gif');","",$imagesURL."/toolbar/tool_import_language.gif");
$objListToolBar->Add("lang_edit","la_ToolTip_Edit","#", "if (LangChecks.itemChecked()) swap('lang_edit','toolbar/tool_edit_f2.gif');",
"if (LangChecks.itemChecked()) swap('lang_edit', 'toolbar/tool_edit.gif');","if (LangChecks.itemChecked()) LangChecks.check_submit('addlang', '');",
"tool_edit.gif",TRUE,TRUE);
$listImages[] = "LangChecks.addImage('lang_edit','$imagesURL/toolbar/tool_edit.gif','$imagesURL/toolbar/tool_edit_f3.gif',1); ";
$objListToolBar->Add("lang_del","la_ToolTip_Delete","#", "if (LangChecks.itemChecked()) swap('lang_del','toolbar/tool_delete_f2.gif');",
"if (LangChecks.itemChecked()) swap('lang_del', 'toolbar/tool_delete.gif');","if (LangChecks.itemChecked()) LangChecks.check_submit('config_lang', 'm_lang_delete');",
"tool_delete.gif",FALSE,TRUE);
$listImages[] = "LangChecks.addImage('lang_del','$imagesURL/toolbar/tool_delete.gif','$imagesURL/toolbar/tool_delete_f3.gif',1); ";
$objListToolBar->Add("lang_export","la_ToolTip_Export","#", "if (LangChecks.itemChecked()) swap('lang_export','toolbar/tool_export_language_f2.gif');",
"if (LangChecks.itemChecked()) swap('lang_export', 'toolbar/tool_export_language.gif');","if (LangChecks.itemChecked()) LangChecks.check_submit('addlang_export', '');",
"tool_export_language.gif");
$listImages[] = "LangChecks.addImage('lang_export','$imagesURL/toolbar/tool_export_language.gif','$imagesURL/toolbar/tool_export_language_f3.gif',1); ";
$objListToolBar->AddToInitScript($listImages);
$objListToolBar->AddToInitScript("fwLoadMenus(); \n");
$objLang = new clsLanguageList();
$SearchWords = $objSession->GetVariable("LangSearchWord");
if(strlen($SearchWords))
{
$where = $objLang->AdminSearchWhereClause($SearchWords);
}
else
$where = "";
$order = trim($objConfig->Get("Lang_LV_Sortfield")." ".$objConfig->Get("Lang_LV_Sortorder"));
$sql = "SELECT l.*,ELT(l.Enabled+1,'".prompt_language("la_Text_Disabled")."','".prompt_language("la_Text_Enabled")."') as Status ";
$sql .= "FROM ".GetTablePrefix()."Language as l ";
if(strlen($where))
$sql .= "WHERE ".$where." ";
if(strlen($order))
$sql .= "ORDER BY ".$order;
$sql .= GetLimitSQL($objSession->GetVariable("Page_LV_Lang"),$objConfig->Get("Perpage_LV_Lang"));
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
$objLanguages->Query_Item($sql);
$itemcount = TableCount(GetTablePrefix()."Language", $where,0);
$objListView = new clsListView($objListToolBar,$objLanguages);
$objListView->IdField = "LanguageId";
$order = $objConfig->Get("Lang_LV_Sortfield");
$objListView->ColumnHeaders->Add("PackName",admin_language("la_prompt_PackName"),1,0,$order,"width=\"30%\"","Lang_LV_Sortfield","Lang_LV_Sortorder","PackName");
$objListView->ColumnHeaders->Add("LocalName",admin_language("la_prompt_Name"),1,0,$order,"width=\"30%\"","Lang_LV_Sortfield","Lang_LV_Sortorder","LocalName");
$objListView->ColumnHeaders->Add("Status",admin_language("la_ColHeader_Status"),1,0,$order,"width=\"30%\"","Lang_LV_Sortfield","Lang_LV_Sortorder","Status");
$objListView->ColumnHeaders->SetSort($objConfig->Get("Lang_LV_Sortfield"), $objConfig->Get("Lang_LV_Sortorder"));
$objListView->PrintToolBar = FALSE;
$objListView->checkboxes = TRUE;
$objListView->CurrentPageVar = "Page_LV_Lang";
$objListView->PerPageVar = "Perpage_LV_lang";
$objListView->CheckboxName = "itemlist[]";
$objListView->SearchBar = TRUE;
$objListView->SearchKeywords = $SearchWords;
$objListView->SearchAction="m_lang_search";
$objListView->TotalItemCount = $itemcount;
for($i=0;$i<count($objLanguages->Items);$i++)
{
$objListView->RowIcons[] = $objLanguages->Items[$i]->AdminIcon();
}
if ($_GET['action'] == "cancel") {
$ado = GetADODBConnection();
$PhraseTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportPhrases";
$EventTable = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix()."ImportEvents";
- $ado->Execute("DROP TABLE $PhraseTable");
- $ado->Execute("DROP TABLE $EventTable");
+ $ado->Execute("DROP TABLE IF EXISTS $PhraseTable");
+ $ado->Execute("DROP TABLE IF EXISTS $EventTable");
}
$objListView->ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSortField,"","",0);
$title = prompt_language("la_Text_Configuration")." - ".prompt_language("la_tab_Regional")." ".prompt_language("la_Text_Settings");
$h = "\n\n<SCRIPT Language=\"JavaScript1.2\">\n".$objListView->GetViewMenu($imagesURL)."\n</SCRIPT>\n";
int_header($objListToolBar,NULL,$title, NULL, $h);
?>
<form name="languages" ID="languages" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar;?>" method=POST>
<table cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
<tbody>
<?php
print $objListView->PrintList();
?>
<input type="hidden" name="Action" value="m_config_lang">
</FORM>
<!-- CODE FOR VIEW MENU -->
<form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" name="viewmenu">
<input type="hidden" name="fieldname" value="">
<input type="hidden" name="varvalue" value="">
<input type="hidden" name="varvalue2" value="">
<input type="hidden" name="Action" value="">
</form>
<FORM ID="ListSearchForm" NAME="ListSearchForm" method="POST" action="<?php echo $_SERVER["PHP_SELF"]."?env=".BuildEnv(); ?>">
<INPUT TYPE="HIDDEN" NAME="Action" VALUE="">
<INPUT TYPE="HIDDEN" NAME="list_search">
</FORM>
<script src="<?php echo $adminURL; ?>/listview/listview.js"></script>
<script>
initSelectiorContainers();
<?php echo $objListToolBar->Get("CheckClass").".setImages();"; ?>
</script>
<?php int_footer(); ?>
Property changes on: trunk/admin/config/config_lang.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1
\ No newline at end of property
+1.2
\ No newline at end of property
Index: trunk/admin/install/install_lib.php
===================================================================
--- trunk/admin/install/install_lib.php (revision 270)
+++ trunk/admin/install/install_lib.php (revision 271)
@@ -1,670 +1,670 @@
<?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 GetMaxPortalVersion($admindirname)
{
$dir = @dir($admindirname.'/install/upgrades');
$version = '';
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')) {
if (str_replace('.', '', $file) > str_replace('.', '', $version)) {
$version = $file;
}
}
}
}
return $version;
}
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;
$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 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
echo "in_ere";
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';
}
?>
Property changes on: trunk/admin/install/install_lib.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/admin/import/import.php
===================================================================
--- trunk/admin/import/import.php (revision 270)
+++ trunk/admin/import/import.php (revision 271)
@@ -1,941 +1,941 @@
<?php
#import script
#taking care of actual importing from in-link db to in-portal db
if(!strlen($pathtoroot))
{
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
require_once($pathtoroot."kernel/startup.php");
$admin = $objConfig->Get("AdminDirectory");
if(!strlen($admin))
$admin = "admin";
if ($_POST["Action"]=="Import")
{
$objSession->SetVariable("import_user_admin",$_POST["user_admin"]);
$objSession->SetVariable("import_user_regular",$_POST["user_regular"]);
$objSession->SetVariable("import_init_cat",$_POST["init_cat"]);
$objSession->SetVariable("image_name",$_POST["image_name"]);
$objSession->SetVariable("importtodo","initialize");
$objSession->SetVariable("importstart",0);
$objSession->SetVariable("importtotal",0);
if((int)$_POST["init_cat"]>0)
{
$c = $objCatList->GetItemByField("ResourceId",(int)$_POST["init_cat"]);
$c->UpdateACL();
$c->UpdateCachedPath();
}
}
$allgroups = $objGroups->GetAllGroupList();
$inlink_sql_type=$objSession->GetVariable("import_inlink_sql_type");
$inlink_server=$objSession->GetVariable("import_inlink_server");
$inlink_db=$objSession->GetVariable("import_inlink_db");
$inlink_user=$objSession->GetVariable("import_inlink_user");
$inlink_pass=$objSession->GetVariable("import_inlink_pass");
$user_admin=$objSession->GetVariable("import_user_admin");
$user_regular=$objSession->GetVariable("import_user_regular");
if(!is_object($c))
$c = $objCatList->GetItemByField("ResourceId",$objSession->GetVariable("import_init_cat"));
$init_cat= $c->Get("CategoryId");
$image_name=$objSession->GetVariable("image_name");
$start = $objSession->GetVariable("importstart");
$acl = explode(",",$c->GetACL("CATEGORY.VIEW"));
//IN-LINK connection
$linkconn=&ADONewConnection($inlink_sql_type);
$linkconn->PConnect($inlink_server, $inlink_user, $inlink_pass, $inlink_db);
if(!$linkconn)
{ echo "Database connection failed. DB Type: $sql_type, DB Server: $inlink_server, DB User: $inlink_user, DB Name: $inlink_db"; //fatal;
echo $linkconn->ErrorMsg();
die();
}
if($pconnect)
{
$linkconn->Close();
$linkconn = ADONewConnection($inlink_sql_type);
$linkconn->PConnect($inlink_server, $inlink_user, $inlink_pass, $inlink_db);
}
//admin only util
$pathtolocal = $pathtoroot."kernel/";
require_once ($pathtoroot."admin/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once ($pathtolocal."admin/include/navmenu.php");
require_once($pathtoroot."admin/toolbar.php");
//Set Section
$section = "in-portal:inlink_inport";
//Set Environment Variable
$envar = "env=" . BuildEnv();
$sec = $objSections->GetSection($section);
$objCatToolBar = new clsToolBar();
$title = admin_language("la_performing_import")." - ".admin_language("la_Step")." 4";
//In-Portal
$portalconn = GetAdodbConnection();
$TablePrefix = "ses_".$objSession->GetSessionKey()."_".GetTablePrefix();
$olddbname=$inlink_db;
//$newdbname="inportal";
$newdbname=$g_DBName;
##############creating a temproary table have to be here
if ($_POST["Action"]=="Import")
{
- $portalconn->Execute("DROP TABLE ".$TablePrefix."import");
- $portalconn->Execute("DROP TABLE ".$TablePrefix."importcat");
+ $portalconn->Execute("DROP TABLE IF EXISTS ".$TablePrefix."import");
+ $portalconn->Execute("DROP TABLE IF EXISTS ".$TablePrefix."importcat");
$temptable = "CREATE TABLE ".$TablePrefix."import (otname varchar(40), oid int(11), ocustomid int(11), oparentid int(11), ntname varchar(40), nid int(11), nrid int(11), npid int(11)) ";
$portalconn->Execute($temptable);
$cattable ="CREATE TABLE ".$TablePrefix."importcat (op int(11), np int(11), flag int(11)) ";
$portalconn->Execute($cattable);
$newcat = 1;
}
global $admin, $pathtoroot;
require_once ($pathtoroot.$admin."/import/status.php"); #for status bar and all visual effects
$todo= $objSession->GetVariable("importtodo");
$total = $objSession->GetVariable("importtotal");
switch ($todo)
{
case "users":
status($start, $total, "users");
usersimport();
//setstart(0,"cats"); #for debugging
break;
case "cats":
status($start, $total, "cats");
catmanager();
#setstart(0,"links"); #for debugging
break;
case "links":
status($start, $total, "links");
linksimport();
#setstart(0,"custom");#For debugging only
break;
case "custom":
status($start, $total, "custom");
customimport();
#setstart(0,"relcat");#for debuggin only
break;
case "relcat":
status($start, $total, "relcat");
relcatimport();
#setstart(0,"terminate"); #for debuggin only
break;
case "terminate":
terminator();
status(1,1,"terminate");
break;
default:
status(0,0,"initializing");
setstart(0,"users"); #to start importing from users first
break;
}
function terminator()
{
global $portalconn, $TablePrefix;
$query="DROP TABLE IF EXISTS ".$TablePrefix."import, ".$TablePrefix."importcat";
$portalconn->Execute($query);
}
function reload()
{
global $newurl;
print '<script language="javascript">' ;
print " setTimeout('location.href=location.href',40);";
print ' </script>';
}
function setstart($mystart, $part)
{
global $objSession;
$objSession->SetVariable("importstart",$mystart);
$objSession->SetVariable("importtodo",$part);
reload();
}
function settotal($total)
{
global $objSession;
$objSession->SetVariable("importtotal",$total);
}
//users import from inlink to inportal
function usersimport()
{
global $objUsers, $objSession, $linkconn, $portalconn, $olddbname,
$user_admin,$objGroups, $user_regular, $start, $TablePrefix;
$counter = 0;
$limit = 350;
$oldtablename = "inl_users";
$newtablename = $objUsers->SourceTable;
if ($start == 0)
{
$query="select count(*) as NumUsers from inl_users";
$row =$linkconn->Execute($query);
if ($row && !$row->EOF)
{
settotal($row->fields["NumUsers"]);
}
}
$query="select * from inl_users LIMIT $start, $limit";
$row =$linkconn->Execute($query);
while($row && !$row->EOF)
{
$counter++; #needed to know when close to time out
if ($row->fields['user_name'] != "root") {
$olduserid=$row->fields["user_id"];
//$Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="", $Status=2,
// $Phone="", $Street="", $City="", $State="", $Zip="", $Country=""
if($row->fields["user_status"]==1)
{
$Status=1;
}
else
{
if($row->fields["user_pend"]==0)
{
$Status=2;
}
else
$Status=0;
}
$u = $objUsers->Add_User( $row->fields["user_name"], $row->fields["user_pass"], $row->fields["email"],
$row->fields["user_date"], $row->fields["first"], $row->fields["last"],
$Status);
$oldid=$row->fields["user_id"];
$oldcustom=$row->fields["user_cust"];
$newid=$u->Get("PortalUserId");
$resid=$u->Get("ResourceId");
#adding user to usergroup
$userpermission = $row->fields["user_perm"];
if ($userpermission==2 || $userpermission==1)
{
$glist = explode(",",$user_admin);
$Primary=1;
for($i=0;$i<count($glist);$i++)
{
$group=$objGroups->GetItem($glist[$i]);
$group->AddUser($newid,$Primary);
$Primary = 0;
}
}
else
{
$glist = explode(",",$user_regular);
$Primary=1;
for($i=0;$i<count($glist);$i++)
{
$group=$objGroups->GetItem($glist[$i]);
$group->AddUser($newid,$Primary);
$Primary = 0;
}
}
//$group=$objGroups->GetItem($g);
//$group->AddUser($newid,1);
#inserting values to the temproary table
$totemp = "INSERT INTO ".$TablePrefix."import (otname,oid,ocustomid,oparentid,ntname,nid,nrid,npid) ";
$tovalues= " VALUES ('$oldtablename',$olduserid,$oldcustom,0,'$newtablename', $newid, $resid, 0 )";
$totemp=$totemp.$tovalues;
$portalconn->Execute($totemp);
}
$row->moveNext();
}
if ($counter == $limit)
{
setstart($start+$limit, "users");
}
else
setstart(0,"cats");
}
//END OF USERS IMPORT ^^^^^^^^^^^^^^^^^^^^^
//Categories Import
function catmanager()
{
global $portalconn, $init_cat,$start,$TablePrefix;
if ($start == 0)
{
$counter = catimport(0,$init_cat);
setstart($counter,"cats");
$portalconn->Execute("UPDATE ".$TablePrefix."importcat SET flag=1 WHERE np=$init_cat");
}
else
{
$query="select * from ".$TablePrefix."importcat WHERE flag=0 LIMIT 0,1";
$row =$portalconn->Execute($query);
if($row && !$row->EOF)
{
$oldid= $row->fields["op"];
$newid = $row->fields["np"];
$counter= catimport($oldid,$newid);
$query2="UPDATE ".$TablePrefix."importcat SET flag=1 WHERE op=$oldid and np=$newid";
$portalconn->Execute($query2);
setstart($counter+$start-1,"cats");
$x=5;
}
else
{
setstart(0,"links");
}
}
}
#pushes into the quque
function pushid($op,$np)
{
global $linkconn, $portalconn, $TablePrefix;
$addnew = "INSERT INTO ".$TablePrefix."importcat (op,np,flag) VALUES ($op,$np,0)";
$portalconn->Execute($addnew);
}
function checkifexist($id)
{
global $linkconn;
$addnew = "select * from inl_cats where cat_sub=$id";
$row =$linkconn->Execute($addnew);
if ($row && !$row->EOF)
{
if ($row->fields["cat_id"] !=0)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
#import itself
function catimport($oldparentid, $parentid)
{
global $objCatList, $linkconn, $objUsers, $linkconn, $portalconn,
$olddbname, $user_admin,$objGroups, $user_regular, $acl,$allgroups,
$c, $start, $TablePrefix;
$counter=0;
$objCacheCount = new clsCacheCountList();
if ($start == 0)
{
$query="select count(*) as CatCount from inl_cats";
$row =$linkconn->Execute($query);
if ($row && !$row->EOF)
{
settotal($row->fields["CatCount"]);
$catcount = $row->fields["CatCount"];
$catcount += (int)$c->Get("CachedDescendantCatsQty");
$c->Set("CachedDescendantCatsQty",$catcount);
$c->Update();
}
}
$query="select * from inl_cats WHERE cat_sub=$oldparentid";
$oldtablename = "inl_cats";
$newtablename = "Category";
$row =$linkconn->Execute($query);
if($row && !$row->EOF)
{
$RowCount = $row->NumRows();
$ResInc = $RowCount;
$ResourceId = GetNextResourceId($ResInc);
}
if($parentid>0)
{
$ParentCat = new clsCategory($parentid);
$Path = $ParentCat->Get("ParentPath");
}
while($row && !$row->EOF)
{
$counter++;
$cat = new clsCategory();
if($row->fields["cat_pend"]==0)
{
$Status=1;
}
else
{
if($row->fields["cat_vis"]==0)
{
$Status=2;
}
else
$Status=0;
}
$CreatedById = getnewid($row->fields["cat_id"]);
$cat->Set(array("ParentId", "Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem",
"NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById",
"CachedDescendantCatsQty"),
array($parentid, $row->fields["cat_name"], $row->fields["cat_desc"],
$row->fields["cat_date"], (int)$row->fields["cat_pick"], $Status, 2, 2, 2, 0,
$row->fields["meta_keywords"],$row->fields["meta_desc"],
(int)$CreatedById,(int)$row->fields["cat_cats"]));
$cat->Set("ResourceId",$ResourceId);
$ResourceId++;
$cat->Create();
$FullPath = $Path.$cat->Get("CategoryId")."|";
$cat->Set("ParentPath",$FullPath);
$cat->SetViewPerms("CATEGORY.VIEW",$acl,$allgroups);
$cat->SetViewPerms("LINK.VIEW",$acl,$allgroups);
$cat->Update();
$cat->UpdateCachedPath();
$objCacheCount->CategoryId= $cat->Get("CategoryId");
$objCacheCount->SetValue(0,0,0,0,0);
$newid = $cat->Get("CategoryId");
$resid = $cat->Get("ResourceId");
$oldid = $row->fields["cat_id"];
$oldcustom = $row->fields["cat_cust"];
$oldpid = $row->fields["cat_sub"];
#inserting values to the temproary table
$totemp = "INSERT INTO ".$TablePrefix."import (otname,oid,ocustomid,oparentid,ntname,nid,nrid,npid) ";
$tovalues= " VALUES ('$oldtablename',$oldid,$oldcustom,$oldpid,'$newtablename', $newid, $resid, $parentid )";
$totemp=$totemp.$tovalues;
$portalconn->Execute($totemp);
#pushes into the queue
if(checkifexist($oldid))
{
pushid($oldid,$newid);
}
$row->moveNext();
}
// disable lost+found category (if found one)
$tmp_cat = $objCatList->GetItemByField('Name','Lost+Found');
if( is_object($tmp_cat) )
{
$tmp_cat->Set('Status',0);
$tmp_cat->Update();
}
return $counter;
}
//Links Import
function linksimport()
{
global $objLinkList, $init_cat, $linkconn, $portalconn, $olddbname,
$user_admin,$objGroups, $user_regular, $start, $TablePrefix;
$limit = 750; #need to change to a higher number like 100, forty is only for debugging
$counter = 0;
set_time_limit(0);
if ($start == 0)
{
$query="select count(*) as LinkCount from inl_lc";
$row =$linkconn->Execute($query);
if ($row && !$row->EOF)
{
settotal($row->fields["LinkCount"]);
}
}
$query="select * from inl_lc INNER JOIN inl_links ON (inl_lc.link_id=inl_links.link_id) limit $start,$limit";
$oldtablename="inl_links";
$newtablename="link";
$row =$linkconn->Execute($query);
if($row && !$row->EOF)
{
$RowCount = $row->NumRows();
$ResInc = $RowCount;
$ResourceId = GetNextResourceId($ResInc);
}
while($row && !$row->EOF)
{
$counter++;
$oldid=$row->fields["link_id"];
$flag=1;
$oldcatid = $row->fields["cat_id"];
$pending = $row->fields["link_pend"];
#getting a new category id
$rs = $portalconn->Execute("SELECT nid FROM ".$TablePrefix."import WHERE ntname='Category' and oid=$oldcatid");
if ($rs && ! $rs->EOF)
{
$categoryid=$rs->fields["nid"];
}
else
{
$categoryid = $init_cat;
}
$rs = $portalconn->Execute("SELECT * FROM ".$TablePrefix."import WHERE otname='inl_link' AND oid='$oldid'");
if($rs && ! $rs->EOF)
{
$NewLinkId = $rs->fields["nid"];
}
else
$NewLinkId=0;
if ($NewLinkId==0)
{
#gets the new user id of the user who created a link
$newuserid=getnewid($row->fields["link_user"]);
#adds link to the IN-PORTAL
$link = new clsLink();
if($Pending==0)
{
$Status=1;
}
else
$Status=2;
$link->Set(array("Name", "Description", "Url", "CreatedOn", "Status", "EditorsPick",
"NewItem","PopItem","HotItem", "CreatedById", "CachedRating",
"CachedVotesQty","Hits", "Priority"),
array($row->fields["link_name"], $row->fields["link_desc"], $row->fields["link_url"], $row->fields["link_date"], $Status,
$row->fields["link_pick"], 2, 2, 2, $newuserid, (int)$row->fields["link_rating"],
(int)$row->fields["link_votes"],(int)$row->fields["link_hits"], 0));
$link->Set("ResourceId",$ResourceId);
$ResourceId++;
$link->Create();
$link->AddToCategory($categoryid,"",1);
$newid = $link->Get("LinkId");
$resid = $link->Get("ResourceId");
$oldcustom=$row->fields["link_cust"];
$linkimage =$row->fields["link_image"];
if ($linkimage)
{
addimage($resid,$linkimage);
}
#calls to import reviews
reviewimport($link,$oldid,$resid);
$parentid = 0;
$totemp = "INSERT INTO ".$TablePrefix."import (odb,otname,oid,ocustomid,oparentid,ndb,ntname,nid,nrid,npid) ";
$tovalues= " VALUES ('$olddbname','$oldtablename',$oldid,$oldcustom,$oldcatid,'inportal','$newtablename', $newid, $resid, $parentid )";
$totemp = $totemp.$tovalues;
//$portalconn->Execute($totemp);
}
else #if link is related to more than one category
{
$link = new clsLink($NewLinkId);
$link->AddtoCategory($categoryid,"",0);
}
#prelast while
$row->moveNext();
}
if ($counter == $limit)
{
setstart($start+$limit, "links");
}
else
{
setstart(0,"custom");
}
}
#importing image from the in-link
function addimage($resourceid, $imageurl)
{
global $objImageList, $image_name;
#echo "<br />IMAGE RESOURCEID: $resourceid IMAGE URL: $imageurl <br />";
if(!is_object($objImageList))
$objImageList = new clsImageList();
$LocalImage = 0;
$LocalThumb = 0;
if(!strlen($image_name))
$image_name="inlink_image";
$img = $objImageList->Add($image_name,"",$resourceid, 0, 0,"", $imageurl, 1,0, 1, 0,1);
}
#Reviews Import for links
function reviewimport($myclass,$oldid,$rid)
{
global $objCustomFieldList, $linkconn, $portalconn;
#ITEM AddReview($createdBy,$reviewText,0)
$query="select * from inl_reviews where rev_link= $oldid";
$row =$linkconn->Execute($query);
while($row && !$row->EOF)
{
$oldreviewuser= $row->fields["rev_user"];
if($oldreviewuser !=0) #meaning was not created by guest
{
$newrid=getnewid($oldreviewuser);
if ($newrid)
{
$temp=$myclass->AddReview($newrid,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");
}
else
{
$temp=$myclass->AddReview(0,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");
}
}
else #meaning was created by guest
{
$temp=$myclass->AddReview(0,$row->fields["rev_text"],0,"127.0.0.1",1, "In-Link");
}
$row->moveNext();
}
}
#HELPER FUNCTION THAT GETS THE NEW ID of the USER
function getnewid($oldid)
{
global $portalconn, $TablePrefix;
$query2="select * from ".$TablePrefix."import where otname='inl_users' and oid=".$oldid;
$row2=$portalconn->Execute($query2);
if ($row2->fields["nid"])
{
return $row2->fields["nid"];
}
else
{
return 0;
}
}
//^^^^^^^^^^^^^^^^^^^^^^ABOVE IS LINKS IMPORT
#########################################Custom Fields Import
#create a new CustomField first and then
#by selecting all and receiving from one record of inl_config the values of cc1,cc2,cc3,cc4,cc5,cc6,uc1,uc2,uc3,uc4,uc5,uc6,lc1,lc2,lc3,lc4,lc5,lc6
#go through all import table and if ocustomid occures get the row from inl_custom and
#create CustomMetaData field
#---------------------
#Regarding CustomField:
#FieldName= cc1,cc2 .... from inl_config
#FieldLabel= value of cc1, cc2 ....
#Type=4 for links 6 for users 0 category
#------------
#Regarding CustomMetaData
#ResourceId <= link id
#CustomFieldId <= id from the top
#Value = Value from the table custom
//VVVVV BELOW ARE CUSTOM FIELD IMPORT REQUIRES TO HAVE A TEMPROARY TABLE IMPORT
function customimport()
{
global $linkconn, $portalconn, $start, $TablePrefix;
$limit = 40; #just for debugging purposes, in real life set it to higher number
$counter=0;
if ($start == 0)
{
$r=buildfields();
$query="SELECT count(*) as cc from ".$TablePrefix."import WHERE NOT ocustomid=0";
$row =$portalconn->Execute($query);
if ($row && !$row->EOF)
{
settotal($row->fields["cc"]);
}
}
else
{
$r=getfields();
}
$query="SELECT * from ".$TablePrefix."import WHERE ocustomid!=0 limit $start,$limit";
$row =$portalconn->Execute($query);
while($row && !$row->EOF)
{
$counter++;
if ($row->fields["ocustomid"]!=0)
{
loadcustom($row->fields["ocustomid"],$row->fields["nrid"],$row->fields["otname"],$r);
}
$row->moveNext();
}
if ($counter == $limit)
{
setstart($start+$limit, "custom");
}
else
{
setstart(0,"relcat");
}
}
function loadcustom($customid,$rid,$tablename,$r)
{
global $linkconn, $objCustomDataList, $objSession;
$objCustomDataList->Clear();
if ($tablename =="inl_cats")
{
//$myfieldname="cc";
$fields = explode(",",$objSession->GetVariable("custom_category"));
}
else if($tablename =="inl_users")
{
//$myfieldname="uc";
$fields = explode(",",$objSession->GetVariable("custom_user"));
}
else if($tablename =="inl_links")
{
//$myfieldname="lc";
$fields = explode(",",$objSession->GetVariable("custom_links"));
}
$oldtablename="inl_links";
$newtablename="link";
$query="select * from inl_custom Where cust_id=$customid";
$row =$linkconn->Execute($query);
if ($row)
{
for ($x=0; $x<count($fields);$x++)
{
$cust=$row->fields["cust".$x];
if ($cust!="")
{
$fieldid =$r[$fields[$x]];
$objCustomDataList->SetFieldValue($fieldid,$rid,$cust);
}
}
$objCustomDataList->SaveData();
}
}
function buildfields() #building and populating an array
{
global $objCustomFieldList, $objSession,$linkconn;
$lc="lc";
$uc="uc";
$cc="cc";
$query = "SELECT * FROM inl_config WHERE name LIKE 'uc%'";
$row =$linkconn->Execute($query);
$names = array();
while($row && !$row->EOF)
{
$data = $row->fields;
$fieldlabel=$data["name"];
if(strlen($data["value"]))
{
$fieldlabel = $data["value"];
}
$f=$objCustomFieldList->AddField(6,$data["name"],$fieldlabel);
$r["'".$data["name"]."'"]=$f->Get("CustomFieldId");
$objSession->SetVariable("custom_".$data["name"],$f->Get("CustomFieldId"));
$names[] = $data["name"];
$row->MoveNext();
}
$objSession->SetVariable("custom_user",implode(",",$names));
unset($names);
$names = array();
$query = "SELECT * FROM inl_config WHERE name LIKE 'cc%'";
$row =$linkconn->Execute($query);
while($row && !$row->EOF)
{
$data = $row->fields;
$fieldlabel=$data["name"];
if(strlen($data["value"]))
{
$fieldlabel = $data["value"];
}
$f=$objCustomFieldList->AddField(1,$data["name"],$fieldlabel);
$r["'".$data["name"]."'"]=$f->Get("CustomFieldId");
$objSession->SetVariable("custom_".$data["name"],$f->Get("CustomFieldId"));
$names[] = $data["name"];
$row->MoveNext();
}
$objSession->SetVariable("custom_category",implode(",",$names));
unset($names);
$names = array();
$query = "SELECT * FROM inl_config WHERE name LIKE 'lc%'";
$row =$linkconn->Execute($query);
while($row && !$row->EOF)
{
$data = $row->fields;
$fieldlabel=$data["name"];
if(strlen($data["value"]))
{
$fieldlabel = $data["value"];
}
$f=$objCustomFieldList->AddField(4,$data["name"],$fieldlabel);
$r["'".$data["name"]."'"]=$f->Get("CustomFieldId");
$objSession->SetVariable("custom_".$data["name"],$f->Get("CustomFieldId"));
$names[] = $data["name"];
$row->MoveNext();
}
$objSession->SetVariable("custom_links",implode(",",$names));
return $r;
}
function getfields() #building and populating an array
{
global $objSession;
$lc="lc";
$uc="uc";
$cc="cc";
$userfields = explode(",",$objSession->GetVariable("custom_user"));
for ($x=0;$x<=count($userfields);$x++)
{
$r[$userfields[$x]]=$objSession->GetVariable("custom_".$userfields[$x]);
}
$catfields = explode(",",$objSession->GetVariable("custom_category"));
for ($x=0;$x<=count($catfields);$x++)
{
$r[$catfields[$x]]=$objSession->GetVariable("custom_".$catfields[$x]);
}
$linkfields = explode(",",$objSession->GetVariable("custom_links"));
for ($x=0;$x<=count($linkfields);$x++)
{
$r[$linkfields[$x]]=$objSession->GetVariable("custom_".$linkfields[$x]);
}
return $r;
}
################################################Relationships Import
function relcatimport()
{
global $linkconn,$objSession, $start;
$limit = 100;
$counter =0;
if ($start == 0)
{
$query="SELECT count(*) from inl_rel_cats";
$row =$linkconn->Execute($query);
if ($row && !$row->EOF)
{
settotal($row->fields[0]);
}
}
$objRelList = new clsRelationshipList();
$query="select * from inl_rel_cats LIMIT $start, $limit";
$row =$linkconn->Execute($query);
while($row && !$row->EOF)
{
$counter++;
$sourceid = newcatrid($row->fields["cat_id"]);
$targetid = newcatrid($row->fields["rel_id"]);
if ($sourceid !="" && $targetid !="")
{
$r = $objRelList->Add($sourceid, 1,$targetid, 1);
$r->Create();
}
$row->moveNext();
}
if ($counter == $limit)
{
setstart($start+$limit, "relcat");
}
else
{
setstart(0,"terminate");
}
}
function newcatrid($oid)
{
global $portalconn, $TablePrefix;
$query2="select * from ".$TablePrefix."import where otname='inl_cats' and oid=$oid";
$row =$portalconn->Execute($query2);
if ($row->fields["nrid"])
{
return $row->fields["nrid"];
}
else
{
return "";
}
}
// END OF RELATIONSHIP IMPORT
?>
\ No newline at end of file
Property changes on: trunk/admin/import/import.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property

Event Timeline