Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 11:41 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: trunk/kernel/parser.php
===================================================================
--- trunk/kernel/parser.php (revision 288)
+++ trunk/kernel/parser.php (revision 289)
@@ -1,3369 +1,3375 @@
<?php
$ItemTypes["category"]=1;
$ItemTables[1] = "Category";
$ParserFiles[] = "kernel/parser.php";
function m_ParseEnv($str = NULL)
{
global $m_var_list, $objConfig, $objCatList, $objLanguages, $objThemes;
if ($str != NULL)
{
$str = substr($str,1);
$pieces = explode("-", $str);
//echo "<PRE>";print_r($pieces);echo "</PRE>";
$m_var_list["cat"] = $pieces[0];
$m_var_list["p"] = $pieces[1];
$objCatList->Page = $m_var_list["p"];
$m_var_list["lang"] = $pieces[2];
$m_var_list["theme"] = $pieces[3];
}
else
{
$m_var_list["cat"]=0;
$m_var_list["p"] = 1;
$m_var_list["lang"] = $objLanguages->GetPrimary();
$m_var_list["theme"]= $objThemes->GetPrimaryTheme();
}
}
function m_BuildEnv()
{
global $m_var_list, $m_var_list_update, $objLanguages;
$str = ":m";
if( is_array($m_var_list_update) )
foreach($m_var_list_update as $m_var => $m_value)
if($m_value == '0') $m_var_list_update[$m_var] = '';
$str .= m_GetVar('cat');
if( isset($m_var_list_update['cat']) ) unset($m_var_list_update['cat']);
$str .= '-'.m_GetVar('p');
$str .= '-'.m_GetVar('lang');
$str .= '-'.m_GetVar('theme');
return $str;
}
function m_GetVar($name)
{
// get variable from template variable's list
global $m_var_list, $m_var_list_update;
return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name];
}
function &LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId)
{
global $objItemTypes;
if(!is_object($Relations))
{
$Relations = new clsRelationshipList();
}
//$Relations->debuglevel = 2;
if ($ResourceId != '') {
$sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority,
IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId,
IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId,
IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType,
IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType
FROM %%s", $ResourceId);
$where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1";
$Relations->LoadRelated($where,"",$sql);
$ids = array();
if($Relations->NumItems()>0)
{
foreach($Relations->Items as $r)
{
if($r->Get("SourceId")==$ResourceId)
{
$ids[$r->Get("TargetType")][] = $r->Get("TargetId");
}
if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1)
{
$ids[$r->Get("SourceType")][] = $ResourceId;
}
}
foreach($ids as $ItemType=>$idlist)
{
$Item =& $objItemTypes->GetItem($ItemType);
$table = GetTablePrefix().$Item->Get("SourceTable");
if($ItemType!=1)
{
$cattable = GetTablePrefix()."CategoryItems";
$sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON ";
$sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 ";
$sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
}
else
{
$sql = "SELECT *,CategoryId FROM $table ";
$sql .="WHERE $table.Status=1 ";
$sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
}
// echo $sql."<br>\n";
$RelatedItems->Query_Item($sql,-1,-1,$ItemType);
}
}
}
}
/*
@description: Inserts the html from a remote source
@attrib: _url:: Remote URL to include
@attrib: _StartPos:: Numeric start point of text to include, or string match
@attrib: _EndPos:: Numeric end point of text to include, or string match
@example: <inp:m_insert_url _Url="http://www.google.com" _StartPos="\<center\>" _EndPos="\</center\>" />
*/
function m_insert_url($attribs=array())
{
global $pathtoroot;
$url = $attribs["_url"];
$StartPos = $attribs["_startpos"];
$EndPos = $attribs["_endpos"];
$socket = new Socket($url,0,NULL);
$txt = $socket->socket_read_all();
$lines = explode("\n",$txt);
$txt = substr($txt,strpos($txt,"<"));
$tmp = strtolower($txt);
$bodypos = strpos($tmp,"<body");
if(strlen($bodypos)>0)
{
$head = substr($txt,0,$bodypos-1);
$body = substr($txt,$bodypos);
if(substr($tmp,-7)=="</html>")
$body = substr($body,0,-7);
}
else
$body = $txt;
if(strlen($body))
{
if(strlen($StartPos))
{
if(!is_numeric($StartPos))
{
$start = strpos($body,$StartPos);
}
else
$start = (int)$StartPos;
}
else
$start = 0;
if(strlen($EndPos))
{
if(!is_numeric($EndPos))
{
$end = strpos($body,$EndPos,$start) + strlen($EndPos);
}
else
$end = (int)$EndPos;
}
else
$end = NULL;
$o = substr($body,$start,$end-$start);
}
return $o;
}
/*
@description: Displays a template depending on the login status of the user
@attrib: _logintemplate:tpl: template to display when the user is NOT logged in
@attrib: _LoggedinTemplate:tpl: template to display when the user is logged in
@example: <inp:m_loginbox _LoginTemplate="right_login" _LoggedInTemplate="right_loggedin" />
*/
function m_loginbox($attribs = array())
{
global $var_list, $objSession, $objUsers, $objTemplate;
$userid = $objSession->Get("PortalUserId");
$groupid = $objSession->Get("GroupId");
if ($userid == 0)
{
if (strlen($attribs["_logintemplate"]))
$t = $objTemplate->ParseTemplate($attribs["_logintemplate"]);
return $t;
}
else
{
$user =& $objUsers->GetItem($userid);
if (strlen($attribs["_loggedintemplate"]))
$t = $user->ParseTemplate($attribs["_loggedintemplate"]);
return $t;
}
}
/*
@description: result of suggest site action
*/
function m_suggest_result()
{
global $suggest_result;
return $suggest_result;
}
/*
@description: result of subscribe to mailing list action
*/
function m_subscribe_result()
{
global $SubscribeResult;
if(strlen($SubscribeResult))
return language($SubscribeResult);
return "";
}
/*
@description: email address of user subscribing to mailing list
*/
function m_subscribe_address()
{
global $SubscribeAddress;
if(strlen($SubscribeAddress))
return $SubscribeAddress;
return "";
}
/*
@description: Error message of subscribe to mailing list action
*/
function m_subscribe_error()
{
global $SubscribeError;
if(strlen($SubscribeError))
return language($SubscribeError);
return "";
}
/*
@description: Displays a prompt for a form field
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _LangText:lang: Language var to use for field label
@attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set)
@attrib: _Template:tpl: template used to display the field label (if not set "<inp:form_prompt />" is used
@attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set
*/
function m_form_prompt($attribs = array())
{
global $FormError, $objTemplate, $objConfig;
$form = strtolower($attribs["_form"]);
$field = strtolower($attribs["_field"]);
if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
{
$o = "";
}
else
{
$t = $attribs["_template"];
if(!strlen($t))
{
$templateText = "<inp:form_prompt />";
}
$e = $attribs["_errortemplate"];
if(!strlen($e))
$e = $t;
if(strlen($attribs["_langtext"]))
{
$txt = language($attribs["_langtext"]);
}
else
$txt = $attribs["_plaintext"];
if (strtolower($field) == "dob")
{
if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")]))
$rawtext = $objTemplate->GetTemplate($e, true);
}
if(isset($FormError[strtolower($form)][strtolower($field)]))
{
$rawtext = $objTemplate->GetTemplate($e);
}
elseif (strlen($t))
$rawtext = $objTemplate->GetTemplate($t);
if(is_object($rawtext))
{
$src = $rawtext->source;
$o = str_replace("<inp:form_prompt />",$txt, $src);
}
else
$o = str_replace("<inp:form_prompt />", $txt, $templateText);
}
return $o;
}
/*
@description: Returns text if system is configured to use auto-generated passwords
@attrib:_LangText:lang:Language tag to return
@attrib:_PlainText::Plain text to return (_LangText takes precedece)
@attrib:_Value:bool:Auto Password setting value to match
*/
function m_autopassword($attribs = array())
{
global $objConfig;
if($attribs["_value"]=="true" || $attribs["_value"]==1)
{
$IsAuto = $objConfig->Get("User_Password_Auto");
}
else
{
$IsAuto = !$objConfig->Get("User_Password_Auto");
}
if($IsAuto)
{
if(strlen($attribs["_langtext"]))
{
$ret = language($attribs["_langtext"]);
}
else
$ret = $attribs["_plaintext"];
if(!$ret)
return "true";
}
return $ret;
}
/*
@description: checks if field specified is equals to value specified
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Field value to compare to
@example: <inp:m_field_equals _field="topic_subject" _Form="edit_topic" _Value="test" />true</inp:m_field_equals>
*/
function m_field_equals($attribs = array())
{
global $FormValues;
//print_pre($attribs);
$form = $attribs["_form"];
$field = $attribs["_field"];
if(isset($_POST[$field]))
{
$value = $_POST[$field];
}
else
$value = $FormValues[$form][$field];
//echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."]<br>";
return $value == $attribs['_value'] ? 1 : '';
}
/*
@description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _ForgetValue:bool: if true, forget value
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@example: <inp:m_form_input type="text" class="input" style="width:600px;" _field="topic_subject" _Form="edit_topic" _Required="1" />
*/
function m_form_input($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
if(isset($_POST[$field]) && $attribs['_forgetvalue'] != 1)
{
$value = $_POST[$field];
}
else {
if ($attribs['_forgetvalue'] != 1) {
$value = $FormValues[$form][$field];
}
}
//echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']."<br>\n";
if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
{
$ret = "";
}
else
{
$ret = "<INPUT ".$html_attribs." name=\"$field\" VALUE=\"$value\" />";
if($attribs["_required"])
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
}
return $ret;
}
/*
@description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:bool: If true, the radio button is CHECKED
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_checkbox _field="owner_notify" _Form="edit_topic" />
*/
function m_form_checkbox($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
if(isset($_POST[$field]))
{
$value = (int)$_POST[$field];
if($value==1)
$checked = " CHECKED";
}
else
{
$value = (int)$FormValues[$form][$field];
if($value==1)
$checked=" CHECKED";
}
//echo $form.".".$field."=".$value."<br>\n";
$ret = "<INPUT TYPE=\"checkbox\" $html_attribs name=\"$field\" VALUE=\"1\" $checked />";
if($attribs["_required"])
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
return $ret;
}
/*
@description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_checkbox _field="owner_notify" _Form="edit_topic" />
*/
function m_form_radio($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
$val = $attribs["_value"];
if(isset($_POST[$field]))
{
$value = (int)$_POST[$field];
if($value==1)
$checked = " CHECKED";
}
else
{
$value = (int)$FormValues[$form][$field];
if($value==$val)
$checked=" CHECKED";
}
//echo $form.".".$field."=".$value."<br>\n";
$ret = "<INPUT TYPE=\"radio\" $html_attribs name=\"$field\" VALUE=\"$val\" $checked />";
if($attribs["_required"])
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
return $ret;
}
/*
@description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition)
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@example: <inp:m_form_value _field="owner_notify" _Form="edit_topic" />
*/
function m_form_value($attribs = array())
{
global $FormValues;
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
if(isset($_POST[$field]))
{
$value = stripslashes($_POST[$field]);
}
else
$value = stripslashes($FormValues[$form][$field]);
//echo "<pre>"; print_r($FormValues); echo "</pre>";
return $value;
}
/*
@description: creates an form OPTION tag for a form SELECT tag.
All extra attributes are passed to the OPTION tag.
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select
field is the same as this attribute, then this option will be set SELECTED.
@attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown
@attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext)
@example: <inp:m_form_option _value="3321" _field="formfield" _form="formname" _langtext="lu..."
*/
function m_form_option($attribs = array())
{
global $FormValues;
$html_attribs = ExtraAttributes($attribs);
$field = $attribs["_field"];
$val = $attribs["_value"];
if(isset($_POST[$field]))
{
$value = $_POST[$field];
}
else
{
$value = $FormValues[$attribs['_form']][$field];
}
$selected = ($val == $value)? "SELECTED" : "";
if(strlen($attribs["_langtext"]))
{
$txt = language($attribs["_langtext"]);
}
else
$txt = $attribs["_plaintext"];
$o = "<OPTION $html_attribs VALUE=\"$val\" $selected>$txt</OPTION>";
return $o;
}
/*
@description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_textarea class="textarea" _field="bb_signature" _Form="bb_profile" ID="textbody" style="width:300px;" ROWS=10 COLS=65 WRAP="VIRTUAL" />
*/
function m_form_textarea($attribs = array())
{
global $FormValues;
$html_attribs = ExtraAttributes($attribs);
$field = $attribs["_field"];
$form = $attribs["_form"];
if(isset($_POST[$field]))
{
$value = stripslashes($_POST[$field]);
}
else
$value = stripslashes($FormValues[$attribs["_form"]][$field]);
$ret = "<TEXTAREA NAME=\"$field\" $html_attribs>$value</TEXTAREA>";
if($attribs["_required"])
$ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
return $ret;
}
/*
@description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _ImageTypes:: Comma-separated list of file extensions allowed
@attrib: _Thumbnail:bool: If true, image is treated as a thumbnail
@attrib: _ImageName:: System name of image being uploaded
@attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all
*/
function m_form_imageupload($attribs = array())
{
$html_attribs = ExtraAttributes($attribs);
$field = $attribs["_field"];
$form = $attribs["_form"];
$TypesAllowed = $attribs["_imagetypes"];
$isthumb = (int)$attribs["_thumbnail"];
$imgname = $attribs["_imagename"];
$maxsize = $attribs["_maxsize"];
$ret = "<INPUT $html_attribs TYPE=file NAME=\"$field\" >";
$ret .= "<INPUT TYPE=HIDDEN name=\"isthumb[$field]\" VALUE=\"$isthumb\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"imagetypes[$field]\" VALUE=\"$TypesAllowed\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"imagename[$field]\" VALUE=\"$imgname\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"maxsize[$field]\" VALUE=\"$maxsize\">";
if($attribs["_required"])
$ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
return $ret;
}
/*
@description: Returns the error text for a form field, or nothing if no error exists for the field
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
*/
function m_form_error($attribs = array())
{
global $FormError;
$form = $attribs["_form"];
$field = $attribs["_field"];
return $FormError[$form][$field];
}
/**
@description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable.
@attrib: _Form:: Form name for the field
*/
function m_form_has_errors($attribs = array())
{
// shows specified template once if form has error(-s)
global $FormError;
$f = $attribs["_form"];
$ret = is_array($FormError[$f]);
if(!$ret) return '';
return isset($attribs["_asif"]) ? true : language('lu_errors_on_form');
}
/**
@description: Lists form errors for all fields in a form
@attrib: _Form:: Form name for the field
@attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "<inp:form_error />" is used)
*/
function m_list_form_errors($attribs = array())
{
global $FormError, $content_set, $objTemplate;
$t = $attribs["_itemtemplate"];
if(!strlen($t))
$templateText = "<inp:form_error />";
$f = $attribs["_form"];
$o = "";
if (strlen($t))
{
$rawtext = $objTemplate->GetTemplate($t, true);
$src = $rawtext->source;
}
else
$src = $templateText;
//echo $f."<br>";
//echo $t."<br>";
// echo "<PRE>"; print_r($FormError); echo "</pre>";
if(is_array($FormError[$f]))
{
foreach($FormError[$f] as $e)
{
$o .= str_replace("<inp:form_error />",$e, $src);
}
}
if(!strlen($o))
$content_set = 0;
return $o;
}
function m_form_load_values($FormName,$IdValue)
{
global $FormValues, $objUsers, $objSession, $objConfig;
switch($FormName)
{
case "m_acctinfo":
$u =& $objUsers->GetItem($IdValue);
$FormValues[$FormName]["username"] = $u->Get("Login");
//$FormValues[$FormName]["password"] = $u->Get("Password");
//$FormValues[$FormName]["passwordverify"] = $u->Get("Password");
$FormValues[$FormName]["password"] = "";
$FormValues[$FormName]["passwordverify"] = "";
$FormValues[$FormName]["firstname"] = $u->Get("FirstName");
$FormValues[$FormName]["lastname"] = $u->Get("LastName");
$FormValues[$FormName]["email"] = $u->Get("Email");
$FormValues[$FormName]["phone"] = $u->Get("Phone");
$FormValues[$FormName]["street"] = $u->Get("Street");
$FormValues[$FormName]["city"] = $u->Get("City");
$FormValues[$FormName]["state"] = $u->Get("State");
$FormValues[$FormName]["zip"] = $u->Get("Zip");
$FormValues[$FormName]["country"] = $u->Get("Country");
// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob"));
$FormValues[$FormName]["dob_day"] = date("d", $u->Get("dob"));
$FormValues[$FormName]["dob_year"] = date("Y", $u->Get("dob"));
$FormValues[$FormName]["dob_month"] = date("m", $u->Get("dob"));
$u->LoadCustomFields();
if(is_array($u->CustomFields->Items))
{
foreach($u->CustomFields->Items as $f)
{
$FormValues[$FormName][$f->Get("FieldName")] = $f->Get("Value");
}
}
break;
case "m_profile":
$u =& $objUsers->GetItem($IdValue);
if(is_object($u))
{
$FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname");
$FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname");
$FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob");
$FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email");
$FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone");
$FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street");
$FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city");
$FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state");
$FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip");
$FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country");
}
break;
case "m_simplesearch":
$FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
break;
case "m_simple_subsearch":
$FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
break;
}
}
/*
@description: Generates the ACTTION property for a FORM tag used by In-Portal
@attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template)
@attrib: _Form:: The form name<br>Possible Values:
<UL>
<LI>login: user login
<LI>logout: user logout
<LI>forgotpw: Form to prompt the user for forgotten password information
<LI>forgotpw_confirm: confirmation form for forgotpw
<LI>suggest: form to suggest the site to a friend
<LI>suggest_confirm: form to confirm suggestion of the site to a friend
<LI>m_subscribe: form to subscribe to the mailing list
<LI>subscribe_confirm: form to confirm subscription to the mailing list
<LI>m_unsubscribe: form to unsubscribe from the mailing list
<LI>unsubscribe_confirm: form to confirm un-subscription from the mailing list
<LI>m_acctinfo: user account information
<LI>m_profile: system-level profile information
<LI>m_register: New User registration form
<LI>m_addcat: Suggest Category form
<LI>m_addcat_confirm: Confirmation for add category
<LI>m_simplesearch: Perform a simple search
<LI>m_simple_subsearch: Search within results
<LI>m_adv_searchtype: Form to select type of advanced search
<LI>m_adv_subsearch: Advanced Search
<LI>error_access: form displayed on the access denied template
<LI>error_template: Form displayed on the template error page
<LI>m_set_theme: Form displayed for theme selection
</UL>
@attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed.
@attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error.
@attrib: _Referer:bool: The destination template will be taken from referer page we can from.
@example: <FORM enctype="multipart/form-data" method="POST" NAME="article_review" ACTION="<inp:m_form_action _Form="register" _confirm="join_confirm" />">
*/
function m_form_action($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList;
$target_template = $attribs["_template"];
if(strlen($target_template))
{
$var_list_update["t"] = $target_template;
}
else
$var_list_update["t"] = $var_list["t"];
$ret = "";
$form = strtolower($attribs["_form"]);
switch($form)
{
case "login":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_login";
if($attribs["_successtemplate"])
{
$ret .= "&dest=".$attribs["_successtemplate"];
}
else
if(strlen($var_list["dest"]))
$ret .= "&dest=".$var_list["dest"];
}
break;
case "logout":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_logout";
break;
case "forgotpw":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
if(strlen($attribs["_errortemplate"]))
{
$err = $attribs["_errortemplate"];
}
else
$err = $var_list["t"];
$ret = GetIndexURL()."?env=".BuildEnv()."&Action=m_forgotpw&error=$err";
}
break;
case "forgotpw_confirm":
$ret = GetIndexURL()."?env=".BuildEnv();
break;
case "suggest":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_suggest_email";
if(strlen($attribs["_confirmtemplate"])>0)
{
$ret .= "&Confirm=".$attribs["_confirmtemplate"];
}
if(strlen($Dest))
{
$ret .= "&DestTemplate=$Dest";
}
else
{
if(strlen($attribs["_confirmtemplate"])>0)
$ret .="&DestTemplate=".$var_list["t"];
}
if(strlen($attribs["_errortemplate"])>0)
{
$ret .= "&Error=".$attribs["_errortemplate"];
}
}
break;
case "suggest_confirm":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
if(strlen($_GET["DestTemplate"]))
{
$var_list_update["t"] = $_GET["DestTemplate"];
}
else
$var_list_update["t"] = "index";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
break;
case "m_subscribe":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_subscribe_confirm";
if(strlen($attribs["_subscribetemplate"]))
{
$ret .="&Subscribe=".$attribs["_subscribetemplate"];
}
if(strlen($attribs["_unsubscribetemplate"])>0)
{
$ret .= "&Unsubscribe=".$attribs["_unsubscribetemplate"];
}
if(strlen($attribs["_errortemplate"])>0)
{
$ret .= "&Error=".$attribs["_errortemplate"];
}
}
break;
case "subscribe_confirm":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_subscribe";
if($attribs["_subscribetemplate"])
$ret .= "&Subscribe=".$attribs["_subscribetemplate"];
break;
case "unsubscribe_confirm":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_unsubscribe";
if($attribs["_subscribetemplate"])
$ret .= "&Subscribe=".$attribs["_subscribetemplate"];
break;
case "m_unsubscribe":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_unsubscribe";
if(strlen($attribs["_confirmtemplate"])>0)
{
$ret .= "&Confirm=".$attribs["_confirmtemplate"];
}
if(strlen($Dest))
{
$ret .= "&DestTemplate=$Dest";
}
else
{
if(strlen($attribs["_confirmtemplate"])>0)
$ret .="&DestTemplate=".$var_list["t"];
}
}
if(strlen($attribs["_confirmtemplate"])>0)
{
$ret .="&ErrorTemplate=".$attribs["_confirmtemplate"];
}
break;
case "m_unsubscribe_confirm":
$ret = GetIndexURL()."?env=" . BuildEnv();
break;
case "m_acctinfo":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_acctinfo&UserId=".$objSession->Get("PortalUserId");
m_form_load_values($form, $objSession->Get("PortalUserId"));
break;
case "m_profile":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_profile&UserId=".$objSession->Get("PortalUserId");
m_form_load_values($form,$objSession->Get("PortalUserId"));
break;
case "m_set_theme":
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_set_theme";
break;
case "m_register":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_register";
switch ($objConfig->Get("User_Allow_New"))
{
case "1":
if(strlen($attribs["_confirmtemplate"]) && $objConfig->Get("User_Password_Auto"))
$_dest = "&dest=".$attribs["_confirmtemplate"];
else
$_dest = "&dest=".$attribs["_logintemplate"];
break;
case "2":
if(strlen($attribs["_notallowedtemplate"]))
$_dest = "&dest=".$attribs["_notallowedtemplate"];
break;
case "3":
if(strlen($attribs["_pendingtemplate"]))
$_dest = "&dest=".$attribs["_pendingtemplate"];
break;
}
if (strlen($_dest))
$ret .= $_dest;
}
break;
case "register_confirm":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv();
}
break;
case "m_addcat":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$action = "m_add_cat";
if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING"))
{
if(strlen($attribs["_confirmpending"]))
{
$ConfirmTemplate = $attribs["_confirmpending"];
}
else
$ConfirmTemplate = $attribs["_confirm"];
$action="m_add_cat_confirm";
}
if ($objSession->HasCatPermission("CATEGORY.ADD"))
{
$ConfirmTemplate = $attribs["_confirm"];
$action="m_add_cat_confirm";
}
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=$action";
if(strlen($ConfirmTemplate))
$ret .= "&Confirm=$ConfirmTemplate";
if (strlen($attribs["_mod_finishtemplate"])) {
$CurrentCat = $objCatList->CurrentCategoryID();
if((int)$CurrentCat>0)
{
$c = $objCatList->GetCategory($CurrentCat);
//will prefix the template with module template root path depending on category
$ids = $c->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 . $attribs["_mod_finishtemplate"];
}
else {
$t = $attribs["_mod_finishtemplate"]; //Just in case
}
}
else {
$t = $attribs["_finishtemplate"];
}
$ret .="&DestTemplate=".$t;
}
break;
case "m_addcat_confirm":
$target_template = $_GET["DestTemplate"];
if(strlen($target_template))
{
$var_list_update["t"] = $target_template;
}
else
$var_list_update["t"] = $var_list["t"];
$ret = GetIndexURL()."?env=".BuildEnv();
break;
case "m_simplesearch":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_simple_search";
if(strlen($attribs["_errortemplate"]))
$ret.= "&Error=".$attribs["_errortemplate"];
m_form_load_values($form, 0);
}
break;
case "m_simple_subsearch":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_simple_subsearch";
m_form_load_values($form,0);
}
break;
case "m_adv_search_type":
if(!$objSession->SessionEnabled())
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_advsearch_type";
m_form_load_values($form,0);
}
break;
case "m_adv_search":
$SearchType = $_GET["type"];
if(!is_numeric($SearchType))
$SearchType = $_POST["itemtype"];
if(!$objSession->SessionEnabled() && !strlen($SearchType))
{
$var_list_update["t"] = "error_session";
$ret = GetIndexURL()."?env=" . BuildEnv();
}
else
{
$ret = GetIndexURL()."?env=" . BuildEnv()."&Action=m_adv_search&type=$SearchType";
m_form_load_values($form,0);
}
break;
case "error_access":
$target_template = $_GET["DestTemplate"];
if(!strlen($target_template))
$target_template="login";
$var_list_update["t"] = $target_template;
$ret = GetIndexURL()."?env=" . BuildEnv();
break;
case "error_template":
$target_template = $_GET["DestTemplate"];
if($attribs["_referer"] == 1)
{
$target_template = "_referer_";
}
elseif (!strlen($target_template))
{
$target_template = "index";
}
$var_list_update["t"] = $target_template;
// $m_var_list_update["cat"]=0;
$ret = GetIndexURL()."?env=".BuildEnv();
break;
}
return $ret;
}
/*
@description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link
*/
function m_logout_link($attribs)
{
$ret = m_template_link($attribs)."&Action=m_logout";
return $ret;
}
/*
@description: returns a URL to the current theme
@attrib: _page:: Additional address to be added to the end of the theme URL
*/
function m_theme_url($attribs=array())
{
global $objConfig,$objSession, $objThemes, $CurrentTheme;
if(!is_object($CurrentTheme))
$CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
$theme_url = "http://". ThisDomain().$objConfig->Get("Site_Path")."themes/".$CurrentTheme->Get("Name")."/";
if($attribs["_page"])
{
if ($attribs["_page"] != 'current')
{
$theme_url .= $attribs["_page"];
}
else
{
$theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
}
}
return $theme_url;
}
/*
@description: returns a URL to the current theme
*/
function m_current_page_url($attribs=array())
{
global $objConfig,$objSession;
$theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
return $theme_url;
}
/*
@description: returns a URL to the current theme
@attrib: _fullpath:bool: Append the title with the full path of the current category
@attrib: _currentcategory:bool: Append the title with the current category
@attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name
*/
function m_page_title($attibs = array())
{
global $objConfig, $objCatList;
$ret = $objConfig->Get("Site_Name");
if($attibs["_fullpath"] || $attribs["_currentcategory"])
{
$CurrentCat = $objCatList->CurrentCategoryID();
if((int)$CurrentCat>0)
{
$c = $objCatList->GetCategory($CurrentCat);
if($attribs["_fullpath"])
{
$path = $c->Get("CachedNavbar");
if(strlen($path))
$ret .= " - ".$path;
}
else
{
if($attribs["_currentcategory"])
{
$f = $attribs["_catfield"];
if(!strlen($f))
$f = "Name";
$ret .= " - ".$c->Get($f);
}
}
}
}
$ret = stripslashes($ret);
return $ret;
}
/*
@description: list all active themes
@attrib: _ItemTemplate:tpl: Template to display each theme in the list
*/
function m_list_themes($attribs=array())
{
global $objThemes;
$t = $attribs["_itemtemplate"];
if(strlen($t))
{
$objThemes->Clear();
$objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC");
foreach($objThemes->Items as $theme)
{
$o .= $theme->ParseTemplate($t);
}
}
return $o;
}
/*
@description: display text based on the user's language
@attrib: _Phrase:lang: label to replace with language-specific text
@example: <inp:m_language _Phrase="lu_hello_world" />
*/
function m_language($attribs)
{
global $objSession, $objLanguages, $ForceLanguage;
$phrase = $attribs["_phrase"];
$LangId = (int)$ForceLanguage;
if(strlen($phrase))
{
$lang = $attribs["_language"];
if(strlen($lang))
{
$l = $objLanguages->GetItemByField("PackName",$lang);
if(is_object($l))
{
$LangId = $l->Get("LanguageId");
}
}
return language($phrase,$LangId);
}
else
return "";
}
/*
@description: Creates a URL used to set the current language for a user
@attrib: _language:: Language to set (this value should be the language Pack Name)
*/
function m_setlang_link($attribs)
{
global $m_var_list_update, $objSession,$objLanguages;
$lang = $attribs["_language"];
if(strlen($lang))
{
$l = $objLanguages->GetItemByField("PackName",$lang);
if(is_object($l))
$LangId = $l->Get("LanguageId");
}
else
$LangId=$objSession->Get("Language");
if($LangId)
{
$m_var_list_update["lang"] = $LangId;
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["lang"]);
}
else
$ret = "";
return $ret;
}
/*
@description: list all active languages
@attrib: _ItemTemplate:tpl: Template to display each language in the list
*/
function m_list_languages($attribs)
{
global $objLanguages, $content_set;
$sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1";
$objLanguages->Clear();
$objLanguages->Query_Item($sql);
if($objLanguages->NumItems()>0)
{
foreach($objLanguages->Items as $l)
$o .= $l->ParseTemplate($attribs["_itemtemplate"]);
}
else
$content_set=0;
return $o;
}
/*
@description: returns the date format for a language
@attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
*/
function m_lang_dateformat($attribs=array())
{
global $objLanguages, $objSession;
$lang = $attribs["_lang"];
if(!strlen($lang))
{
$LangId = $objSession->Get("Language");
$l = $objLanguages->GetItem($LangId);
}
else
{
$l = $objLanguages->GetItemByField("PackName",$lang);
}
$fmt = GetDateFormat($LangId);
$fmt = GetStdFormat($fmt);
return $fmt;
}
/*
@description: returns a language field value
@attrib: _Field:: Language field to return
@attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
*/
function m_lang_field($attribs = array())
{
global $objLanguages, $objSession;
if(!strlen($attribs["_field"]))
return "";
$lang = $attribs["_lang"];
if(!strlen($lang))
{
$LangId = $objSession->Get("Language");
$l = $objLanguages->GetItem($LangId);
}
else
{
$l = $objLanguages->GetItemByField("PackName",$lang);
}
if(is_object($l))
{
//$ret = $l->Get($attribs["_field"]);
$e = new clsHtmlTag();
$e->name=$l->TagPrefix;
$e->attributes=$attribs;
$ret = $l->ParseObject($e);
}
return $ret;
}
/*
@description: Creates a URL used to set the current theme for a user
@attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index"
*/
function m_settheme_link($attribs)
{
global $m_var_list_update, $objSession, $objThemes, $CurrentTheme;
$ThemeName = $attribs["_theme"];
if(strlen($ThemeName))
{
$t = $objThemes->GetItemByField("Name",$ThemeName);
if(is_object($t))
{
$Id = $t->Get("ThemeId");
}
else
$Id = 0;
}
else
{
$t = $CurrentTheme;
$Id = 0;
}
$m_var_list_update["theme"] = $Id;
$ret = GetIndexURL()."?env=".BuildEnv();
unset($m_var_list_update["theme"]);
return $ret;
}
function m_init_cats($attribs = array())
{
// save current & previous category (used in pagination)
global $objSession, $objCatList;
global $var_list;
//echo "SID_INIT: ".$var_list["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')<br>';
$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') );
$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() );
//$last_cat = $objSession->GetVariable('last_category');
//$prev_cat = $objSession->GetVariable('prev_category');
//echo "Last CAT: [$last_cat]<br>";
//echo "Prev CAT: [$prev_cat]<br>";
}
/*
@description: List all subcategories a user is allowed to view
@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: _ItemTemplate:tpl: default template used for category list items
@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
@example: <inp:m_list_cats _NoTable="0" _columns="2" _ItemTemplate="catlist_element" border="0" cellspacing="0" cellpadding="0" width="98%" />
*/
function m_list_cats($attribs = array())
{
global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache;
$CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv());
if(strlen($CachedList))
{
return $CachedList;
}
$cols = $attribs["_columns"];
if($cols<1)
$cols =1;
$CategoryId = $attribs["_catid"];
if(!is_numeric($CategoryId))
$CategoryId = $objCatList->CurrentCategoryID();
$cat_count = (int)$attribs["_maxlistcount"];
/* validation */
if(strlen($attribs["_itemtemplate"])==0)
{
if($attribs["dataexists"])
$content_set = 0;
return "";
}
$GroupList = $objSession->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];
$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))";
$objCatList->Clear();
$OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
$objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy);
if ($objCatList->NumItems() == 0)
{
if($attribs["_dataexists"])
$content_set = 0;
return "";
}
$html_attr = ExtraAttributes($attribs);
$o="";
$notable = $attribs["_notable"];
$count=0;
$row=0;
$var_list_update["t"] = $var_list["t"];
if(!$notable)
{
$per_row = ceil($objCatList->NumItems()/$cols);
$o = "<TABLE $html_attr><TR CLASS=\"m_list_cats\">";
$o .= "<TD valign=\"top\">";
$CatCount = $objCatList->NumItems();
foreach($objCatList->Items as $cat)
{
$parsed=0;
if($count==$per_row)
{
$o .= "</TD><TD valign=\"top\">";
$count=0;
}
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
$count++;
$row++;
}
if($count != $per_row)
$o .= "</TD>";
$o .= "\n</tr></table>\n";
}
else
{
$CatCount = $objCatList->NumItems();
foreach($objCatList->Items as $cat)
{
if($cat->Get("ParentId")==$CategoryId)
{
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o .= $cat->ParseTemplate($attribs["_itemtemplate"]);
$row++;
$i++;
$count++;
if($count>=$cat_count && $cat_count>0)
break;
}
}
}
unset($var_list_update["t"]);
SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o);
return $o;
}
function LoadCatSearchResults($attribs)
{
global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal;
$GroupList = $objSession->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];
$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))";
$CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
$ctable = $objCatList->SourceTable;
$stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable;
$ptable = GetTablePrefix()."PermCache";
$sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) ";
$sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY EdPick DESC,Relevance DESC ";
$objSearchCats->Page = $m_var_list["p"];
if($objSearchCats->Page<1)
$objSearchCats->Page=1;
if(is_numeric($objConfig->Get($objSearchCats->PerPageVar)))
{
$Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar);
$limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar);
}
else
$limit = NULL;
if(strlen($limit))
$sql .= $limit;
// echo "TEST:<BR>$sql<br>\n";
$objSearchCats->Query_Item($sql);
$where = "ItemType=1";
if(is_numeric($CountVal[1]))
{
$objSearchCats->QueryItemCount = $CountVal[1];
}
else
{
$objSearchCats->QueryItemCount = QueryCount($sql);
$CountVal[1]= $objSearchCats->QueryItemCount;
}
}
/*
@description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is
used to switch from a short list to a longer list. The page number is not changed.
If this tag is called before the list tag, this function will load the category list.
Generally, it is good practice to duplicate all attributes set for m_search_list_cats.
Any extra HTML attributes are passed to the anchor tag
@attrib: _Template:tpl: Template to link to
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
*/
function m_search_cat_more($attribs = array())
{
global $objSearchCats, $objConfig, $m_var_list_update;
$html_attribs = ExtraAttributes($attribs);
$DestTemplate = $attribs["_template"];
if($attribs["_shortlist"])
$objSearchList->PerPageVar = "Perpage_Category_Short";
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
}
$max = $objConfig->Get($objSearchList->PerPageVar);
$val = $objSearchCats->QueryItemCount;
if($val > $max)
{
if($attribs["_root"])
$attribs["_category"]=0;
$m_var_list_update["p"]=1;
$url = m_template_link($attribs);
unset($m_var_list_update["p"]);
$o = "<A $html_attribs HREF=\"$url\">";
$text = $attribs["_text"];
if(!strlen($text))
{
$text = $attribs["_plaintext"];
if(!strlen($text))
{
}
$o .= $text."</A>";
}
else
$o .= language($text);
if(strlen($attribs["_image"]))
{
$o .= "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\" />";
}
$o .= "</A>";
}
return $o;
}
/*
@description: Used in conjuction with m_search_list_cats. This function generates the page navigation
for the list. If this tag is called before the list tag, this function will load
the category list. Generally, it is good practice to duplicate all attributes set for
m_search_list_cats.
@attrib: _PagesToList:int: Number of pages to list (default is 10)
@attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages
listed, this text will not be included (resulting in an empty output)
*/
function m_search_cat_pagenav($attribs = array())
{
global $objSearchCats, $objConfig, $objCatList, $objSession;
$DestTemplate = $attribs["_template"];
$PagesToList = $attribs["_pagestolist"];
if(!is_numeric($PagesToList))
$PagesToList = 10;
$CatId = $attribs["_catid"];
if(!is_numeric($CatId))
$CatId = $objCatList->CurrentCategoryID();
$objSearchCats->PerPageVar = "Perpage_Category";
if($attribs["_shortlist"])
$objSearchCats->PerPageVar = "Perpage_Category_Short";
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
}
$o = $objSearchCats->GetPageLinkList($DestTemplate);
if(strlen($o) && strlen($attribs["_label"]))
$o = language($attribs["_label"]).$o;
return $o;
}
/*
@description: List all categories matched in a search
@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
@attrib: _maxlistcount:int: Maximum number of categories to list
@attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category
@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
@attrib: _LastItemTemplate:tpl: Template used for the last category listed
@attrib: _ItemTemplate:tpl: default template used for category list items
@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
@example: <inp:m_search_list_cats _NoTable="1" _ItemTemplate="category_search_results_element" />
*/
function m_search_list_cats($attribs = array())
{
global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set,
$objSearchCats, $objPermissions, $m_var_list;
if(!is_object($objSearchCats))
{
$objSearchCats = new clsCatList();
$objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search"
$objSearchCats->Clear();
}
$objSearchCats->PerPageVar = "Perpage_Category";
if($attribs["_shortlist"])
{
$objSearchCats->Page=1;
$m_var_list["p"] = 1;
$objSearchCats->PerPageVar = "Perpage_Category_Short";
}
$keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
//echo "Cat count: ". $objSearchCats->QueryItemCount;
$ret = 0;
if ($keywords) {
foreach ($objSearchCats->Items as $cat) {
if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($_POST['keywords']))) {
$ret++;
}
}
}
else {
$ret = $objSearchCats->QueryItemCount;
}
if ($ret == 0) //if ($objSearchCats->NumItems() == 0)
{
$content_set = 0;
return language("lu_no_categories");
}
}
$html_attr = ExtraAttributes($attribs);
$cols = $attribs["_columns"];
if($cols<1)
$cols =1;
$cat_count = (int)$attribs["_maxlistcount"];
/* validation */
if(strlen($attribs["_itemtemplate"])==0)
{
$content_set = 0;
return "ERROR -1";
}
$o="";
$notable = $attribs["_notable"];
$count=0;
$row=0;
$var_list_update["t"] = $var_list["t"];
if(!$notable)
{
$per_row = ceil($objCatList->NumItems()/$cols);
$o = "<TABLE $html_attr><TR CLASS=\"m_list_cats\">";
$o .= "<TD valign=\"top\">";
foreach($objSearchCats->Items as $cat)
{
$parsed=0;
if($count==$per_row)
{
$o .= "</TD><TD valign=\"top\">";
$count=0;
}
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
$count++;
}
if($count != $per_row)
$o .= "</TD>";
$o .= "\n</tr></table>\n";
}
else
{
//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
foreach($objSearchCats->Items as $cat)
{
//$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
$keywords_found = strstr( strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords));
if(!$keywords) $keywords_found = true;
if ($keywords_found) {
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
$row++;
$i++;
$count++;
}
}
}
unset($var_list_update["t"]);
return $o;
}
/*
@description: Parse a template based on the current advanced search type
@attrib:_TypeSelect:tpl:Template to parse if no item type has been selected
@attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search
*/
function m_advsearch_include($attribs)
{
global $objTemplate;
$TypeSelectTemplate = $attribs["_typeselect"];
$ItemTemplate = $attribs["_itemselect"];
if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search"))
{
$o = $objTemplate->ParseTemplate($ItemTemplate);
}
else
$o = $objTemplate->ParseTemplate($TypeSelectTemplate);
return $o;
}
/*
@description: Returns the name of the item type currently being advanced searched
@attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name])
*/
function m_advsearch_type($attribs)
{
global $objItemTypes;
if($_GET["Action"]=="m_advsearch_type")
{
$ItemType = $_POST["itemtype"];
}
elseif($_GET["Action"]=="m_adv_search")
$ItemType = $_GET["type"];
$o = "";
if((int)$ItemType>0)
{
$Item = $objItemTypes->GetItem($ItemType);
if(is_object($Item))
{
$name = strtolower($Item->Get("ItemName"));
if($attribs["_plaintext"])
{
$o .= $name;
}
else
$o = language("lu_searchtitle_".strtolower($name));
}
}
return $o;
}
/*
@description: Lists advanced search fields for the selected item type
@attrib: _FirstItemTemplate:tpl: Template used for the first field listed
@attrib: _LastItemTemplate:tpl: Template used for the last field listed
@attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed
@attrib: _ItemTemplate:tpl: default template used for field list items
@attrib: _AltTemplate:tpl: Alternate template used for field list items
*/
function m_advsearch_fields($attribs)
{
global $objItemTypes, $objTemplate, $objSearchConfig;
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSearchConfigList();
if($_GET["Action"]=="m_advsearch_type")
{
$ItemType = $_POST["itemtype"];
}
elseif($_GET["Action"]=="m_adv_search")
$ItemType = $_GET["type"];
$o = "";
if((int)$ItemType>0)
{
$Item = $objItemTypes->GetItem($ItemType);
if(is_object($Item))
{
$name = strtolower($Item->Get("ItemName"));
$table = $Item->Get("SourceTable");
$sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder";
$objSearchConfig->Query_Item($sql);
$row=0;
if(is_array($objSearchConfig->Items))
{
$ItemCount = count($objSearchConfig->Items);
foreach($objSearchConfig->Items as $s)
{
$even = (($row+1) % 2 == 0);
$parsed=0;
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o .= $s->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]);
$parsed=1;
}
if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
{
if($even && strlen($attribs["_altitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_altitemtemplate"]);
}
else
$o .= $s->ParseTemplate($attribs["_itemtemplate"]);
}
$row++;
}
}
}
}
return $o;
}
/*
@description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
@attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link)
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
nothing is returned. (The link is not created.)
@attrib: _Root:bool: If set, the current category is set to the module's root category
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
@attrib: _image_actions:: Image events.
*/
function m_module_link($attribs = array())
{
global $objCatList, $objSession;
$permission = $attribs["_perm"];
$o = "";
$tpath = GetModuleArray("template");
if(strlen($permission))
{
$perms = explode(",",$permission);
$hasperm = FALSE;
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission($perms[$x]))
{
$hasperm = TRUE;
break;
}
}
}
else
$hasperm = TRUE;
if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
{
$hasperm = TRUE;
$attribs["_template"]=$attribs["_deniedtemplate"];
}
if($hasperm)
{
$module = $attribs["_module"];
if(ModuleEnabled($module))
{
$t = $tpath[$attribs["_module"]];
$t .= $attribs["_template"];
$attribs["_template"] = $t;
$html_attr = ExtraAttributes($attribs);
if($attribs["_root"])
{
$func = ModuleTagPrefix($module)."_root_link";
if(function_exists($func))
{
$url = $func($attribs);
}
else
$url = m_template_link($attribs);
}
else
$url = m_template_link($attribs);
$o = "<A $html_attr HREF=\"";
$o .= $url;
$o .= "\"> ";
$text = $attribs["_text"];
if(!strlen($text))
{
$text = $attribs["_plaintext"];
if(!strlen($text))
{
if(strlen($attribs["_image"]))
{
$text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\">";
}
}
$o .= $text."</A>";
}
else
$o .= language($text)."</A>";
}
else
{
$o = "";
}
}
return $o;
}
/*
@description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
nothing is returned. (The link is not created.)
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
*/
function m_permission_link($attribs = array())
{
global $objCatList, $objSession;
$permission = $attribs["_perm"];
$o = "";
if(strlen($permission))
{
$perms = explode(",",$permission);
$hasperm = FALSE;
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission($perms[$x]))
{
$hasperm = TRUE;
break;
}
}
}
else
$hasperm = TRUE;
if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
{
$hasperm = TRUE;
$attribs["_template"]=$attribs["_deniedtemplate"];
}
if($hasperm)
{
$url = m_template_link($attribs);
$o = "<A $html_attr HREF=\"";
$o .= $url;
$o .= "\"> ";
$text = $attribs["_text"];
if(!strlen($text))
{
$text = $attribs["_plaintext"];
if(!strlen($text))
{
if(strlen($attribs["_image"]))
{
$text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\">";
}
}
$o .= $text."</A>";
}
else
$o .= language($text)."</A>";
}
else
{
$o = "";
}
return $o;
}
/*
@description: Create a link to a template.
@attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list")
@attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test")
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in <A HREF="..#top">)
@attrib: _Secure:bool:If set, creates an https URL
@attrib: _Root:bool:If set, gets module root category id
@attrib: _Module:str:Module Name
@attrib: _Unsecure:bool: Is set, creates an insecure full url (http://...)
@example: <a href="<inp:m_template_link _Template="index" _Category=0 />"><inp:m_language _Phrase="lu_home" /></a>
*/
function m_template_link($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList;
$template = $attribs["_template"];
$query = trim($attribs["_query"]);
$query = !ereg("^&", $query)? "&$query" : $query;
if(!strlen($template))
$template = $var_list["t"];
$cat = $attribs["_category"];
$var_list_update["t"] = $template;
if(strlen($cat))
{
if($cat=="NULL")
{
$m_var_list_update["cat"]=0;
}
else
{
$m_var_list_update["cat"] = $cat;
}
}
if($attribs["_secure"])
{
$ret = GetIndexURL(1)."?env=".BuildEnv().$query;
}
elseif($attribs["_unsecure"])
{
$ret = GetIndexURL(2)."?env=".BuildEnv().$query;
}
else
$ret = GetIndexURL()."?env=".BuildEnv().$query;
if(strlen($attribs["_anchor"]))
$ret .= "#".$attribs["_anchor"];
unset($var_list_update["t"]);
if(strlen($cat))
unset($m_var_list_update["cat"]);
return $ret;
}
/*
@description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to if the user has access
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
the "login" template is used.
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@example: <a href="<inp:m_access_template_link _Template="my_account" _DeniedTemplate="login" _Perm="login" />"><inp:m_language _Phrase="lu_myaccount" /></A>
*/
function m_access_template_link($attribs = array(), $Permission="")
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
$cat = $attribs["_category"];
if(strlen($cat))
{
if($cat=="NULL")
$cat = 0;
}
else
$cat = $objCatList->CurrentCategoryID();
if(!strlen($Permission))
{
$Permission = strtoupper($attribs["_perm"]);
}
$o = "";
$hasperm = FALSE;
if(strlen($Permission))
{
$perms = explode(",",$Permission);
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission(trim($perms[$x]),$cat))
{
$hasperm = TRUE;
break;
}
}
if(!$hasperm && $attribs["_system"])
{
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasSystemPermission(trim($perms[$x])))
{
$hasperm = TRUE;
break;
}
}
}
}
$access = $attribs["_template"];
$denied = $attribs["_deniedtemplate"];
if(!strlen($denied))
$denied = "login";
$m_var_list_update["cat"] = $cat;
if($hasperm)
{
$template = $access;
if(!strlen($template))
$template = $var_list["t"];
$var_list_update["t"] = $template;
}
else
{
$template = $denied;
if(!strlen($template))
$template = $var_list["t"];
if($template == "login")
{
$dest = $access;
}
$var_list_update["t"] = $template;
}
$ret = GetIndexURL()."?env=".BuildEnv();
unset($var_list_update["t"]);
if(strlen($dest))
$ret .= "&dest=$dest";
return $ret;
}
/*
@description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded.
@attrib: _Text:lang: Template to link to if the user has access
@attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used.
@attrib: _DenyText:lang: Template to link to if the user has access
@attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set.
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated.
@attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used.
@attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0.
@example: <inp:m_perm_text _Text="!lu_allow_language_tag!" _PlainText="Just a text" _DenyText="!lu_deny_language_tag!" _PlainDenyText="Just a plain text" _Perm="login" _MatchAllPerms="1" _NoPerm="0">Some HTML here!</inp>
*/
function m_perm_text($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
$cat = $attribs["_category"];
if(strlen($cat))
{
if($cat=="NULL")
$cat = 0;
}
else
$cat = $objCatList->CurrentCategoryID();
if(!strlen($Permission))
{
$Permission = strtoupper($attribs["_perm"]);
}
$o = "";
$hasperm = FALSE;
$count = 0;
if(strlen($Permission))
{
$perms = explode(",",$Permission);
for($x=0;$x<count($perms);$x++)
{
$_AllPermsCount[$count] = 0;
if($objSession->HasCatPermission($perms[$x],$cat))
{
$hasperm = TRUE;
$_AllPermsCount[$count] = 1;
// break;
}
$count++;
}
if(!$hasperm && $attribs["_system"])
{
for($x=0; $x<count($perms); $x++)
{
$_AllPermsCount[$count] = 0;
if($objSession->HasSystemPermission($perms[$x]))
{
$hasperm = TRUE;
$_AllPermsCount[$count] = 1;
// break;
}
$count++;
}
}
}
if ((int)$attribs["_matchallperms"])
{
if (count($_AllPermsCount) != array_sum($_AllPermsCount))
$hasperm = FALSE;
}
$text = $attribs["_text"];
$plaintext = $attribs["_plaintext"];
$denytext = $attribs["_denytext"];
$plaindenytext = $attribs["_plaindenytext"];
$nopermissions_status = (int)$attribs["_noperm"]? 1 : 0;
if(!strlen($denied))
$denied = "login";
if (!$nopermissions_status)
{
if ($hasperm)
{
if (strlen($text) || strlen($plaintext))
$ret = strlen($text)? language($text) : $plaintext;
else
$ret = "1";
}
else
$ret = strlen($denytext)? language($denytext) : $plaindenytext;
}
elseif (!$hasperm)
{
$ret = "1";
}
return $ret;
}
/*
@description: Returns the error string associated with a permission
*/
function m_permission_error($attribs = array())
{
global $objPermissions;
$ret = "";
$perm = strtoupper($_GET["error"]);
if(strlen($perm))
{
$ado = GetADODBConnection();
$sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$error_tag = $data["ErrorMessage"];
}
else
$error_tag = "lu_unknown_error";
$ret = language($error_tag);
}
return $ret;
}
/*
@description: Returns the error text encountered when parsing templates
*/
function m_template_error($attribs = array())
{
global $objTemplate;
$ret = "";
if($objTemplate->ErrorNo<0)
{
$ret = $objTemplate->ErrorStr;
}
return $ret;
}
/*
@description: Creates a category navigation bar
@attrib: _Template:tpl: template to use for navigation links
@attrib: _RootTemplate:bool: If set, this template is linked to for the root category
@attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed
@attrib: _Separator:: text to display between levels of the navigation bar
@attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used
@example: <inp:m_navbar _RootTemplate="index" _Template="inbulletin/index" _LinkCurrent="1" _separator=" &gt; " />
*/
function m_navbar($attribs = array())
{
global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules;
$separator = GetElem($attribs, '_separator');
if(!$separator) $separator = "<span class=\"NAV_ARROW\"> > </span>";
$admin = (int)GetElem($attribs, 'admin');
$t = GetElem($attribs, '_template');
$LinkLeafNode = GetElem($attribs, '_linkcurrent');
$catid = (int)GetElem($attribs, '_catid');
if( GetElem($attribs, '_root') )
{
$var = GetElem($attribs, '_root')."_Root";
$Root = (int)$objConfig->Get($var);
}
else
$Root = 0;
$RootTemplate = GetElem($attribs, '_roottemplate') ? GetElem($attribs, '_roottemplate') : '';
$Module = GetElem($attribs, '_module');
$ModuleRootTemplate = '';
if($Module)
{
$ModuleRootCat = $objModules->GetModuleRoot($Module);
if($ModuleRootCat>0)
{
$modkey = "_moduleroottemplate";
$ModuleRootTemplate = GetElem($attribs, $modkey);
}
else
$ModuleRootTemplate="";
}
else
$ModuleRootCat = 0;
if(!$catid)
$catid = $objCatList->CurrentCategoryID();
$ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate);
return $ret;
}
/*
@description: Parse a category field and return the value
@attrib: _Field:: Category field to parse
@attrib: _CatId:int: Category ID to parse (uses current category if not set)
@attrib: _StripHTML:bool: if set, all HTML is removed from the output
*/
function m_category_field($attribs)
{
global $objCatList;
$ret = "";
$catid = (int)$attribs["_catid"];
$field = $attribs["_field"];
if(!$catid)
$catid = $objCatList->CurrentCategoryID();
if(strlen($field))
{
$cat =& $objCatList->GetCategory($catid);
if(is_object($cat))
{
$element = new clsHtmlTag();
$element->name=$cat->TagPrefix;
$element->attributes = $attribs;
$ret = $cat->ParseObject($element);
}
}
if($attribs["_striphtml"])
$ret = strip_tags($ret);
return $ret;
}
/*
@description: returns the date of the last modification to a category
@attrib: _Part:: part of the date to display
@attrib: _Local:bool: If set, only subcategories of the current category is checked
@example: <inp:m_category_modified />
*/
function m_category_modified($attribs)
{
global $objConfig, $objCatList;
$ado = GetADODBConnection();
if($attribs["_local"] && $objCatList->CurrentCategoryID() != 0)
{
$c =& $objCatList->GetItem($objCatList->CurrentCategoryID());
$catlist = $c->GetSubCatIds();
$catwhere = "CategoryId IN (".explode(",",$catlist).")";
$sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category ";
$sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) ";
$sql .= "WHERE $catwhere LIMIT 1";
}
else
$sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1";
$rs = $ado->Execute($sql);
if($rs && ! $rs->EOF)
{
$mod = $rs->fields["ModDate"];
if($mod)
{
$part = strtolower($attribs["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$mod);
}
else
{
$ret = LangDate($mod);
}
}
}
return $ret;
}
/*
@description: creates LINK tags to include all module style sheets
@attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin")
@attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..".
If a module does not have a *css attribute, the default (style.css) is assumed.
@example: <inp:m_module_stylesheets _Modules="In-Portal,In-News,In-Bulletin,In-Link" _In-PortalCss="incs/inportal_main.css" />
*/
function m_module_stylesheets($attribs)
{
global $TemplateRoot;
$IncludeList = explode(",",trim($attribs["_modules"]));
$tpath = GetModuleArray("template");
for($inc=0;$inc<count($IncludeList);$inc++)
{
$css_attr = "_".strtolower($IncludeList[$inc])."css";
if(strlen($attribs[$css_attr]))
{
$mod_css = $tpath[$IncludeList[$inc]].$attribs[$css_attr];
}
else
$mod_css = $tpath[$IncludeList[$inc]]."style.css";
$file = $TemplateRoot.$mod_css;
if(file_exists($file))
$ret .= "<link rel=\"stylesheet\" href=\"$mod_css\" type=\"text/css\" />\n";
}
return $ret;
}
/*
@description: lists items related to a category
@attrib:CatId:int: Category ID of category, or current category if not set
@attrib:_ListItem: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority.
Each item should have its own template passed in as an attribute (_{ItemType}Template)
*/
function m_related_items($attribs)
{
global $objItemTypes, $objCatList, $content_set;
static $Related;
global $CatRelations;
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
$c =& $objCatList->GetCategory($cat);
$data_sent=0;
if(is_object($c))
{
$ResourceId = $c->Get("ResourceId");
$IncludeList = explode(",",trim(strtolower($attribs["_listitems"])));
$o = "";
if(!is_object($CatRelations))
{
$CatRelations = new clsMultiTypeList();
LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId"));
}
if($CatRelations->NumItems()>0)
{
for($inc=0;$inc<count($IncludeList);$inc++)
{
$t_attr = "_".$IncludeList[$inc]."template";
$t = $attribs[$t_attr];
$item_type = $IncludeList[$inc];
if(strlen($item_type))
{
$objType = $objItemTypes->GetTypeByName($item_type);
if(is_object($objType))
{
foreach($CatRelations->Items as $item)
{
if(is_object($item))
{
if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType"))
{
if(strlen($item->BasePermissionName))
{
$perm = $item->BasePermissionName.".VIEW";
$haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId"));
}
else
$hasperm = 1;
if($hasperm)
{
$data_sent =1;
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$l = new $classname;
$l->Data = $item->Data;
$o .= $l->ParseTemplate($t);
}
}
}
}
$item = NULL;
}
}
else
echo $item_type." not found <br>\n";
}
}
if($data_sent)
{
return $o;
}
else
{
$content_set=0;
return "";
}
}
else
{
$content_set = 0;
return "";
}
}
else
{
$content_set = 0;
return "";
}
}
/*
@description: Returns the number of items related to the current category
@attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used
@attrib:_ItemType::Name of item to count. If not set, all related items are counted
*/
function m_related_count($attribs)
{
global $objItemTypes, $objCatList, $content_set;
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
$c =& $objCatList->GetCategory($cat);
$data_sent=0;
//echo "Category: $cat<pre>"; print_r($c); echo " </pre>";
if(is_object($c))
{
$ResourceId = $c->Get("ResourceId");
if(!is_object($CatRelations))
{
$CatRelations = new clsMultiTypeList();
LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId"));
}
$item_type = $attribs["_itemtype"];
if(strlen($item_type))
{
$objType = $objItemTypes->GetTypeByName($item_type);
if(is_object($objType))
{
$TargetType = $objType->Get("ItemType");
}
else
$TargetType="";
}
if($CatRelations->NumItems()>0)
{
for($x=0;$x<$CatRelations->NumItems();$x++)
{
$a = $CatRelations->GetItemByIndex($x);
if($a->type == $TargetType || !strlen($TargetType))
{
$count++;
}
}
}
}
return $count;
}
/*
@description: Returns the MetaKeywords field for a category, or the system MetaKeywords value
if the category doesn't have a value for MetaKeywords
@attrib: _CatId:int: Category to use (The current category is used by default)
*/
function m_meta_keywords($attribs = array())
{
global $objCatList, $objConfig;
$catid = (int)$attribs["_catid"];
if(!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if($catid)
{
$c = $objCatList->GetItem($catid);
$keywords = $c->Get("MetaKeywords");
}
if(!strlen($keywords))
{
$keywords = $objConfig->Get("MetaKeywords");
}
return $keywords;
}
/*
@description: Returns the MetaDescription field for a category, or the system MetaDescription value
if the category doesn't have a value for MetaDescription
@attrib: _CatId:int: Category to use (The current category is used by default)
*/
function m_meta_description($attribs = array())
{
global $objCatList, $objConfig;
$catid = (int)$attribs["_catid"];
if(!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if($catid)
{
$c = $objCatList->GetItem($catid);
$desc = $c->Get("MetaDescription");
}
if(!strlen($desc))
{
$desc = $objConfig->Get("MetaDescription");
}
return $desc;
}
/*
@description: return the number of items in the database
@attrib: _ItemType:: Name of item to count
@attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc)
@attrib: _CategoryCount:int: Limit scope to the current category
@attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set)
@attrib: _Today:bool: Count items added today
@attrib: _GroupOnly:bool: Only count items the current user can view
@attrib: _NoCache:bool: Count without using cache
*/
function m_itemcount($attribs = array())
{
global $objItemTypes, $objCatList, $objSession, $objCountCache;
$Bit_None = 0;
$Bit_Today = 1;
$Bit_Owner = 2;
$Bit_Global = 4;
$Bit_SubCats=8;
if($attribs["_categorycount"])
{
$evar = m_BuildEnv();
}
else
$evar = "";
$cat = $attribs["_catid"];
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
if((int)$cat>0)
$c = $objCatList->GetCategory($cat);
if(is_numeric($attribs["_itemtype"]))
{
$item = $objItemTypes->GetItem($attribs["_itemtype"]);
}
else
$item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
$DoUpdate=0;
//echo "<pre>"; print_r($item); echo "</pre>";
$ExtraId="";
if(is_object($item))
{
if($item->Get("ItemType")==1) /* counting categories */
{
$ret = $objCatList->CountCategories($attribs);
}
else
{
$ListVar =& GetItemCollection($attribs["_itemtype"]);
if(is_object($ListVar))
{
$ret = $ListVar->PerformItemCount($attribs);
}
}
}
else
$ret = 0;
return $ret;
}
/*
@description: Parse a User field and return the value
@attrib: _Field:: User field to parse
@attrib: _UserId:int: Category ID to parse (uses current user if not set)
*/
function m_user_field($attribs)
{
global $objUsers, $objSession;
$o = "";
$userid = $attribs["_userid"];
if(!is_numeric($userid) || $userid=="0")
$userid = $objSession->Get("PortalUserId");
if($userid)
{
$u =& $objUsers->GetItem($userid);
if(is_object($u))
{
$element = new clsHtmlTag();
$element->name = $u->TagPrefix;
$element->attributes = $attribs;
$o = $u->ParseObject($element);
}
}
return $o;
}
/*
@description: Parses a user template
@attrib:_Template:tpl: Template to parse
@attrib:_UserId:int: User ID to parse. If not set, the current user is used
*/
function m_user_detail($attribs = array())
{
global $objTemplate, $objUsers, $objSession;
$tname = $attribs["_template"];
$UserId = (int)$attribs["_userid"];
if(!$UserId)
{
$UserId=$objSession->Get("PortalUserId");
}
if($UserId>0)
{
$u = $objUsers->GetUser($UserId);
$o = $u->ParseTemplate($tname);
}
else
{
$u = new clsPortalUser(NULL);
$o = $u->ParseTemplate($tname);
}
return $o;
}
/*
@description: returns a user field from the current profile being viewed
@example:<inp:m_user_profile_field _Field="login" />
*/
function m_user_profile_field($attribs = array())
{
if((int)$_GET["UserId"])
{
$attribs["_userid"] = $_GET["UserId"];
}
$ret = m_user_field($attribs);
/* if ($ret == '') {
$ret = admin_language("lu_Guest");
}*/
return $ret;
}
/*
@description: Parses a user profile template
@attrib:_Template:tpl: Template to parse
@attrib:_UserId:int: User ID to parse. If not set, the current user is used
*/
function m_user_profile_detail($attribs)
{
if((int)$_GET["UserId"])
{
$attribs["_userid"] = $_GET["UserId"];
}
$ret = m_user_detail($attribs);
return $ret;
}
/*
@description: Lists all user profile fields the user has indicated to be public
@attrib: _ItemTemplate:tpl: Template used to list each field
@example:<inp:m_user_profile _ItemTemplate="view_profile_field" />
*/
function m_user_profile($attribs = array())
{
global $objTemplate, $objUsers;
$tname = $attribs["_itemtemplate"];
$t = $objTemplate->GetTemplate($tname);
if(is_object($t))
{
$html = $t->source;
}
$userid = $_GET["UserId"];
$o = "";
if((int)$userid>0)
{
$u = $objUsers->GetItem($userid);
$vars = $u->GetAllPersistantVars();
foreach($vars as $field=>$value)
{
if(substr($field,0,3)=="pp_")
{
if($value==1)
{
$src = $html;
$src = str_replace("<inp:user_profile_field />","<inp:user _field=\"".substr($field,3)."\" />",$src);
$src = str_replace("lu_profile_field","lu_".$field,$src);
$o .= $u->ParseTemplateText($src);
}
}
}
}
return $o;
}
/*
@description: List users the current user has marked as 'friend'
@attrib: _Status:: Determines which online status to list, either "online" or "offline".
@attrib: _ItemTemplate:tpl: Template used to parse list items
*/
function m_list_friends($attribs = array())
{
global $objUsers, $objSession;
global $online_friends;
$ado = GetADODBConnection();
$status = strtolower($attribs["_status"]);
$logedin_user = $objSession->Get("PortalUserId");
$u =& $objUsers->GetUser($logedin_user);
//echo "<pre>"; print_r($u); echo "</pre>";
if(!isset($online_friends) || $status=="online")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
if(isset($online_friends))
{
foreach($online_friends as $id=>$name)
{
$u =& $objUsers->GetUser($id);
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
}
}
else
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
$sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
//echo $sql;
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$u =& $objUsers->GetItem($rs->fields["PortalUserId"]);
if($status=="online")
{
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
}
$online_friends[]=$rs->fields["PortalUserId"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
}
}
if($status=="offline")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
$sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
if(count($online_friends)>0)
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
$sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
else
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
//echo $sql;
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$u = $objUsers->GetItem($rs->fields["PortalUserId"]);
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
}
$t = $attribs["_itemtemplate"];
return $o;
}
/*
@description: Returns the number of users the current user has marked as 'friend'
@attrib: _Status:: Determines which online status to count, either "online" or "offline".
*/
function m_friend_count($attribs=array())
{
global $objUsers, $objSession;
global $online_friends;
$ado = GetADODBConnection();
$logedin_user = $objSession->Get("PortalUserId");
$u =& $objUsers->GetUser($logedin_user);
$status = strtolower($attribs["_status"]);
if(!isset($online_friends) || $status=="online")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
if(isset($online_friends) && $status="online")
{
return count($online_friends);
}
else
{
$online_friends = array();
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
$sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
//echo $sql."<br>\n";
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
if($status=="online")
return count($online_friends);
}
}
if($status=="offline")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
$sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
if(count($online_friends)>0)
{
$sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
$sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
else
{
$sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
$rs = $ado->Execute($sql);
return $rs->fields["ItemCount"];
}
}
/*
@description: Returns the number of users the current user has marked as 'friend' today
*/
function m_friend_count_today($attribs)
{
global $objSession;
$logedin_user = $objSession->Get("PortalUserId");
$ret =0;
$ado = GetADODBConnection();
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
$ret = $rs->fields["c"];
return $ret;
}
/*
@description: Returns the number of items in a search result
@Example: <span>(<inp:m_search_item_count _ItemType="Topic" />)</span>
*/
function m_search_item_count($attribs)
{
global $objItemTypes, $objCatList, $objSession, $CountVal;
if(!is_array($CountVal))
$CountVal=array();
$item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
if(is_object($item))
{
$val = $CountVal[$item->Get("ItemType")];
if(is_numeric($val))
return $val;
$where = "ItemType=".$item->Get("ItemType");
$table = $objSession->GetSearchTable();
$ret = TableCount($table,$where,0);
$CountVal[$item->Get("ItemType")]=(int)$ret;
}
return $ret;
}
/*
@description: Returns the number of categories in a search result
@Example: <span>(<inp:m_search_cat_count />)</span>
*/
function m_search_cat_count($attribs = array())
{
global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats;
if(!is_object($objSearchCats))
{
$objSearchCats = new clsCatList();
$objSearchCats->SourceTable = $objSession->GetSearchTable();
$objSearchCats->Clear();
}
LoadCatSearchResults($attribs);
//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
$ret = 0;
$keywords = $objSession->GetVariable("Search_Keywords");
if ($keywords) {
foreach ($objSearchCats->Items as $cat) {
if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords))) {
$ret++;
}
}
}
else {
$ret = $objSearchCats->QueryItemCount;
}
//echo $ret;
//$objSearchCats->QueryItemCount = $ret;
return $ret;
}
/*
@description: Returns super global variable by type and name
@attrib: _Name:: Name of variable
@attrib: _Type:: Type super global variable <br>Possible Values:
<UL>
<LI>get: $_GET super variable
<LI>post: $_POST super variable
<LI>cookie: $_COOKIE super variable
<LI>env: $_ENV super variable
<LI>server: $_SERVER super variable
<LI>session: $_SESSION super variable
</UL>
@Example: <inp:m_get_var _name="url" _type="get" />
*/
function m_get_var($attribs = array())
{
global $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_SERVER, $_SESSION;
$type = strtolower($attribs['_type']);
$name = $attribs['_name'];
switch ($type)
{
case "get":
$vars = $_GET;
break;
case "cookie":
$vars = $_COOKIE;
break;
case "files":
$vars = $_FILES;
break;
case "server":
$vars = $_SERVER;
break;
case "session":
$vars = $_SESSION;
break;
case "env":
$vars = $_ENV;
break;
case "post":
$vars = $_POST;
break;
default :
$vars = $_POST;
break;
}
$ret = $vars[$name];
return $ret;
}
/*
@description: Returns number of users currently on-line
@attrib: _LastActive:: Last user/session activity in seconds
@attrib: _OwnCount:bool: Count user's own session
*/
function m_users_online($attribs = array())
{
global $objSession;
$LastActive = (int)($attribs['_lastactive']);
$OwnCount = (int)($attribs['_owncount']);
if ($LastActive && !is_null($LastActive))
$sql_add = " AND LastAccessed>".(time()-$LastActive);
if (!$OwnCount || is_null($OwnCount))
$sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'";
$ado = GetADODBConnection();
$sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add;
$rs = $ado->Execute($sql);
$ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0;
return $ret;
}
+
+function m_debug_mode($attribs = array())
+{
+ $const_name = $attribs['_debugconst'];
+ return defined($const_name) && (constant($const_name) == 1) ? 'yes' : '';
+}
?>
Property changes on: trunk/kernel/parser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.6
\ No newline at end of property
Index: trunk/kernel/include/itemreview.php
===================================================================
--- trunk/kernel/include/itemreview.php (revision 288)
+++ trunk/kernel/include/itemreview.php (revision 289)
@@ -1,615 +1,614 @@
<?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>";
+ if( $GLOBALS['debuglevel'] ) echo $sql."<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
function MoveUp()
{
$this->Increment("Priority");
}
function MoveDown()
{
$this->Decrement("Priority");
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $objUsers;
$extra_attribs = ExtraAttributes($element->attributes);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower($element->attributes["_field"]);
switch($field)
{
case "id":
/*
@field:review.id
@description: review id
*/
$ret = $this->Get("ReviewId");
break;
case "item_id":
/*
@field:review.item_id
@description: ID of the item being reviewed
*/
$ret = inp_unescape($this->Get("ItemId"));
break;
case "text":
/*
@field:review.text
@description:Review text
*/
if($this->Get("TextFormat")==0 || $element->attribues["_textonly"])
{
$ret = inp_escape($this->Get("ReviewText"),0);
}
else
{
$ret = $this->Get("ReviewText");
}
break;
case "ip":
/*
@field:review.ip
@description:IP address of remote host submitting the review
*/
$ret = $this->Get("IPAddress");
break;
case "pending":
/*
@field:review.pending
@description: Returns the review pening status
*/
$ret = $this->Get("Pending");
break;
case "item_type":
/*
@field:review.item_type
@description:Returns the name of the reviewed item type
*/
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
if(is_object($type))
$ret = $type->Get("ItemName");
break;
case "date":
/*
@field:review.date
@description:Returns the date/time the review was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if($element->attributes["_tz"])
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower($element->attributes["_part"]);
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if($d<=0)
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "reviewer":
/*
@field:revier.reviewer
@description:Parse a user tag for the user submitting the review
@attrib:_usertag::User tag to parse, defaults to the users login name
*/
$userfield = $element->attributes["_usertag"];
if(!strlen($userfield))
{
$userfield = "login";
}
if($this->Get("CreatedById")>0)
{
$u =& $objUsers->GetItem($this->Get("CreatedById"));
$e = new clsHtmlTag();
$e->name = $u->TagPrefix;
$e->attributes = $element->attributes;
$e->attributes["_field"] = $userfield;
$ret = $u->ParseObject($e);
}
else
if($userfield=="login")
$ret = "root";
break;
default:
$tag = $this->TagPrefix."_".$field;
$ret = "Undefined: ".$tag->name;
break;
}
}
else
{
$ret = $element->Execute();
}
return $ret;
}
function parsetag($tag)
{
global $objConfig, $objUsers, $objItemTypes;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "review_id":
return $this->Get("ReviewId");
break;
case "review_item_id":
return inp_unescape($this->Get("ItemId"));
break;
case "review_text":
return $this->Get("ReviewText");
break;
case "review_ip_address":
return $this->Get("IPAddress");
break;
case "review_pending":
return $this->Get("Pending");
break;
case "review_item_type":
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
return $res;
break;
case "review_created_date":
return LangDate($this->Get("CreatedOn"));
break;
case "review_created_time":
if($this->Get("CreatedOn")<=0)
return "";
return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn"));
break;
case "review_created_date_month":
return adodb_date("m", $this->Get("CreatedOn"));
break;
case "review_created_date_day":
return adodb_date("d", $this->Get("CreatedOn"));
break;
case "review_created_date_year":
return adodb_date("Y", $this->Get("CreatedOn"));
break;
default:
if (substr($tagname, 0, 16) == "review_createdby")
{
/* parse the created by user */
$u = $objUsers->GetUser($this->Get("CreatedById"));
$usertag = substr($tag,17);
return $u->parsetag($usertag);
}
else
return "Undefined:$tagname";
break;
}
}
function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL)
{
global $objItemTypes, $objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendToUser($ToUserId);
}
}
}
function SendAdminEventMail($EventName,$LangId=NULL)
{
global $objItemTypes,$objMessageList;
$type =& $objItemTypes->GetItem($this->Get("ItemType"));
$res = $type->Get("ItemName");
$EventName = $res.$Suffix;
$Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId);
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
return $Event->SendAdmin($ToUserId);
}
}
}
} /*clsIItemReview*/
class clsItemReviewList extends clsItemCollection
{
var $itemID;
var $Page;
var $PerPageVar;
function clsItemReviewList($id=NULL)
{
$this->clsItemCollection();
$this->classname = "clsItemReview";
$this->SourceTable = GetTablePrefix()."ItemReview";
$this->Page = 1;
$this->PerPageVar = "Perpage_Review";
if(isset($id))
$this->itemID=$id;
$this->AdminSearchFields = array("ReviewText");
}
function ItemCount()
{
return $this->NumItems();
}
function GetReview($ID)
{
return $this->GetItem($ID);
}
function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL)
{
$this->Clear();
$where = "ItemId=".$this->itemID;
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ";
if(strlen($StatusWhere))
$where .= " AND ".$StatusWhere;
$sql .= $where;
if(strlen($OrderBy))
$sql .= " ORDER BY ".$OrderBy;
$Limit = $this->GetLimitSQL();
if(strlen($Limit))
$sql .= " ".$Limit;
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
return $this->Query_item($sql);
}
function GetItemReviewCount($TodayOnly = FALSE)
{
$sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1";
if($TodayOnly)
{
$today = mktime(0,0,0,date("m"),date("d"),date("Y"));
$where .= " AND CreatedOn>=$today";
}
$rs = $this->adodbConnection->execute($sql);
$count=0;
if($rs)
$count = $rs->fields["ItemCount"];
return (int)$count;
}
function ip_exists($ip,$id)
{
return ip_exists($ip,id,$this->SourceTable);
}
function GetLimitSQL()
{
global $objConfig;
if($this->Page<1)
$this->Page=1;
$PerPage = $objConfig->Get($this->PerPageVar);
if(is_numeric($PerPage))
{
$Start = ($this->Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function Query_Review($whereClause=NULL,$orderByClause=NULL)
{
global $Errors;
$this->Clear();
$sql = "SELECT * FROM ".$this->SourceTable." ";
if(isset($whereClause) && strlen(trim($whereClause))>0)
$sql = sprintf("%s WHERE %s",$sql,$whereClause);
if(isset($orderByClause) && strlen(trim($orderByClause))>0)
$sql = sprintf("%s ORDER BY %s",$sql,$orderByClause);
return $this->Query_Item($sql);
}
function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module)
{
global $objSession;
$r = new clsItemReview(NULL,$this->SourceTable);
$ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText);
//$r->debuglevel = 1;
$r->Set(array("CreatedOn","ReviewText","Status", "IPAddress",
"Priority","ItemId","ItemType","CreatedById","TextFormat","Module"),
array($CreatedOn,$ReviewText,$Status, $IPAddress,
$Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Create();
array_push($this->Items,$r);
if($Status==1)
{
$r->SendUserEventMail("REVIEW.ADD",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD");
}
else
{
$r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById);
$r->SendAdminEventMail("REVIEW.ADD.PENDING");
}
return $r;
}
function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)
{
global $objSession;
$r = $this->GetItem($ReviewId);
if($CreatedById==0)
$CreatedById = $r->Get("CreatedById");
$r->Set(array("ReviewId","CreatedOn","ReviewText","Status",
"IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"),
array($ReviewId,$CreatedOn,$ReviewText,$Status,
$IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module));
$r->Update();
//$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId"));
$r->SendAdminEventMail("REVIEW.MODIFY");
return $r;
}
function DeleteReview($ReviewId)
{
$r = $this->GetItem($ReviewId);
$r->Delete();
}
function CopyToItemId($OldId,$NewId)
{
$this->Clear();
$this->Query_Review("ItemId=$OldId","");
if($this->NumItems()>0)
{
foreach($this->Items as $i)
{
$i->Set("ItemId",$NewId);
$i->UnsetIdField();
$i->Create();
}
}
}
function CopyFromEditTable($ResourceId)
{
global $objSession;
$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 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.2
\ No newline at end of property
+1.3
\ No newline at end of property
Index: trunk/kernel/include/portaluser.php
===================================================================
--- trunk/kernel/include/portaluser.php (revision 288)
+++ trunk/kernel/include/portaluser.php (revision 289)
@@ -1,1000 +1,1000 @@
<?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->SetTable('live', GetTablePrefix().'PortalUser');
$this->Page = isset($_GET['lpn']) ? $_GET['lpn'] : 1;
$this->EnablePaging = true;
$this->PerPageVar = "Perpage_User";
$this->AdminSearchFields = array("Login","FirstName","LastName","Email","Street","City", "State","Zip","Country","Phone");
}
function GetPageLinkList($dest_template=NULL,$link_template=NULL,$page = "")
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
if(!strlen($page))
$page = GetIndexURL();
$NumPages = $this->GetNumPages($objConfig->Get("Perpage_Topics"));
if(strlen($dest_template)>0)
{
$var_list_update["t"]=$dest_template;
}
else
{
$var_list_update["t"] = $var_list["t"];
}
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $page."?env=".BuildEnv();
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $page."?env=".BuildEnv();
}
for($p=1;$p<=$NumPages;$p++)
{
$t = template($link_template);
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = $page."?env=".BuildEnv();
$t = str_replace("<%page_link%>", $href, $t);
$t = str_replace("<%page_number%>",$p,$t);
$t = str_replace("<%prev_url%>",$prev_url,$t);
$t = str_replace("<%next_url%>",$next_url,$t);
$o .= $t;
}
else
{
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
}
return $o;
}
function GetUser($ID)
{
$u = $this->GetItem($ID);
return $u;
}
function GetUserName($Id)
{
$rs = $this->adodbConnection->Execute("SELECT Login from ".$this->SourceTable." where PortalUserId=$Id");
return $rs->fields["Login"];
}
function GetUserId($Login)
{
$rs = $this->adodbConnection->Execute("SELECT PortalUserId from ".$this->SourceTable." where Login LIKE '$Login'");
return $rs->fields["PortalUserId"];
}
function GetTotalUsers()
{
return $this->UserCount("1");
}
function GetLatestUser()
{
global $Errors;
$sql = "SELECT max(CreatedOn) as LastDate FROM ".$this->SourceTable;
$result = $this->adodbConnection->Execute($sql);
if ($result === false || !is_object($result))
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$sql = "SELECT PortalUserId FROM ".$this->SourceTable." WHERE CreatedOn >= ".$result->fields["LastDate"];
$result = $this->adodbConnection->Execute($sql);
if (!rs || $rs->EOF)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
return false;
}
$u = $this->GetUser($result->fields["PortalUserId"]);
return $u;
}
function &Add_User($Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="", $Status=2,
$Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0, $ip="", $CheckBanned=FALSE)
{
$u = new clsPortalUser(NULL);
$u->tablename = $this->SourceTable;
//echo "Creating User..<br>\n";
$u->Set(array("Login", "Password", "FirstName", "LastName", "Email", "Status",
"Phone","Street", "City", "State", "Zip", "Country", "CreatedOn","dob"),
array($Login, $Password, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn, $dob));
$BrokenRule = $CheckBanned ? $u->CheckBanned() : false;
if(!$BrokenRule)
{
$u->Create();
return $u;
}
return $BrokenRule;
/*md5($Password)*/
}
function &Edit_User($UserId, $Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="",
$Status=2, $Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0)
{
//echo "<font color=\"red\">Editing User: [$UserId]</font><br>";
$u =& $this->GetItem($UserId);
if(!$CreatedOn)
$CreatedOn = $u->Get("CreatedOn");
// $u->debuglevel=1;
if (is_object($u))
{
$IsBanned = $u->Get('IsBanned');
if($Status == 1) $IsBanned = 0;
$u->Set(array("Login", "FirstName", "LastName", "Email", "Status",
"Phone", "Street", "City", "State", "Zip", "Country", "CreatedOn","dob","IsBanned"),
array($Login, $FirstName, $LastName, $Email, $Status,
$Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn,$dob,$IsBanned));
if(strlen($Password))
$u->Set("Password",$Password);
$u->Update();
}
return $u;
}
function Delete_User($UserId)
{
$u = $this->GetItemByField("ResourceId",$UserId);
if(is_object($u))
{
$u->RemoveFromAllGroups();
$u->Delete();
}
}
function LoadUsers($where = "",$orderBy = "")
{
global $objConfig;
$this->Clear();
if($this->Page<1)
$this->Page=1;
if(is_numeric($objConfig->Get("Perpage_Users")))
{
$Start = ($this->Page-1)*$objConfig->Get("Perpage_Users");
$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Users");
}
else
$limit = NULL;
$where = trim($where);
$orderBy = trim($orderBy);
if(!strlen($where))
$where = "1";
$this->QueryItemCount=TableCount($this->SourceTable,$where,0);
if($this->QueryItemCount>0)
{
if ($orderBy!="")
{
$this->Query_PortalUser($where,$orderBy,$limit);
}
else
{
$this->Query_PortalUser($where,"Login DESC",$limit);
}
}
}
function Query_PortalUser($whereClause,$orderByClause="", $limitClause="")
{
global $m_var_list,$Errors, $objSession;
$resultSet = array();
$utable = $this->SourceTable;
$gtable = GetTablePrefix()."UserGroup";
$sql = "SELECT * FROM $utable LEFT JOIN $gtable ON ($utable.PortalUserId=$gtable.PortalUserId)";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
if(strlen(trim($orderByClause))>0)
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
if(isset($limitClause))
$sql = sprintf('%s %s',$sql,$limitClause);
return $this->Query_Item($sql);
}
function Query_GroupPortalUser($whereClause,$orderByClause)
{
global $m_var_list,$objSession,$Errors;
$resultSet = array();
$table = $this->SourceTable;
$sql = "SELECT * FROM $table LEFT JOIN ".GetTablePrefix()."UserGroup USING (PortalUserId) ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
return $this->query_item($sql);
}
function UserCount($whereClause)
{
$count = TableCount($this->SourceTable,$whereClause,0);
return $count;
}
function CountActive()
{
return $this->UserCount("Status=1");
}
function CountPending()
{
return $this->UserCount("Status=2");
}
function CountDisabled()
{
return $this->UserCount("Status=0");
}
function CopyFromEditTable($idfield)
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
// echo $sql."<BR>";
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->idfield = $idfield;
$c->Dirty();
if($c->Get($idfield)<1)
{
$old_id = $c->Get($idfield);
$c->UnsetIdField();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PortalUserId=".$c->Get("PortalUserId");
$sql .=" WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
else
$c->Update();
unset($c);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
}
function PurgeEditTable()
{
parent::PurgeEditTable();
$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=0";
$this->adodbConnection->Execute($sql);
}
} /*clsUserManager*/
?>
Property changes on: trunk/kernel/include/portaluser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property
Index: trunk/kernel/include/config.php
===================================================================
--- trunk/kernel/include/config.php (revision 288)
+++ trunk/kernel/include/config.php (revision 289)
@@ -1,515 +1,514 @@
<?php
require_once($pathtoroot."kernel/include/adodb/adodb.inc.php");
class clsConfig
{
var $config;
var $m_dirty_session;
var $m_IsDirty;
var $m_DirtyFields;
var $m_VarType;
var $adodbConnection;
function clsConfig()
{
$this->m_IsDirty=false;
$this->adodbConnection = GetADODBConnection();
$this->config = array();
$this->m_IsDefault = array();
$this->VarType = array();
}
function SetDebugLevel($value)
{
}
function Load()
{
if(is_object($this->adodbConnection))
{
LogEntry("Config Load Start\n");
$sql = "select VariableName, VariableValue from ".GetTablePrefix()."ConfigurationValues";
$rs = $this->adodbConnection->Execute($sql);
unset($this->config);
#this->config=array();
$count=0;
while($rs && !$rs->EOF)
{
$this->config[$rs->fields["VariableName"]] = $rs->fields["VariableValue"];
$this->m_VarType[$rs->fields["VariableName"]] = 0;
// $this->Set($rs->fields["VariableName"],$rs->fields["VariableValue"],0);
if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 )
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
$count++;
}
LogEntry("Config Load End - $count Variables\n");
}
unset($this->m_DirtyFields);
$this->m_IsDirty=false;
}
function Get($property)
{
return isset($this->config[$property]) ? $this->config[$property] : '';
}
function Set($property, $value,$type=0,$force=FALSE)
{
if(is_array($this->config) && strlen($property)>0)
{
if(array_key_exists($property,$this->config))
{
$current = $this->config[$property];
$changed = ($current != $value);
}
else
$changed = true;
}
else
$changed = false;
$this->config[$property]=$value;
$this->m_IsDirty = ($this->m_IsDirty or $changed or $force);
if($changed || $force)
{
$this->m_DirtyFields[$property] = $value;
}
$this->m_VarType[$property] = $type;
}
function Save()
{
if($this->m_IsDirty==TRUE)
{
foreach($this->m_DirtyFields as $field=>$value)
{
if($this->m_VarType[$field]==0)
{
$sql = sprintf("UPDATE ".GetTablePrefix()."ConfigurationValues SET VariableValue=%s WHERE VariableName=%s", $this->adodbConnection->qstr($value), $this->adodbConnection->qstr($field));
// echo $sql."<br>\n";
$rs = $this->adodbConnection->execute($sql);
}
}
}
$this->m_IsDirty=FALSE;
unset($this->m_DirtyFields);
}
function TimeFormat()
{
if($this->Get("ampm_time")=="1")
{
$format = "g:i:s A";
}
else
$format = "H:i:s";
return $format;
}
/* vartype should be either 1 or 2, 1 = perstant data, 2 = session data */
function GetDirtySessionValues($VarType)
{
$result = array();
if(is_array($this->m_DirtyFields))
{
foreach($this->m_DirtyFields as $property=>$values)
{
if($this->m_VarType[$property]==$VarType)
$result[$property] = $values;
}
}
return $result;
}
function GetConfigValues($postfix = '')
{
// return only varibles, that match specified criteria
if(!$postfix) return $this->config;
$result = Array();
$postfix_len = $postfix ? strlen($postfix) : 0;
foreach($this->config as $config_var => $var_value)
{
if( substr($config_var, - $postfix_len) == $postfix )
$result[$config_var] = $var_value;
}
return $result;
}
}/* clsConfig */
/*
To create the configuration forms in the admin section, populate the table ConfigurationAdmin and
ConfigurationValues.
The tables are fairly straight-forward. The fields of concern in the ConfigurationValues table is
ModuleOwner and Section. ModuleOwner should either be the module name or In-Portal for kernel related stuff.
(Items which should appear under 'System Configuration').
The Section field determines the NavMenu section the value is associated with. For example,
in-portal:configure_general refers to items listed under System Configuration->General.
In the ConfigurationAdmin table, ensure the VariableName field is the same as the one in ConfigurationValues
(this is the field that creates the natural join.) The prompt field is the text displayed to the left of the form element
in the table. This should contain LANGUAGE ELEMENT IDENTIFIERS that are plugged into the Language function.
The element_type field describes the type of form element is associated with this item. Possible values are:
- text : textbox
- checkbox : a simple checkbox
- select : creates a dropdown box. In this case, the ValueList field should be populated with a comma-separated list
in name=value,name=value format (each element is translated to:
<option VALUE="[value]">[name]</option>
To add dynamic data to this list, enclose an SQL statement with <SQL></SQL> tags for example:
<SQL>SELECT FieldLabel as OptionName, FieldName as OptionValue FROM <prefix>CustomField WHERE <prefix>.CustomFieldType=3></SQL>
note the specific field labels OptionName and OptionValue. They are required by the parser.
use the <prefix> tag to insert the system's table prefix into the sql statement as appropriate
*/
class clsConfigAdminItem
{
var $name;
var $heading;
var $prompt;
var $ElementType;
var $ValueList; /* comma-separated list in name=value pair format*/
var $ValidationRules;
var $default_value;
var $adodbConnection;
var $NextItem=NULL;
var $Section;
function clsConfigAdminItem($config_name=NULL)
{
$this->adodbConnection = GetADODBConnection();
if($config_name)
$this->LoadSetting($config_name);
}
function LoadSetting($config_name)
{
$sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) WHERE ".GetTablePrefix()."ConfigurationAdmin.VariableName='".$config_name."'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$this->name = $rs->fields["VariableName"];
$this->heading = $rs->fields["heading"];
$this->prompt = $rs->fields["prompt"];
$this->ElementType = $rs->fields["element_type"];
$this->ValidationRules=$rs->fields["validation"];
$this->default_value = $rs->fields["VariableValue"];
$this->ValueList=$rs->fields["ValueList"];
$this->Section = $rs->fields["Section"];
}
}
function explode_sql($sql)
{
$s = "";
$rs = $this->adodbConnection->Execute($sql);
while ($rs && !$rs->EOF)
{
if(strlen(trim($rs->fields["OptionName"]))>0 && strlen(trim($rs->fields["OptionValue"]))>0)
{
if(strlen($s))
$s .= ",";
$s .= $rs->fields["OptionName"]."="."+".$rs->fields["OptionValue"];
$rs->MoveNext();
}
}
return $s;
}
function replace_sql($string)
{
$string = str_replace("<PREFIX>",GetTablePrefix(),$string);
$start = strpos($string,"<SQL>");
while($start)
{
$end = strpos($string,"</SQL>");
if(!$end)
{
$end = strlen($string);
}
$len = $end - $start;
$sql = substr($string,$start+5,$len-5);
$sql_val = $this->explode_sql($sql);
$s = substr($string,0,$start) . $sql_val . substr($string,$end+5);
$string = $s;
$start = strpos($string,"<SQL>");
}
return $string;
}
function ItemFormElement()
{
global $objConfig;
static $TabIndex;
if (empty($TabIndex))
$TabIndex = 1;
$o = "";
if($objConfig->Get($this->name)!="")
$this->default_value = stripslashes($objConfig->Get($this->name));
switch($this->ElementType)
{
case "text":
$o .= "<INPUT TYPE=\"TEXT\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
$o .= "VALUE=\"".$this->default_value."\">";
break;
case "checkbox":
$o .= "<INPUT TYPE=\"checkbox\" NAME=\"".$this->name."\" tabindex=\"".($TabIndex++)."\"";
if($this->default_value)
{
$o .= " CHECKED>";
}
else
$o .= ">";
break;
case "password":
/* To exclude config form from populating with Root (md5) password */
if ($this->Section == "in-portal:configure_users")
$this->default_value = "";
$o .= "<INPUT TYPE=\"PASSWORD\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
$o .= "VALUE=\"".$this->default_value."\">";
break;
case "textarea":
$o .= "<TEXTAREA tabindex=\"".($TabIndex++)."\" ".$this->ValueList." name=\"".$this->name."\">".$this->default_value."</TEXTAREA>";
break;
case "label":
if($this->default_value)
{
$o .= $this->default_value;
}
break;
case "radio":
$radioname = $this->name;
$ValList = $this->replace_sql($this->ValueList);
$TabIndex++;
$localTabIndex = $TabIndex;
$TabIndex++;
$val = explode(",",$ValList);
for($i=0;$i<=count($val);$i++)
{
if(strlen($val[$i]))
{
$parts = explode("=",$val[$i]);
$s = $parts[1];
if(strlen($s)==0)
$s="";
$o .= "<input type=\"radio\" tabindex=\"".($localTabIndex)."\" name=\"".$this->name."\" VALUE=\"".$parts[0]."\"";
if($this->default_value==$parts[0])
{
$o .= " CHECKED>";
}
else
$o .= ">";
if(substr($s,0,1)=="+")
{
$o .= $s;
}
else
$o .= prompt_language($s);
}
}
break;
case "select":
$o .= "<SELECT NAME=\"".$this->name."\" tabindex=\"".($TabIndex++)."\">";
$ValList = $this->replace_sql($this->ValueList);
$val = explode(",",$ValList);
for($i=0;$i<=count($val);$i++)
{
if(strlen($val[$i]))
{
$parts = explode("=",$val[$i]);
$s = $parts[1];
if(strlen($s)==0)
$s="";
$selected = "";
if($this->default_value==$parts[0])
$selected = " SELECTED";
if(substr($s,0,1)=="+")
{
$o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".substr($s,1)."</OPTION>";
}
else
{
if(strlen($s))
$o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".admin_language($s)."</OPTION>";
}
}
}
$o .= "</SELECT>";
}
return $o;
}
function GetPrompt()
{
$ret = prompt_language($this->prompt);
return $ret;
}
}
class clsConfigAdmin
{
var $module;
var $section;
var $Items;
function clsConfigAdmin($module="",$section="",$Inst=FALSE)
{
$this->module = $module;
$this->section = $section;
$this->Items= array();
if(strlen($module) && strlen($section))
$this->LoadItems(TRUE,$Inst);
}
function Clear()
{
unset($this->Items);
$this->Items = array();
}
function NumItems()
{
if(is_array($this->Items))
{
return count($this->Items);
}
else
return 0;
}
function LoadItems($CheckNextItems=TRUE, $inst=FALSE)
{
$this->Clear();
if(!$inst)
{
$sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName)
WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' ORDER BY DisplayOrder ASC";
}
else
{
$sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName)
WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' AND Install=1 ORDER BY DisplayOrder ASC";
}
- if((int)$_GLOBALS["debuglevel"])
- echo $sql."<br>\n";
+ if( $GLOBALS['debuglevel'] ) echo $sql."<br>\n";
$adodbConnection = GetADODBConnection();
$rs = $adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
$data = $rs->fields;
if(is_object($i) && $CheckNextItems)
{
$last = $i->prompt;
unset($i);
}
$i = new clsConfigAdminItem(NULL);
$i->name = $data["VariableName"];
$i->default_value = $data["VariableValue"];
$i->heading = $data["heading"];
$i->prompt = $data["prompt"];
$i->ElementType = $data["element_type"];
$i->ValueList = $data["ValueList"];
$i->ValidationRules = $data["validaton"];
$i->Section = $data["Section"];
if(strlen($last)>0)
{
if($i->prompt==$last)
{
$this->Items[count($this->Items)-1]->NextItem=$i;
}
else
{
$i->NextItem=NULL;
array_push($this->Items,$i);
}
}
else
{
$i->NextItem=NULL;
array_push($this->Items,$i);
}
//unset($i);
$rs->MoveNext();
}
}
function SaveItems($POSTVARS, $force=FALSE)
{
global $objConfig;
foreach($this->Items as $i)
{
if($i->ElementType != "label")
{
if($i->ElementType != "checkbox")
{
$objConfig->Set($i->name,$POSTVARS[$i->name]);
}
else
{
if($POSTVARS[$i->name]=="on")
{
$value=1;
}
else
$value = (int)$POSTVARS[$i->name];
$objConfig->Set($i->name,$value,0,$force);
}
}
}
$objConfig->Save();
}
function GetHeadingList()
{
$res = array();
foreach($this->Items as $i)
{
$res[$i->heading]=1;
}
reset($res);
return array_keys($res);
}
function GetHeadingItems($heading)
{
$res = array();
foreach($this->Items as $i)
{
if($i->heading==$heading)
array_push($res,$i);
}
return $res;
}
}
?>
Property changes on: trunk/kernel/include/config.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/image.php
===================================================================
--- trunk/kernel/include/image.php (revision 288)
+++ trunk/kernel/include/image.php (revision 289)
@@ -1,1132 +1,1130 @@
<?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( $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( $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");
$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 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 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.3
\ No newline at end of property
+1.4
\ No newline at end of property
Index: trunk/kernel/include/usersession.php
===================================================================
--- trunk/kernel/include/usersession.php (revision 288)
+++ trunk/kernel/include/usersession.php (revision 289)
@@ -1,1129 +1,1130 @@
<?php
class clsUserSession
{
//Common DB operation class variables
var $m_dirtyFieldsMap = array();
//Identity
var $m_SessionKey;
var $m_CurrentTempKey;
var $m_PrevTempKey;
//Required attributes
var $m_LastAccessed;
var $m_PortalUserId;
var $m_Language;
var $m_Theme;
var $m_GroupId;
var $adodbConnection;
var $m_Errors;
var $m_GroupList;
var $PermCache;
var $SysPermCache;
var $PermCacheGroups;
var $CurrentUser;
var $UseTempKeys;
function clsUserSession($id=NULL, $TempKeys=FALSE)
{
global $objConfig, $objLanguages, $objThemes, $m_var_list;
$this->m_Errors = new clsErrorManager();
$this->adodbConnection = GetADODBConnection();
$this->PermCache = array();
$this->PermCacheGroups ="";
$this->UseTempKeys = $TempKeys;
if( GetVar('help_usage') == 'install' ) return;
if(!$this->UseTempKeys || strlen($id)==0)
{
//echo "with cookies";
if( !isset($_SERVER['HTTP_REFERER']) ) $_SERVER['HTTP_REFERER'] = '';
if(!isset($_GET['destform'])) $_GET['destform'] = null;
if(!isset($_GET['continue_sess'])) $_GET['continue_sess'] = null;
if( strlen($id) && (strstr($_SERVER['HTTP_REFERER'], $_SERVER['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 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 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()
{
+ //trace();
$res = FALSE;
$key = $this->GetSessionKey();
if(strlen($key)>0)
$res = TRUE;
return $res;
}
function GetSessionKey()
{
return $this->Get("SessionKey");
}
function SetThemeName($id=0)
{
global $objThemes;
if($id==0)
$id = $objThemes->GetPrimaryTheme();
$Theme = $objThemes->GetItem($id);
$name = $Theme->Get("Name");
$this->Set("Theme",$name);
//$this->Update();
}
function ValidSession($SessionKey=NULL)
{
global $objConfig;
$a = $this->Get("LastAccessed");
$cutoff = time()-$objConfig->Get("SessionTimeout");
//echo $a." ".$cutoff."<br>";
//$ip = ($_SERVER['REMOTE_ADDR'] == $this->Get("IpAddress"));
//echo $this->Get("IpAddress");
//$ip = TRUE;
if ($a < $cutoff) {
//$this->UpdateAccessTime();
}
return ($a >= $cutoff);
}
function UpdateAccessTime()
{
$now = time();
$this->Set("LastAccessed",$now);
}
function InSpamControl($ResourceId,$DataType=NULL)
{
static $ClearStat;
if(!$ClearStat)
$this->PurgeSpamControl();
$ClearStat=1;
if(strlen($DataType))
$DataType="'".$DataType."'";
$sql = "SELECT count(*) as SpamCount FROM ".GetTablePrefix()."SpamControl WHERE ItemResourceId=$ResourceId AND DataType=$DataType";
if($this->Get("PortalUserId")==0)
{
$sql .= " AND PortalUserId=0 AND IPaddress='".$_SERVER["REMOTE_ADDR"]."'";
}
else
{
$sql .= " AND PortalUserId=".$this->Get("PortalUserId");
}
$rs = $this->adodbConnection->Execute($sql);
$value = (int)$rs->fields["SpamCount"];
if($value>0)
{
return TRUE;
}
else
return FALSE;
}
function AddToSpamControl($ResourceId,$secstoexpire,$DataType=NULL)
{
$expire = adodb_date("U") + $secstoexpire;
if(strlen($DataType))
$DataType = "'".$DataType."'";
$sql = "INSERT INTO ".GetTablePrefix()."SpamControl (ItemResourceId,IPaddress,Expire,PortalUserId,DataType) VALUES (";
$sql .= $ResourceId.",'".$_SERVER["REMOTE_ADDR"]."',$expire,".$this->Get("PortalUserId").",$DataType)";
//echo $sql;
$this->adodbConnection->Execute($sql);
}
function PurgeSpamControl()
{
$sql = "DELETE FROM ".GetTablePrefix()."SpamControl WHERE Expire<".adodb_date("U");
$this->adodbConnection->Execute($sql);
}
}/* clsUserSession */
?>
Property changes on: trunk/kernel/include/usersession.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/kernel/include/language.php
===================================================================
--- trunk/kernel/include/language.php (revision 288)
+++ trunk/kernel/include/language.php (revision 289)
@@ -1,745 +1,744 @@
<?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";
+ if( $GLOBALS['debuglevel'] ) echo $sql."<br>\n";
$this->adodbConnection->Execute($sql);
}
function CopyFromEditTable()
{
global $objSession;
$edit_table = $objSession->GetEditTable($this->SourceTable);
//$idlist = array();
$sql = "SELECT * FROM $edit_table";
-
+ echo "performing mass create/update<br>";
+ flush();
$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();
}
// Phrases deleted from temporary table are marked with LanguageId = 0, when saving we need to actually delete them all
// The idea was taken from Images edit by Kostja
$sql = "DELETE FROM ".$this->SourceTable." WHERE LanguageId = 0";
$this->adodbConnection->Execute($sql);
- if((int)$_GLOBALS["debuglevel"])
- echo $sql."<br>\n";
+ if( $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 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 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.5
\ No newline at end of property
+1.6
\ No newline at end of property
Index: trunk/kernel/frontaction.php
===================================================================
--- trunk/kernel/frontaction.php (revision 288)
+++ trunk/kernel/frontaction.php (revision 289)
@@ -1,857 +1,855 @@
<?php
if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & FRONT_KERNEL_ACTIONS) == FRONT_KERNEL_ACTIONS )
{
if($Action) echo '<span class="debug_text">Front, Kernel Action [<b>'.$Action."</b>]</span><br>\n";
}
if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & FRONT_SHOW_REQUEST) == FRONT_SHOW_REQUEST )
{
// don't show debug output in tree & header of admin & while logging in
$script = basename($_SERVER['PHP_SELF']);
echo '<table width="100%" cellspacing="0" cellpadding="5"><tr><td>';
echo "<div class=\"debug_text\">ScriptName: <b>$script</b> (<b>".dirname($_SERVER['PHP_SELF'])."</b>)</div><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>';
+ echo '</table></div>';
echo '</td></tr></table>';
unset($script);
+// echo "SID: ".$objSession->GetSessionKey().'<br>';
}
switch($Action)
{
case "m_login":
// if($objSession->ValidSession()) $objSession->Logout();
+ //echo $objSession->GetSessionKey()."<br>\n";
if ($objConfig->Get("CookieSessions") == 1 && $_COOKIE["CookiesTest"] != "1") {
$FormError["login"]["login_user"] = language("lu_cookies_error");
}
- else {
+ else
+ {
$MissingCount = SetMissingDataErrors("login");
if($MissingCount==2)
{
$FormError["login"]["login_user"]= language("lu_ferror_loginboth");
unset($FormError["login"]["login_password"]);
}
+
if($MissingCount==0)
{
if($_POST["login_user"]=="root")
{
$FormError["login"]["login_user"]= language("lu_access_denied");
}
else
{
if ($objSession->Login($_POST["login_user"], md5($_POST["login_password"])) == FALSE)
{
$FormError["login"]["login_password"] = language("lu_incorrect_login");
}
else
{
-
- if(!headers_sent() && ($_POST["usercookie"]==1 || $_GET["usercookie"]==1))
+ if( !headers_sent() && GetVar('usercookie') == 1 )
{
$c = $_POST["login_user"]."|";
$pw = $_POST["login_password"];
- if(strlen($pw)<31)
- $pw = md5($pw);
-
+ if(strlen($pw) < 31) $pw = md5($pw);
$c .= $pw;
setcookie("login",$c,time()+2592000);
}
- $dest = $_POST["dest"];
- if(!strlen($dest))
- $dest = $_GET["dest"];
- if(!strlen($dest))
- $dest = $_POST["DestTemplate"];
- if(!strlen($dest))
- $dest = $_GET["DestTemplate"];
- if(strlen($dest))
- {
- $var_list["t"] = $dest;
- //header("Location: ../../index.php?env=" . BuildEnv());
- }
+
- // echo "DEST: ".$t; die();
- }
- }
- }
- }
- break;
+ // set new destination template if passed
+ $dest = GetVar('dest', true);
+ if(!$dest) $dest = GetVar('DestTemplate', true);
+ if($dest) $var_list['t'] = $dest;
+ echo "DEST: $dest<br>";
+ }
+ }
+ }
+ }
+ break;
+
case "m_forgotpw":
$MissingCount = SetMissingDataErrors("forgotpw");
if($MissingCount==0)
{
$username = $_POST["username"];
$email = $_POST["email"];
$found = FALSE;
if(strlen($username))
{
$u = $objUsers->GetItemByField("Login",$username);
if(is_object($u))
$found = ($u->Get("Login")==$username && $u->Get("Status")==1) && strlen($u->Get("Password"));
}
else if(strlen($email))
{
$u = $objUsers->GetItemByField("Email",$email);
if(is_object($u))
$found = ($u->Get("Email")==$email && $u->Get("Status")==1) && strlen($u->Get("Password"));
}
if($found)
{
$newpw = makepassword();
$u->Set("Password",$newpw);
$u->Update();
$u->SendUserEventMail("USER.PSWD",$u->Get("PortalUserId"));
$u->SendAdminEventMail("USER.PSWD");
$u->Set("Password",md5($newpw));
$u->Update();
$u->Clean();
}
else
{
if(!strlen($username) && !strlen($email))
{
$FormError["forgotpw"]["username"] = language("lu_ferror_forgotpw_nodata");
$MissingCount++;
}
else
{
if(strlen($username))
$FormError["forgotpw"]["username"] = language("lu_ferror_unknown_username");
if(strlen($email))
$FormError["forgotpw"]["email"] = language("lu_ferror_unknown_email");
$MissingCount++;
}
if(strlen($_GET["error"]))
$var_list["t"] = $_GET["error"];
}
}
else
if(strlen($_GET["error"]))
$var_list["t"] = $_GET["error"];
break;
case "m_subscribe_confirm":
$t = "";
$SubscribeAddress = $_POST["subscribe_email"];
if(!ValidEmail($SubscribeAddress)&& strlen($SubscribeAddress))
{
$t = $_GET["Error"];
$SubscribeError = "lu_invalid_emailaddress";
}
else
{
if((int)$objConfig->Get("User_SubscriberGroup")>0)
{
$g = $objGroups->GetItem($objConfig->Get("User_SubscriberGroup"));
if(is_object($g))
{
$email = $_POST["subscribe_email"];
if(strlen($email)>0)
{
$u = $objUsers->GetItemByField("Email",$email);
if(is_object($u))
{
if($u->CheckBanned())
{
$t = $_GET["Error"];
$SubscribeError ="lu_subscribe_banned";
}
else
{
if($u->IsInGroup($g->Get("GroupId")))
{
$t = $_GET["Unsubscribe"];
}
else
$t = $_GET["Subscribe"];
}
}
else
$t = $_GET["Subscribe"];
}
else
{
$t = $_GET["Error"];
$SubscribeError ="lu_subscribe_no_address";
}
}
else
{
$t = $_GET["Error"];
$SubscribeError ="lu_subscribe_unknown_error";
}
}
}
if(strlen($t))
{
$var_list["t"] = $t;
$var_list_update["t"] = $t;
}
break;
case "m_subscribe":
//phpinfo(INFO_VARIABLES);
if($_POST["buttons"][0]==language("lu_button_yes"))
{
$SubscribeAddress = $_POST["subscribe_email"];
if(strlen($SubscribeAddress)>0)
{
if(ValidEmail($SubscribeAddress))
{
$GroupId = (int)$objConfig->Get("User_SubscriberGroup");
if ($GroupId)
{
$g = $objGroups->GetItem($GroupId);
$u = $objUsers->GetItemByField("Email",$SubscribeAddress);
if(is_object($u))
{
if(strtolower($u->Get("Email"))==strtolower($SubscribeAddress))
{
$bExists = TRUE;
}
else
$bExists = FALSE;
}
if($bExists)
{
$g->AddUser($u->Get("PortalUserId"));
}
else
{
$u = new clsPortalUser(NULL);
$u->Set("Email",$SubscribeAddress);
$u->Set("ip",$_SERVER['REMOTE_ADDR']);
$u->Set("CreatedOn",date("U"));
$u->Set("Status",1);
if(!$u->CheckBanned())
{
$u->Create();
$g->AddUser($u->Get("PortalUserId"),1);
}
else
$SubscribeResult = "lu_subscribe_banned";
}
$SubscribeResult = "lu_subscribe_success";
$u->SendUserEventMail("USER.SUBSCRIBE",$u->Get("PortalUserId"));
$u->SendAdminEventMail("USER.SUBSCRIBE");
if(strlen($_GET["Subscribe"])>0)
$var_list["t"] = $_GET["Subscribe"];
}
}
else
{
$SubscribeResult = "lu_invalid_emailaddress";
}
}
else
$SubscribeResult = "lu_subscribe_missing_address";
}
if(!strlen($SubscribeResult))
$SubscribeResult = "lu_subscribe_success";
break;
case "m_unsubscribe":
if($_POST["buttons"][0]==language("lu_button_yes"))
{
$MissingCount = SetMissingDataErrors("m_unsubscribe");
if($MissingCount==0)
{
$email = $_POST["subscribe_email"];
$u = $objUsers->GetItemByField("Email",$email);
if(is_object($u))
{
if(strtolower($u->Get("Email"))==strtolower($email))
{
$GroupId = (int)$objConfig->Get("User_SubscriberGroup");
if($u->PrimaryGroup()==$GroupId)
{
$u_gorup_list = $u->GetGroupList();
if (count($u_gorup_list) > 1) {
$u->RemoveFromGroup($GroupId);
}
else {
$u->RemoveFromAllGroups();
$u->Delete();
}
}
else
{
$u->RemoveFromGroup($GroupId);
}
}
}
if(strlen($_GET["Subscribe"])>0)
$var_list["t"] = $_GET["Subscribe"];
}
}
break;
case "m_logout":
// $objSession->Logout();
//unset($objSession);
//$objSession = new clsUserSession();
// $var_list_update["t"] = "index";
// setcookie("login","",time()-3600);
break;
case "m_register":
$MissingCount = SetMissingDataErrors("m_register");
if(!$objConfig->Get("User_Password_Auto"))
{
if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"]))
{
$MissingCount++;
$FormError["m_register"]["passwordverify"] = language("lu_ferror_pswd_mismatch");
}
}
if(strlen($_POST["password"])>30)
{
// echo "VAR: ".$_POST["password"]; die();
$MissingCount++;
$FormError["m_register"]["password"] = language("lu_ferror_pswd_toolong");
}
if (strlen($_POST['password']) < $objConfig->Get("Min_Password"))
{
$MissingCount++;
$FormError["m_register"]["password"] = language("lu_ferror_pswd_tooshort");
}
$u = $objUsers->GetItemByField("Login",$_POST["username"]);
if(is_object($u))
{
if($u->Get("Login")==$_POST["username"])
{
$MissingCount++;
$FormError["m_register"]["username"] = language("lu_user_exists");
}
}
if (strlen($_POST['username']) < $objConfig->Get("Min_UserName"))
{
$MissingCount++;
$FormError["m_register"]["username"] = language("lu_ferror_username_tooshort");
}
if(!$MissingCount)
{
$CreatedOn = adodb_date("U");
$GroupId = $objConfig->Get("User_NewGroup");
$Status=0;
/* determine the status of new users */
switch ($objConfig->Get("User_Allow_New"))
{
case "1":
$Status=1;
break;
case "3":
$Status=2;
break;
}
/* set Destination template */
$var_list["t"] = strlen($_GET["dest"])? $_GET["dest"] : "index";
if($Status>0)
{
if($objConfig->Get("User_Password_Auto"))
{
$password = makepassword();
}
else
$password = $_POST["password"];
$_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"];
$dob = DateTimestamp($_POST["dob"],GetDateFormat());
$ip = $_SERVER['REMOTE_ADDR'];
$u = &$objUsers->Add_User($_POST["username"], md5($password), $_POST["email"], $CreatedOn, $_POST["firstname"], $_POST["lastname"], $Status, $_POST["phone"], $_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"], $_POST["country"], $dob, $ip, TRUE);
if(!is_object($u))
{
$RuleId=$u;
$r = $objBanList->GetItem($RuleId);
$err = $r->Get("ErrorTag");
if(strlen($err))
{
$FormError["m_register"][$r->Get("ItemField")] = language($err);
$MissingCount++;
}
}
else
{
$u->Set("Password",$password);
$u->Clean();
if($GroupId>0)
{
$g = $objGroups->GetItem($GroupId);
$g->AddUser($u->Get("PortalUserId"),1);
}
$custom = $_POST["custom"];
if(is_array($custom))
{
for($x=0;$x<count($custom);$x++)
{
$u->SetCustomField($custom[$x],$_POST[$custom[$x]]);
}
$u->SaveCustomFields();
}
if($Status==1)
{
if($objConfig->Get("User_Password_Auto"))
{
$u->SendUserEventMail("USER.VALIDATE",$u->Get("PortalUserId"));
$u->SendAdminEventMail("USER.VALIDATE");
}
else
{
$doLoginNow = true;
$u->SendUserEventMail("USER.ADD",$u->Get("PortalUserId"));
$u->SendAdminEventMail("USER.ADD");
}
}
else
{
$u->SendUserEventMail("USER.ADD.PENDING",$u->Get("PortalUserId"));
$u->SendAdminEventMail("USER.ADD.PENDING");
}
if ($doLoginNow)
$objSession->Login($_POST["username"], md5($password));
}
}
}
break;
case "m_add_friend":
$id = $_GET["UserId"];
$userid = $objSession->Get("PortalUserId");
if($id!=$userid)
{
$u =& $objUsers->GetItem($id);
$u->AddFavorite($userid);
}
break;
case "m_del_friend":
$id = $_GET["UserId"];
$userid = $objSession->Get("PortalUserId");
$u =& $objUsers->GetItem($id);
$u->DeleteFavorite();
break;
case "m_acctinfo":
// phpinfo(INFO_VARIABLES);
$MissingCount = SetMissingDataErrors("m_acctinfo");
$UserId = $_GET["UserId"];
if($UserId != $objSession->Get("PortalUserId"))
{
$MissingCount++;
$FormError["m_acctinfo"]["UserId"] = language("lu_ferror_m_profile_userid");
}
if(strlen($_POST["password"])>0)
{
if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"]))
{
$MissingCount++;
$FormError["m_acctinfo"]["passwordverify"] = language("lu_ferror_pswd_mismatch");
}
if(strlen($_POST["password"])>30)
{
// echo "VAR: ".$_POST["password"]; die();
$MissingCount++;
$FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_toolong");
}
if (strlen($_POST['password']) < $objConfig->Get("Min_Password"))
{
$MissingCount++;
$FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_tooshort");
}
}
if(!$MissingCount)
{
/* save profile */
$u =& $objUsers->GetItem($UserId);
$status = $u->Get("Status");
$_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"];
$dob = DateTimestamp($_POST["dob"], GetDateFormat());
if(strlen($_POST["password"])>0)
{
$password = md5($_POST["password"]);
}
else
$password = "";
$objUsers->Edit_User($UserId, $_POST["username"], $password, $_POST["email"], 0,
$_POST["firstname"], $_POST["lastname"], $status, $_POST["phone"],
$_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"],
$_POST["country"], $dob);
}
break;
case "m_profile":
$userid = $objSession->Get("PortalUserId");
if($userid>0)
{
$u = $objUsers->GetItem($userid);
foreach($_POST as $field=>$value)
{
if(substr($field,0,3)=="pp_")
{
$objSession->SetPersistantVariable($field,$value);
}
}
}
break;
case "m_set_lang":
$lang = $_GET["lang"];
$LangId = 0;
if(strlen($lang))
{
$l = $objLanguages->GetItemByField("PackName",$lang);
if(is_object($l))
{
$LangId = $l->Get("LanguageId");
}
}
if($LangId)
{
if($objSession->Get("PortalUserId")>0)
{
$objSession->SetPersistantVariable("Language",$LangId);
}
$objSession->Set("Language",$LangId);
$objSession->Update();
$m_var_list_update["lang"] = $LangId;
$m_var_list["lang"] = $LangId;
}
break;
case "m_set_theme":
$id = $_POST["ThemeId"];
if(!is_numeric($id))
$id = $_GET["ThemeId"];
if($id)
{
$objSession->SetThemeName($id);
$m_var_list["t"] = "index";
$m_var_list_update["theme"] = $id;
$m_var_list["theme"] = $id;
unset($CurrentTheme);
}
break;
case "m_sort_cats":
$objSession->SetVariable("Category_Sortfield",$_POST["cat_field_sort"]);
$objSession->SetVariable("Category_Sortorder",$_POST["cat_sort_order"]);
break;
case "m_add_cat_confirm":
// phpinfo(INFO_VARIABLES);
$perm = 0;
$CategoryId=$objCatList->CurrentCategoryID();
if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING"))
$perm = 2;
if ($objSession->HasCatPermission("CATEGORY.ADD"))
$perm = 1;
if ($perm == 0)
{
$MissingCount++;
$FormError["m_addcat"]["name"] = language("lu_ferror_no_access");
}
else
{
$MissingCount = SetMissingDataErrors("m_addcat");
if(is_array($_FILES))
{
foreach($_FILES as $field => $file)
{
$allowed = TRUE;
if(strlen($_POST["imagetypes"][$field]))
{
$types = explode(",",strtolower($_POST["imagetypes"][$field]));
if(is_array($types))
{
if(count($types)>0)
{
$path_parts = pathinfo($file["name"]);
$ext = $path_parts["extension"];
$allowed = in_array($ext,$types);
if(!$allowed)
{
$MissingCount++;
$FormError["m_addcat"][$field] = language("lu_ferror_wrongtype");
}
}
}
}
$maxsize = (int)$_POST["maxsize"][$field];
if($maxsize>0 && $allowed && $file["size"]>$maxsize)
{
$allowed = FALSE;
$MissingCount++;
$FormError["m_addcat"][$field] = language("lu_ferror_toolarge");
}
}
}
if($MissingCount==0)
{
$CreatedOn = date("U");
$name = $_POST["name"];
$desc = $_POST["description"];
$metadesc = $_POST["meta_description"];
$keywords = $_POST["meta_keywords"];
$parent = $objCatList->CurrentCategoryID();
$cat =& $objCatList->Add($parent, $name, inp_escape($desc,0), $CreatedOn,
0, $perm, 2, 2, 2, 0, $keywords,$metadesc);
$cat->UpdateCachedPath();
$cat->Update();
$cat->UpdateACL();
$objCatList->UpdateMissingCacheData();
if(strlen($_GET["Confirm"]))
{
$var_list["t"] = $_GET["Confirm"];
}
else
$var_list["t"] = $_GET["DestTemplate"];
}
}
break;
case "m_front_review_add":
if($objSession->InSpamControl($_POST["ItemId"]))
{
$StatusMessage["review"] = language("la_Review_AlreadyReviewed");
}
else
{
$objReviews = new clsItemReviewList();
$Status = $objConfig->Get("Review_DefaultStatus");
$CreatedOn = adodb_date("U");
$html = (int)$objConfig->Get("Review_Html");
$ReviewText = inp_escape($_POST["review_text"],$html);
$r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress,
0, $_POST["ItemId"], $_POST["ItemType"], $objSession->Get("PortalUserId"));
foreach($ItemTypes as $type=>$id)
{
if($id==$_POST["ItemType"])
{
$ValName = $type."_ReviewDelay_Value";
$IntName = $type."_ReviewDelay_Interval";
break;
}
}
if(strlen($ValName) && strlen($IntName))
{
$exp_secs = $objConfig->Get($ValName) * $objConfig->Get($IntName);
$objSession->AddToSpamControl($_POST["ItemId"],$exp_secs);
if(is_object($r))
{
if($Status)
{
$StatusMessage["review"] = language("la_Review_Added");
}
else
$StatusMessage["review"] = language("la_Review_Pending");
}
else
$StatusMessage["review"] = language("la_Review_Error");
}
else
$StatusMessage["error"] = language("la_ConfigError_Review");
}
break;
case "m_suggest_email":
$cutoff = time()+(int)$objConfig->Get("Suggest_MinInterval");
$email = $_POST["suggest_email"];
if (strlen($email))
{
if(ValidEmail($email))
{
$sql = "SELECT * FROM ".GetTablePrefix()."SuggestMail WHERE email='".inp_escape($email,0)."' and sent<".$cutoff;
$adodbConnection = GetADODBConnection();
$rs = $adodbConnection->Execute($sql);
$rs = false;
if($rs && !$rs->EOF)
{
if(strlen($_GET["Error"])>0)
$var_list["t"] = $_GET["Error"];
$suggest_result = "$email ".language("lu_already_suggested ")." ".LangDate($rs->fields["sent"]);
}
else
{
$Event =& $objMessageList->GetEmailEventObject("USER.SUGGEST");
if(is_object($Event))
{
if($Event->Get("Enabled")=="1")
{
$Event->Item = $this;
$Event->SendToAddress($email);
$sql = "INSERT INTO ".GetTablePrefix()."SuggestMail (email,sent) VALUES ('".inp_escape($email,0)."','".time()."')";
$rs = $adodbConnection->Execute($sql);
$suggest_result=language("lu_suggest_success")." ".$email;
}
}
$e =& $objMessageList->GetEmailEventObject("USER.SUGGEST",1);
if($e->Get("Enabled")==1)
$e->SendAdmin();
if(strlen($_GET["Confirm"])>0)
$var_list["t"] = $_GET["Confirm"];
}
}
else
{
if(strlen($_GET["Error"])>0)
$var_list["t"] = $_GET["Error"];
$suggest_result=language("lu_invalid_emailaddress");
}
}
else
{
if(strlen($_GET["Error"])>0)
$var_list["t"] = $_GET["Error"];
$suggest_result=language("lu_suggest_no_address");
}
break;
case "m_simple_search":
$keywords = $_POST["keywords"];
$type = $objItemTypes->GetTypeByName("Category");
$objSearch = new clsSearchResults("Category","clsCategory");
if(strlen($keywords))
{
$objSearchList = new clsSearchLogList();
$objSearchList->UpdateKeyword($keywords,0);
$objSearch->SetKeywords($keywords);
$objSearch->AddSimpleFields();
if(is_numeric($objConfig->Get("SearchRel_Pop_category")))
$objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100);
if(is_numeric($objConfig->Get("SearchRel_Keyword_category")))
$objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100);
if(is_numeric($objConfig->Get("SearchRel_Rating_article")))
$objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100);
//echo "Searching On $keywords<br>\n";
$objSearch->PerformSearch(1,$SortOrder,TRUE);
$SearchPerformed = TRUE;
//$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId");
//echo "Finished Setting Category Relevence<br>\n";
}
else
{
if(strlen($_GET["Error"])>0)
$var_list["t"] = $_GET["Error"];
$MissingCount = SetMissingDataErrors("m_simplesearch");
$MissingCount++;
$FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword");
}
break;
case "m_adv_search":
if( !is_object($objSearchConfig) ) $objSearchConfig = new clsSearchConfigList();
switch($_GET["type"])
{
case 1: /* category */
//echo "Searching for categories<br>";
$objAdvSearch = new clsAdvancedSearchResults("Category","clsCategory");
foreach($objSearchConfig->Items as $field)
{
$fld = $field->Get("FieldName");
$Verb = $_POST["verb"][$field->Get("FieldName")];
if(!strlen($Verb) && $field->Get("FieldType")=="boolean")
{
if($_POST["value"][$field->Get("FieldName")]!=-1)
{
$Value = $_POST["value"][$field->Get("FieldName")];
$Verb = "is";
}
}
else
{
$Value = $_POST["value"][$field->Get("FieldName")];
}
switch( $_POST["andor"][$field->Get("FieldName")])
{
case 1:
$Conjuction = "AND";
break;
case 2:
$Conjuction = "OR";
break;
default:
$Conjuction = "";
break;
}
if(strlen($Verb)>0 && $Verb!="any")
{
//echo "Adding CAT SearchField: [".$field->Get("TableName")."]; [".$field->Get("FieldName")."]; [$Verb]; [$Value]; [$Conjuction]<br>";
$objAdvSearch->AddAdvancedField($field->Get("TableName"),$field->Get("FieldName"),$Verb,$Value,$Conjuction);
}
}
$objAdvSearch->PerformSearch(1,NULL,TRUE);
break;
}
break;
case "m_id":
echo $Action.":".$DownloadId;
die();
break;
case "m_simple_subsearch":
$keywords = $_POST["keywords"];
$type = $objItemTypes->GetTypeByName("Category");
$objSearch = new clsSearchResults("Category","clsCategory");
if(strlen($keywords))
{
$objSearchList = new clsSearchLogList();
$objSearchList->UpdateKeyword($keywords,0);
$objSearch->SetKeywords($keywords);
$objSearch->AddSimpleFields();
if(is_numeric($objConfig->Get("SearchRel_Pop_category")))
$objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100);
if(is_numeric($objConfig->Get("SearchRel_Keyword_category")))
$objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100);
if(is_numeric($objConfig->Get("SearchRel_Rating_article")))
$objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100);
$SearchResultIdList = $objSearch->Result_IdList();
if(count($SearchResultIdList)>0)
{
$objSearch->PerformSearch(1,$SortOrder,TRUE,$SearchResultIdList);
//$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId");
}
$SearchPerformed = TRUE;
}
else {
$MissingCount = SetMissingDataErrors("m_simplesearch");
$MissingCount++;
$FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword");
}
break;
}
?>
Property changes on: trunk/kernel/frontaction.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/themes/default/incs/inportal_main.css
===================================================================
--- trunk/themes/default/incs/inportal_main.css (revision 288)
+++ trunk/themes/default/incs/inportal_main.css (revision 289)
@@ -1,795 +1,803 @@
/*--- THE BASICS ---*/
body {
color : #000000;
background : #ffffff;
font-family : arial, helvetica, sans-serif;
font-size : 12px;
margin : 0;
padding: 0;
}
ul,ol,li {
color : #333333;
font-family : arial, helvetica, sans-serif;
font-size : 12px;
}
form {
margin : 0;
}
img, a img {
border: 0;
}
.img-intextleft {
margin-left: 5px;
margin-bottom: 5px;
}
a {
color : #1f569a;
text-decoration : underline;
}
a:link {
color : #1f569a;
text-decoration : underline;
}
a:hover {
color : #619ae0;
text-decoration : underline;
}
p {
font-family : arial, helvetica, sans-serif;
font-size : 11px;
font-weight : normal;
color: #000000;
line-height: 14px;
margin-top: 2px;
margin-bottom: 5px;
}
td {
font-family : arial, verdana, sans-serif;
font-size : 12px;
}
h1 {
font-family : verdana, helvetica, sans-serif;
font-size : 20px;
font-weight : bold;
color: #1f569a;
margin: 10px 0px;
line-height: 22px
}
h1 span {
font-size : 14px;
color: #999999;
}
h2, h2 span {
font-family : verdana, helvetica, sans-serif;
font-size : 20px;
font-weight : normal;
color: #009ff0;
margin : 0;
}
h2 span {
font-size : 14px;
color: #999999;
}
h3, h3 span {
font-family : verdana, helvetica, sans-serif;
font-size : 16px;
font-weight : normal;
color: #009ff0;
margin: 0;
}
h3 span {
font-size : 12px;
font-weight : normal;
color: #999999;
}
h4, h4 span {
font-family : verdana, helvetica, sans-serif;
font-size : 12px;
font-weight : normal;
color: #009ff0;
margin: 0;
}
h4 span {
font-size : 10px;
font-weight : normal;
color: #999999;
}
.tip {
cursor : help;
border-bottom : 1px dashed #999999;
}
.table-collapse {
border-collapse: collapse;
}
.input {
font-family : arial, verdana, sans-serif;
font-size : 11px;
color: #000000;
background-color: #ffffff;
border: 1px inset #94c0de;
}
.textarea {
font-family : arial, verdana, sans-serif;
font-size : 11px;
color: #000000;
background-color: #ffffff;
border: 1px inset #94c0de;
}
.button {
font-family: arial, helvetica, sans-serif;
font-size: 10px;
font-weight: normal;
text-decoration: none;
color: #000000;
padding: 0 2 0 2;
border-style: outset;
border-color: #ffffff #999999 #999999 #ffffff;
border-width: 1px;
width:auto;
cursor: hand;
background: #fcde79 url("../img/bgr_button.gif") repeat-x scroll right top;
margin: 1px;
}
select {
font-size: 11px;
}
/*--- HEADINGS ---*/
.welcome {
font-family : verdana, helvetica, sans-serif;
color : #009ff0;
font-size : 20px;
font-weight : bold;
text-decoration : none;
}
.page-title {
margin-bottom: 10px;
color : #1f569a;
}
.item, .item a, item a:hover,
.item-small, .item-small a, .item-small a:hover,
.item-spec, .item-spec a, .item-spec a:hover,
.item-my, .item-my a, item-my a:hover, .item-my-stat
.quick-title, .quick-title a, .quick-title a:hover,
.reviewer {
font-family : verdana, helvetica, sans-serif;
color : #1f569a;
font-size : 12px;
font-weight : bold;
text-decoration : none;
}
.item a {
text-decoration : underline;
}
.item a:hover {
color : #619ae0;
text-decoration : underline;
}
.item-spec {
font-size : 11px;
}
.item-spec a {
color: 3333ff;
font-size : 11px;
text-decoration : underline;
}
.item-spec a:hover {
color : #619ae0;
font-size : 11px;
text-decoration : underline;
}
.item-small {
font-size : 11px;
}
.item-small a {
font-size : 11px;
text-decoration : underline;
}
.item-small a:hover {
color : #619ae0;
font-size : 11px;
text-decoration : underline;
}
.item-my, .item-my a, .item-my a:hover {
font-size : 11px;
}
.item-my a:hover {
text-decoration : none;
}
.item-my-stat {
font-size : 10px;
font-weight : normal;
}
.quick-title {
color : #009FF0;
font-size : 11px;
font-weight : bold;
text-decoration : none;
}
.quick-title a {
color : #009FF0;
font-size : 11px;
text-decoration : underline;
}
.quick-title a:hover {
color : #1f569a;
font-size : 11px;
text-decoration : underline;
}
.reviewer {
color : #000000;
font-size : 12px;
font-weight : bold;
text-decoration : none;
}
.posts, a.posts, a:hover.posts, .posts a, .posts a:hover {
font: 11px verdana, helvetica, sans-serif;
color : #1f569a;
text-decoration : none;
}
a.posts {
text-decoration : none;
}
a:hover.posts {
color : #619ae0;
text-decoration : underline;
}
.posts a {
text-decoration : none;
}
.posts a:hover {
color : #619ae0;
text-decoration : underline;
}
.post-altern {
background: #E6F0F9
}
.new, .pop, .hot, .top {
font-family : arial, helvetica, sans-serif;
color : #00c600;
font-size : 9px;
vertical-align: super;
font-weight : normal;
text-decoration : none;
text-transform: uppercase;
}
.pop {
color : #00cece;
}
.hot {
color : #d92100;
}
.top {
color : #00cece;
}
.poster {
font: 10px verdana, sans-serif;
}
.forum-data, .forum-time {
font: 10px verdana, helvetica, sans-serif;
text-decoration : none;
}
.forum-time {
color : #666;
}
.forum-name td {
font: 11px verdana, sans-serif;
border-bottom: 1px dashed #ccc
}
.post-text, .post-text td {
font: 10px verdana, sans-serif;
}
.forum {
font: 14px arial, sans-serif;
text-decoration: none
}
.login-box-top, .friend-box-top, .login-name {
font-family : verdana, helvetica, sans-serif;
color : #ffffff;
font-size : 12px;
font-weight : bold;
text-decoration : none;
background-color: #64a1df;
padding: 5px;
padding-left: 7px;
}
.login-name {
font-size : 11px;
font-weight : normal;
text-decoration : none;
background-color: #64a1df;
padding: 1px;
}
.login-name a {
text-decoration: none;
color: #fff
}
.login-name a:hover {
color: #1f569a;
text-decoration: none
}
.friend-box-top {
color : #1f569a;
background-color: #94c0de;
border-top: 1px solid #64a1df;
}
.act-box-top, .act-title-it {
padding-left: 7px;
font-family : arial, helvetica, sans-serif;
color : #ffffff;
font-size : 20px;
font-weight : bold;
text-decoration : none;
letter-spacing: 0,5em;
background-color: #1F569A;
}
.act-sep {
color : #ffffff;
font-size : 16px;
font-weight : normal;
}
.act-title-it {
padding-left: 0px;
font-weight : normal;
font-style: oblique;
}
.bgr-login, .bgr-friend-box, .bgr-quick-links-top, .bgr-quick-links, .bgr-quick-links-bottom, .bgr-act {
padding: 7px;
background: #e3edf6 url("../img/bgr_login.jpg") repeat-y scroll left top;
border-bottom: 1px solid #64a1df;
}
.bgr-loggedin {
padding: 7px;
background: #e3edf6 url("../img/bgr_loggedin.jpg") no-repeat scroll right top;
}
.bgr-friend-box {
background: #ffffff url("../img/bgr_friendbox.jpg") repeat-y scroll left top;
border-bottom: 1px solid #64a1df;
}
.bgr-quick-links-top {
background: #ffffff url("../img/bgr_quick_links_top.jpg") no-repeat scroll right top;
border-bottom: none;
}
.bgr-quick-links {
background: #ffffff url("../img/bgr_quick_links.jpg") no-repeat scroll right top;
border-bottom: none;
}
.bgr-quick-links-bottom {
background: none;
}
.bgr-act {
padding-top: 0px;
background: #ffffff url("../img/bgr_actionbox.jpg") repeat-y scroll right top;
border-top: none;
border-bottom: none;
}
.bgr-act-bottom {
background: #ffffff url("../img/bgr_actionbox.jpg") repeat-y scroll right top;
border-bottom: 1px solid #64a1df;
padding: 0px;
}
.box {
border: 1px solid #64a1df;
}
.open-box {
border: 1px solid #64a1df;
border-top: none;
}
/*--- NAVIGATION STYLES ---*/
.head-nav, .head-nav td, .head-nav td a, head-nav td a:hover {
font-family : verdana, helvetica, sans-serif;
color : #ffffff;
font-size : 10px;
font-weight : bold;
text-decoration : none;
}
.head-nav td a {
color : #94c0de;
}
.head-highlight a, .head-nav td a:hover {
color : #ffffff;
text-decoration : none;
}
.head-highlight {
color : #ffffff;
text-decoration : none;
}
.post-action, .post-action a {
font-family : arial, helvetica, sans-serif;
color : #ffffff;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.post-action a:hover {
color : #ffffff;
text-decoration : underline;
}
.post-action-alt,.post-action-alt, .post-action-alt a, .post-action-alt a {
font-family : arial, helvetica, sans-serif;
color : #ffffff;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.post-action-alt a:hover,.post-action-alt-last a:hover {
color : #ffffff;
text-decoration : underline;
}
.path, .path a, .zoom {
font-family : arial, helvetica, sans-serif;
color : #ffffff;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.path a {
text-decoration : underline;
color : #ffff00;
}
.path a:hover {
color : #ffffff;
text-decoration : underline;
}
.zoom, .zoom a, .zoom a:hover {
text-decoration : none;
}
.quick-links, .quick-links a, .quick-links a:hover, .links-action, .links-action a, .links-action a:hover,
.tips, .tips a, .tips a:hover,
.option-txt {
font-family : verdana, helvetica, sans-serif;
color : #1f569a;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.quick-links a {
color : #1f569a;
text-decoration : underline;
}
.quick-links a:hover {
color : #619ae0;
text-decoration : underline;
}
.links-action a {
color : #999999;
text-decoration : none;
}
.links-action a:hover {
color : #1f569a;
text-decoration : none;
}
.tips-i {
font-family : verdana, helvetica, sans-serif;
font-size : 11px;
font-weight : normal;
font-style: oblique;
}
.tips, .tips-i {
color : #666666;
}
.tips a, .tips-i a {
text-decoration : underline;
color : #666666;
}
.tips a:hover, .tips-i a:hover {
text-decoration : underline;
color : #999999;
}
.option-txt {
color : #2c73cb;
}
.option-txt a {
text-decoration : underline;
color : #2c73cb;
}
.option-txt a:hover {
color : #619ae0;
text-decoration : underline;
}
.box-links {
font-family : Tahoma, helvetica, sans-serif;
color : #004080;
font-size : 11px;
font-weight : normal;
text-decoration : none;
}
.box-links a {
color : #004080;
text-decoration : none;
}
/*--- ---*/
.pagination, .pagination a, .pagination a:hover {
font: bold 11px verdana, sans-serif;
}
.pagination a {
color: #619ae0;
}
.pagination a:hover {
color: #1f569a;
background-color: #deebf8;
}
.updated {
font-family : arial, helvetica, sans-serif;
color : #778055;
font-size : 10px;
font-weight : normal;
text-decoration : none;
letter-spacing: 1px;
}
.statistics, .statistics span, .statistics a, .statistics a:hover, .statistics td a, .statistics td a:hover {
font-family : arial, helvetica, sans-serif;
color : #64a1df;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.statistics span {
color : #999999;
font-size : 10px;
}
.statistics a {
color : #009ff0;
}
.statistics a:hover {
color : #94c0de;
}
.statistics td a {
color : #009ff0;
}
.statistics td a:hover {
color : #94c0de;
}
.comments, .field-title {
font-family : arial, helvetica, sans-serif;
color : #999999;
font-size : 10px;
font-weight : normal;
text-decoration : none;
}
.field-title {
color : #333333;
}
.welcome-text {
font-family : verdana, helvetica, sans-serif;
color : #666666;
font-size : 11px;
font-weight : normal;
text-decoration : none;
line-height: 14px;
}
.field-name {
font-family : verdana, helvetica, sans-serif;
color : #666666;
font-size : 11px;
font-weight : normal;
text-decoration : none;
background: #eeeeee none;
padding: 3px 10px 3px 10px;
white-space: nowrap;
}
.field-content, .field-content-top, .field-content-input {
padding: 4px 0px 4px 5px;
border-top: 1px dotted #eaeaea;
}
.field-content-input, .field-content-input-top {
padding: 1px 0px 1px 5px;
}
.field-content-top {
border-top: none;
}
.field-content-input-top {
border-top: none;
}
.copyright, .norate {
font-family : verdana, helvetica, sans-serif;
font-size : 9px;
color: #deebf8;
}
.norate {
color: #ff8000;
font-weight: normal;
}
.error {
color: #ff0000;
}
/*--- BACKGROUNDS ---*/
.bgr-categories {
background: #ffffff url("../img/bgr_categories.jpg") no-repeat scroll right top;
}
.bgr-myaccount {
background: #ffffff url("../img/bgr_empty.jpg") no-repeat scroll right top;
}
.bgr-news {
background: #ffffff url("../img/bgr_news.jpg") no-repeat scroll right top;
}
.bgr-links {
background: #ffffff url("../img/bgr_links.jpg") no-repeat scroll right top;
}
.bgr-forum {
background: #ffffff url("../img/bgr_forum.jpg") no-repeat scroll right top;
}
.bgr-logoside {
background: #ffffff url("../img/bgr_top_short.jpg") repeat-y scroll right top;
}
.bgr-logounder {
background: #1866AE url("../img/bgr_headmiddle.jpg") repeat-y scroll right top;
}
.bgr-headnav {
background: #1866AE url("../img/bgr_headnav.jpg") repeat-y scroll left top;
}
.bgr-topsquares {
background: #ffffff url("../img/bgr_topsquares.jpg") repeat-y scroll right top;
}
.bgr-path {
background: #61b0ec url("../img/bgr_path.jpg") repeat-y scroll left top;
}
.bott-line {
border-bottom: 1px solid #1f569a;
}
.dott-line {
border-bottom: 1px dotted #94c0de;
}
.bgr-updatefill {
background-color: #deebf8;
}
.bgr-dark {
background-color: #1f569a;
}
.bgr-updatelight {
background-color: #f5f9fd;
}
.bgr-on, .bgr-on td{
background-color: #e7f0fa;
}
.bgr-off, .bgr-off td {
background-color: #eeeeee;
}
.bgr-underactbox {
background: #e0ebf9 url("../img/bgr_underactbox.jpg") repeat-x scroll right top;
}
.bgr-welcome {
background-color: #ecede4;
}
.match {
background-color: #ffff00;
}
/* COLORS in use:
link hover: #619ae0
*/
.lang-box-top {
font-family : verdana, helvetica, sans-serif;
color : #ffffff;
font-size : 12px;
font-weight : bold;
text-decoration : none;
background-color: #1866AE;
padding: 5px;
padding-left: 7px;
}
.bgr-lang {
padding: 7px;
background: #e3edf6 url("../img/bgr_loggedin.jpg") no-repeat scroll right top;
border: 1px solid #64a1df;
}
.bgr-act-top {
background: #fff9dd url("../img/bgr_actbox.gif") no-repeat scroll right top;
border-top: none;
border-bottom: none;
}
.relevance-bar {
border-color: red;
border-width: 1px;
}
/* debug output styles */
.debug_table {
border: 1px solid green;
border-width: 0 0 1 1;
}
.debug_table TD, .debug_text {
color: #000000;
font-family: Arial, Helvetica;
font-size: 13px;
}
.debug_table TD {
border: 1px solid green;
border-width: 1 1 0 0;
+}
+
+.debug_layer {
+ position: relative;
+ overflow: auto;
+
+ height: 300px;
+ width: 600px;
}
\ No newline at end of file
Property changes on: trunk/themes/default/incs/inportal_main.css
___________________________________________________________________
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/users/addgroup_permissions.php
===================================================================
--- trunk/admin/users/addgroup_permissions.php (revision 288)
+++ trunk/admin/users/addgroup_permissions.php (revision 289)
@@ -1,181 +1,181 @@
<?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";
$browseURL = $adminURL."/browse";
$cssURL = $adminURL."/include";
//$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");
unset($objEditItems);
$objEditItems = new clsGroupList();
$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
$objEditItems->EnablePaging = FALSE;
$en = (int)$_GET["en"];
$sql ="SELECT * FROM ".$objEditItems->SourceTable;
$objEditItems->Query_Item($sql);
//echo $sql."<br>\n";
$itemcount=$objEditItems->NumItems();
$c = $objEditItems->GetItemByIndex($en);
if($itemcount>1)
{
if ($en+1 == $itemcount)
$en_next = -1;
else
$en_next = $en+1;
if ($en == 0)
$en_prev = -1;
else
$en_prev = $en-1;
}
$action = "m_edit_group";
$envar = "env=" . BuildEnv() . "&en=$en";
$section = 'in-portal:editgroup_permissions';
//Display header
$sec = $objSections->GetSection($section);
$objCatToolBar = new clsToolBar();
$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('editgroup','GroupEditStatus','".$admin."/users/user_groups.php',1);","tool_select.gif");
$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('editgroup','GroupEditStatus','".$admin."/users/user_groups.php',2);","tool_cancel.gif");
$title = prompt_language("la_Text_Editing")." ".prompt_language("la_Text_Group")." '".$c->Get("Name")."' - ".prompt_language("la_tab_Permissions");
if ( isset($en_prev) || isset($en_next) )
{
$url = $RootUrl.$admin."/users/addgroup_permissions.php";
$StatusField = "GroupEditStatus";
$form = "editgroup";
MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevGroup','la_NextGroup');
}
int_header($objCatToolBar,NULL,$title);
?>
<TABLE CELLPADDING=0 CELLSPACING=0 class="tableborder" width="100%">
<TBODY>
<tr BGCOLOR="#e0e0da">
<td WIDTH="100%" CLASS="navar">
<img height="15" src="<?php echo $imagesURL; ?>/arrow.gif" width="15" align="middle" border="0">
<span class="NAV_CURRENT_ITEM"><?php echo prompt_language("la_Prompt_SystemPermissions"); ?></span>
</td>
</TR>
</TBODY>
</TABLE>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="tableborder">
<form ID="editgroup" name="editgroup" action="" method=POST>
<?php
$Mod_names = array();
$Mod_ids = array();
$Mod_names[] = admin_language("la_PermType_Admin");
$Mod_ids[] = "Admin";
$Mod_names[] = admin_language("la_PermType_Front");
$Mod_ids[] = "Front";
$UserId = $c->Get("PortalUserId");
for($i=0;$i<count($Mod_ids);$i++)
{
$module = $Mod_names[$i];
$mod_id = $Mod_ids[$i];
echo "<TR ".int_table_color_ret().">";
echo "<TD><IMG src=\"".$imagesURL."/itemicons/icon16_permission.gif\"> ";
$getvar = "?env=".BuildEnv()."&en=$en&module=$mod_id";
echo "<A class=\"NAV_URL\" HREF=\"".$adminURL."/users/group_addpermission.php$getvar\">$module</A></TD>";
echo "</TR>";
}
?>
<input type="hidden" name="Action" value="m_noop">
<input type="hidden" name="GroupId" value="<?php echo $c->Get("ResourceId"); ?>">
-<input type="hidden" name="PermList" value="<?php echo implode(",",$permlist); ?>">
+<!-- <input type="hidden" name="PermList" value="<?php //echo implode(',', GetVar('PermList') ); ?>"> -->
<input type="hidden" name="GroupEditStatus" value="0">
</FORM>
</TABLE>
<?php int_footer(); ?>
Property changes on: trunk/admin/users/addgroup_permissions.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/cat_select.php
===================================================================
--- trunk/admin/cat_select.php (revision 288)
+++ trunk/admin/cat_select.php (revision 289)
@@ -1,386 +1,385 @@
<?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. ##
##############################################################
$b_header_addon = "<DIV style='position:relative; z-Index: 1; background-color: #ffffff; padding-top:1px;'><div style='z-Index:1; position:relative'>";
$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;
}
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;
$cssURL = $adminURL."/include";
$imagesURL = $adminURL."/images";
$browseURL = $adminURL."/browse";
$destform = $_GET["destform"];
$destfield = $_GET["destfield"];
RegisterEnv("destform",$destform);
RegisterEnv("destfield",$destfield);
RegisterEnv("source",$_GET["source"]);
$envar = "env=" . BuildEnv();
$m_var_list_update["cat"] = 0;
//$homeURL = $_SERVER["PHP_SELF"]."?".$envar;
$homeURL = "javascript:AdminCatNav('".$_SERVER["PHP_SELF"]."?env=".BuildEnv()."');";
-if((int)$_GLOBALS["debuglevel"])
- echo $homeURL."<br>\n";
+if( $GLOBALS['debuglevel'] ) echo $homeURL."<br>\n";
unset($m_var_list_update["cat"]);
if($objCatList->CurrentCategoryID()>0)
{
$c = $objCatList->CurrentCat();
$upURL = $c->Admin_Parent_Link();
}
else
$upURL = $_SERVER["PHP_SELF"]."?".$envar;
//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");
$m = GetModuleArray();
foreach($m as $key=>$value)
{
$path = $pathtoroot.$value."admin/include/parser.php";
if(file_exists($path))
{
//echo "<!-- $path -->";
@include_once($path);
}
}
//Set Section
$section = 'in-portal:catselect';
//Set Environment Variable
//echo $objCatList->ItemsOnClipboard()." Categories on the clipboard<br>\n";
//echo $objTopicList->ItemsOnClipboard()." Topics on the clipboard<br>\n";
//echo $objLinkList->ItemsOnClipboard()." Links on the clipboard<br>\n";
//echo $objArticleList->ItemsOnClipboard()." Articles on the clipboard<br>\n";
$SearchType = $objSession->GetVariable("SearchType");
if(!strlen($SearchType))
$SearchType = "Categories";
$SearchLabel = "la_SearchLabel";
/* 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">
END;
require_once($pathtoroot.$admin."/include/mainscript.php");
print <<<END
<script src="$browseURL/toolbar.js"></script>
<script src="$browseURL/checkboxes_new.js"></script>
<script language="JavaScript1.2" src="$browseURL/fw_menu.js"></script>
<script language="JavaScript1.2">
var enableContextMenus= true;
var doubleClickAction = 'select';
function toggleTabB(tabId, atm)
{
var hl = document.getElementById("hidden_line");
var activeTabId;
if (activeTab) activeTabId = activeTab.id;
if (activeTabId == tabId)
{
var devider = document.getElementById("tabsDevider");
devider.style.display = "";
unselectAll(tabId);
var tab = document.getElementById(tabId);
tab.active = false;
activeTab = null;
collapseTab = tab;
toolbar.setTab(null);
showTab();
}
else
{
if (activeTab)
toggleTab(tabId, true)
else
toggleTab(tabId, atm)
if (hl) hl.style.display = "none";
}
tab_hdr = document.getElementById('tab_headers');
if (!tab_hdr) return;
// process all module tabs
var active_str = '';
for(var i = 0; i < tabIDs.length; i++)
{
var tabHeader;
TDs = tab_hdr.getElementsByTagName("TD");
for (var j = 0; j < TDs.length; j++)
if (TDs[j].getAttribute("tabHeaderOf") == tabIDs[i])
{
tabHeader = TDs[j];
break;
}
if (!tabHeader) continue;
var tab = document.getElementById(tabIDs[i]);
if (!tab) continue;
active_str = (tab.active) ? "tab_active" : "tab_inactive";
if (TDs[j].getAttribute("tabHeaderOf") == tabId) {
// module tab is selected
SetBackground('l_' + tabId, "$imagesURL/itemtabs/" + active_str + "_l.gif");
SetBackground('m_' + tabId, "$imagesURL/itemtabs/" + active_str + ".gif");
SetBackground('m1_' + tabId, "$imagesURL/itemtabs/" + active_str + ".gif");
SetBackground('r_' + tabId, "$imagesURL/itemtabs/" + active_str + "_r.gif");
}
else
{
// module tab is not selected
SetBackground('l_' +tabIDs[i], "$imagesURL/itemtabs/" + active_str + "_l.gif");
SetBackground('m_' + tabIDs[i], "$imagesURL/itemtabs/" + active_str + ".gif");
SetBackground('m1_' + tabIDs[i], "$imagesURL/itemtabs/" + active_str + ".gif");
SetBackground('r_' + tabIDs[i], "$imagesURL/itemtabs/" + active_str + "_r.gif");
}
var images = tabHeader.getElementsByTagName("IMG");
if (images.length < 1) continue;
images[0].src = "$imagesURL/itemtabs/" + ((tab.active) ? "divider_up" : "divider_empty") + ".gif";
}
}
function toggleCategoriesB(tabHeader, instant)
{
var categories = document.getElementById('categories');
if (!categories) return;
toggleCategories(instant);
var active_str = '$imagesURL'+'/itemtabs/' + (categories.active ? 'tab_active' : 'tab_inactive');
SetBackground('l_cat', active_str + '_l.gif');
SetBackground('m_cat', active_str + '.gif');
SetBackground('m1_cat', active_str + '.gif');
SetBackground('r_cat', active_str + '_r.gif');
var images = tabHeader.getElementsByTagName("IMG");
if (images.length < 1) return;
images[0].src = '$imagesURL'+'/itemtabs/' + ((categories.active) ? "divider_up" : "divider_dn") + ".gif";
}
</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;
int_SectionHeader();
?>
</div>
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<div name="toolBar" id="mainToolBar">
<tb:button action="select" alt="<?php echo admin_language("la_ToolTip_Select"); ?>" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:button action="stop" alt="<?php echo admin_language("la_ToolTip_Cancel"); ?>" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:separator ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:button action="upcat" alt="<?php echo admin_language("la_ToolTip_Up"); ?>" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:button action="homecat" alt="<?php echo admin_language("la_ToolTip_Home"); ?>" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:separator ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:button action="view" alt="<?php echo admin_language("la_ToolTip_View"); ?>" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
</div>
</td>
</tr>
</tbody>
</table>
<table cellspacing="0" cellpadding="0" width="100%" bgcolor="#e0e0da" border="0" class="tableborder_full_a">
<tbody>
<tr>
<td><img height="15" src="<?php echo $imagesURL; ?>/arrow.gif" width="15" align="middle" border="0">
<span class="navbar"><?php print m_navbar(1); ?></span>
</td>
<td align="right">
<FORM METHOD="POST" ACTION="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" NAME="admin_search" ID="admin_search"><INPUT ID="SearchScope" NAME="SearchScope" type="hidden" VALUE="<?php echo $objSession->GetVariable("SearchScope"); ?>"><INPUT ID="SearchType" NAME="SearchType" TYPE="hidden" VALUE="<?php echo $objSession->GetVariable("SearchType"); ?>"><INPUT ID="NewSearch" NAME="NewSearch" TYPE="hidden" VALUE="0"><INPUT TYPE="HIDDEN" NAME="Action" value="m_Exec_Search">
<table cellspacing="0" cellpadding="0"><tr>
<td><?php echo admin_language($SearchLabel); ?>&nbsp;</td>
<td><input ID="SearchWord" type="text" name="SearchWord" size="10" style="border-width: 1; border-style: solid; border-color: #999999"></td>
<td><img action="search_b" src="<?php echo $imagesURL."/toolbar/";?>/icon16_search.gif" alt="<?php echo admin_language("la_ToolTip_Search"); ?>" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="<?php echo $imagesURL."/toolbar/";?>/arrow16.gif" onmouseover="this.src='<?php echo $imagesURL."/toolbar/";?>/icon16_search_f2.gif'" onmouseout="this.src='<?php echo $imagesURL."/toolbar/";?>/icon16_search.gif'" style="cursor:hand" width="22" width="22"><img action="search_a" alt="<?php echo admin_language("la_ToolTip_Search"); ?>" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="<?php echo $imagesURL."/toolbar/";?>/arrow16.gif" onmouseover="this.src='<?php echo $imagesURL."/toolbar/";?>/arrow16_f2.gif'" onmouseout="this.src='<?php echo $imagesURL."/toolbar/";?>/arrow16.gif'" style="cursor:hand">
<img action="search_c" src="<?php echo $imagesURL."/toolbar/";?>/icon16_search_reset.gif" alt="<?php echo admin_language("la_ToolTip_Search"); ?>" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" onmouseover="this.src='<?php echo $imagesURL."/toolbar/";?>/icon16_search_reset_f2.gif'" onmouseout="this.src='<?php echo $imagesURL."/toolbar/";?>/icon16_search_reset.gif'" style="cursor:hand" width="22" width="22">&nbsp;
</td>
</tr></table>
</FORM>
<!--tb:button action="search_b" alt="<?php echo admin_language("la_ToolTip_Search"); ?>" align="right" ImagePath="<?php echo $imagesURL."/toolbar/";?>">
<tb:button action="search_a" alt="<?php echo admin_language("la_ToolTip_Search"); ?>" align="right" ImagePath="<?php echo $imagesURL."/toolbar/";?>"-->
</td>
</tr>
</tbody>
</table>
<br>
<!-- CATEGORY DIVIDER -->
<?php
$OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
$objCatList->Clear();
if($SearchType=="categories" || $SearchType="all")
{
$list = $objSession->GetVariable("SearchWord");
$SearchQuery = $objCatList->AdminSearchWhereClause($list);
if(strlen($SearchQuery))
{
$SearchQuery = " (".$SearchQuery.") ";
if(strlen($CatScopeClause))
$SearchQuery .= " AND ".$CatScopeClause;
$objCatList->LoadCategories($SearchQuery.$CategoryFilter,$OrderBy);
}
else
$objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter,$OrderBy);
}
else
$objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter,$OrderBy);
?>
<table cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td width="138" height="20" nowrap="nowrap" class="active_tab" onclick="toggleCategoriesB(this)" id="cats_tab">
<table cellspacing="0" cellpadding="0" width="100%" border="0">
<tr>
<td id="l_cat" background="<?php echo $imagesURL; ?>/itemtabs/tab_active_l.gif" class="left_tab">
<img src="<?php echo $imagesURL; ?>/itemtabs/divider_up.gif" width="20" height="20" border="0" align="absmiddle">
</td>
<td id="m_cat" nowrap background="<?php echo $imagesURL; ?>/itemtabs/tab_active.gif" class="tab_class">
<?php echo admin_language("la_ItemTab_Categories"); ?>:&nbsp;
</td>
<td id="m1_cat" align="right" valign="top" background="<?php echo $imagesURL; ?>/itemtabs/tab_active.gif" class="tab_class">
<span class="cats_stats">(<?php echo $objCatList->QueryItemCount; ?>)</span>&nbsp;
</td>
<td id="r_cat" background="<?php echo $imagesURL; ?>/itemtabs/tab_active_r.gif" class="right_tab">
<img src="<?php echo $imagesURL; ?>/spacer.gif" width="21" height="20">
</td>
</tr>
</table>
</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<div class="divider" style="" id="categoriesDevider"><img width=1 height=1 src="images/spacer.gif"></div>
</DIV>
<DIV style="background-color: #ffffff; position: relative; padding-top: 1px; top: -1px; z-Index:0" id="firstContainer">
<DIV style="background-color: #ffffff; position: relative; padding-top: 1px; top: -1px; z-Index: 2" id="secondContainer">
<!-- CATEGORY OUTPUT START -->
<div id="categories" tabtitle="Categories">
<form id="categories_form" name="categories_form" action="" method="post">
<input type="hidden" name="Action">
<?php print adListSubCats($objCatList->CurrentCategoryID(),"cat_select_element.tpl"); ?>
</form>
</div>
<BR>
<!-- CATEGORY OUTPUT END -->
</DIV>
<form method="post" action="cat_select.php?env=<?php echo BuildEnv(); ?>" 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>
</DIV>
<!-- END CODE-->
<script language="JavaScript">
<?php
//if($_GET["Selector"]=="radio")
echo " var single_select = true;";
?>
InitPage();
</script>
<?php int_footer(); ?>
Property changes on: trunk/admin/cat_select.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/globals.php
===================================================================
--- trunk/globals.php (revision 288)
+++ trunk/globals.php (revision 289)
@@ -1,1353 +1,1365 @@
<?php
$vars = parse_portal_ini($pathtoroot."config.php");
while($key = key($vars))
{
$key = "g_".$key;
global $$key;
$$key = current($vars); //variable variables
next($vars);
}
/*list the tables which contain item data */
$ItemTables = array();
$KeywordIgnore = array();
global $debuglevel;
-$debuglevel=0;
-$_GLOBALS["debuglevel"]=0;
+$debuglevel = 0;
+//$GLOBALS['debuglevel'] = 0;
/*New, Hot, Pop field values */
define('NEVER', 0);
define('ALWAYS', 1);
define('AUTO', 2);
/*Status Values */
define('STATUS_DISABLED', 0);
define('STATUS_ACTIVE', 1);
define('STATUS_PENDING', 2);
$LogLevel=0;
$LogFile = NULL;
function parse_portal_ini($file, $parse_section = false) {
if(!file_exists($file) && !is_readable($file))
die('Could Not Open Ini File');
$contents = file($file);
$retval = array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if ($resave) {
$fp = fopen($file, "w");
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
function &GetADODBConnection()
{
global $g_adodbConnection, $g_DBType, $g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_DebugMode;
global $ADODB_FETCH_MODE,$ADODB_COUNTRECS,$ADODB_CACHE_DIR,$pathtoroot;
//echo '<pre>'.print_r( debug_backtrace() , true).'</pre>';
if(!isset($g_adodbConnection) && strlen($g_DBType)>0)
{
$g_adodbConnection = ADONewConnection($g_DBType);
$connected = $g_adodbConnection->Connect($g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName);
if(!$connected)
{
echo "Error connecting to database $g_DBHost <br>\n";
die();
}
$ADODB_CACHE_DIR = $pathtoroot."cache";
$ADODB_FETCH_MODE = 2;
$ADODB_COUNTRECS = FALSE;
$g_adodbConnection->debug = defined('ADODB_OUTP') ? 1 : 0;
$g_adodbConnection->cacheSecs = 3600;
$g_adodbConnection->Execute('SET SQL_BIG_SELECTS=1');
}
elseif (!strlen($g_DBType)) {
global $rootURL;
echo "In-Portal is probably not installed, or configuration file is missing.<br>";
echo "Please use the installation script to fix the problem.<br><br>";
if (!preg_match('/admin/', $_SERVER['SCRIPT_FILENAME'])) {
$ins = 'admin/';
}
echo "<a href='$rootURL".$ins."install.php'>Go to installation script</a><br><br>";
flush();
die();
}
return $g_adodbConnection;
}
function GetNextResourceId($Increment=1)
{
$sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment;
$adodbConnection = GetADODBConnection();
$adodbConnection->Execute($sql);
$rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator");
$val = $rs->fields["lastid"];
if(!$rs || $rs->EOF)
{
echo $adodbConnection->ErrorMsg();
$sql = "INSERT INTO ".GetTablePrefix()."IdGenerator (lastid) VALUES ($Increment)";
$adodbConnection->Execute($sql);
$val = 1;
}
$val = $val-($Increment-1);
return $val;
}
function AddSlash($s)
{
if(substr($s,-1) != "/")
{
return $s."/";
}
else
return $s;
}
function StripNewline($s)
{
$bfound = false;
while (strlen($s)>0 && !$bfound)
{
if(ord(substr($s,-1))<32)
{
$s = substr($s,0,-1);
}
else
$bfound = true;
}
return $s;
}
function DeleteElement($array, $indice)
{
for($i=$indice;$i<count($array)-1;$i++)
$array[$i] = $array[$i+1];
unset($array[count($array)-1]);
return $array;
}
function DeleteElementValue($needle, &$haystack)
{
while(($gotcha = array_search($needle,$haystack)) > -1)
unset($haystack[$gotcha]);
}
function TableCount($TableName, $where="",$JoinCats=1)
{
$db = GetADODBConnection();
if(!$JoinCats)
{
$sql = "SELECT count(*) as TableCount FROM $TableName";
}
else
$sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
if(strlen($where)>0)
$sql .= " WHERE ".$where;
$rs = $db->Execute($sql);
// echo "SQL TABLE COUNT: ".$sql."<br>\n";
$res = $rs->fields["TableCount"];
return $res;
}
Function QueryCount($sql)
{
$countsql = "SELECT count(*) as TableCount ".substr($sql,strpos($sql," FROM "));
if(strpos($countsql,"LIMIT"))
$countsql = substr($countsql,0,strpos($countsql,"LIMIT"));
if(strpos($countsql,"ORDER BY"))
$countsql = substr($countsql,0,strpos($countsql,"ORDER BY"));
$db = GetADODBConnection();
$rs = $db->Execute($countsql);
//echo $countsql."<br>\n";
$res = $rs->fields["TableCount"];
return $res;
}
function GetPageCount($ItemsPerPage,$NumItems)
{
if($ItemsPerPage==0 || $NumItems==0)
{
return 1;
}
$value = $NumItems/$ItemsPerPage;
return ceil($value);
}
function GetTablePrefix()
{
global $g_TablePrefix;
return $g_TablePrefix;
}
function TableHasPrefix($t)
{
$pre = GetTablePrefix();
if(strlen($pre)>0)
{
if(substr($t,0,strlen($pre))==$pre)
{
return TRUE;
}
else
return FALSE;
}
else
return TRUE;
}
function AddTablePrefix($t)
{
if(!TableHasPrefix($t))
$t = GetTablePrefix().$t;
return $t;
}
function ThisDomain()
{
global $objConfig, $g_Domain;
if($objConfig->Get("DomainDetect"))
{
$d = $_SERVER['HTTP_HOST'];
}
else
$d = $g_Domain;
return $d;
}
function GetIndexUrl($secure=0)
{
global $indexURL, $rootURL, $secureURL;
switch($secure)
{
case 0:
$ret = $indexURL;
break;
case 1:
$ret = $secureURL."index.php";
break;
case 2:
$ret = $rootURL."index.php";
break;
default:
$ret = $i;
}
return $ret;
}
function GetLimitSQL($Page,$PerPage)
{
if($Page<1)
$Page=1;
if(is_numeric($PerPage))
{
if($PerPage==0)
$PerPage = 20;
$Start = ($Page-1)*$PerPage;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $limit;
}
function filelist ($currentdir, $startdir=NULL,$ext=NULL)
{
global $pathchar;
//chdir ($currentdir);
// remember where we started from
if (!$startdir)
{
$startdir = $currentdir;
}
$d = @opendir($currentdir);
$files = array();
if(!$d)
return $files;
//list the files in the dir
while (false !== ($file = readdir($d)))
{
if ($file != ".." && $file != ".")
{
if (is_dir($currentdir."/".$file))
{
// If $file is a directory take a look inside
$a = filelist ($currentdir."/".$file, $startdir,$ext);
if(is_array($a))
$files = array_merge($files,$a);
}
else
{
if($ext!=NULL)
{
$extstr = stristr($file,".".$ext);
if(strlen($extstr))
$files[] = $currentdir."/".$file;
}
else
$files[] = $currentdir.'/'.$file;
}
}
}
closedir ($d);
return $files;
}
function DecimalToBin($dec,$WordLength=8)
{
$bits = array();
$str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
for($i=$WordLength;$i>0;$i--)
{
$bits[$i-1] = (int)substr($str,$i-1,1);
}
return $bits;
}
function inp_escape($in, $html_enable=0)
{
$out = stripslashes($in);
$out = str_replace("\n", "\n^br^", $out);
if($html_enable==0)
{
$out=ereg_replace("<","&lt;",$out);
$out=ereg_replace(">","&gt;",$out);
$out=ereg_replace("\"","&quot;",$out);
$out = str_replace("\n^br^", "\n<br />", $out);
}
else
$out = str_replace("\n^br^", "\n", $out);
$out=addslashes($out);
return $out;
}
function inp_unescape($in)
{
$out=stripslashes($in);
return $out;
}
function inp_textarea_unescape($in)
{
$out=stripslashes($in);
$out = str_replace("\n<br />", "\n", $out);
return $out;
}
function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($Keywords as $k) {
for ($i = 0; $i < count($r); $i++) {
if ($r[$i] == "<") {
$i++; continue;
}
$r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
}
}
return join("", $r);
}
/*
function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
{
global $objConfig;
if(!strlen($OpenTag))
$OpenTag = "<B>";
if(!strlen($CloseTag))
$CloseTag = "</B>";
$ret = strip_tags($html);
foreach ($Keywords as $k)
{
if(strlen($k))
{
//$html = str_replace("<$k>", ":#:", $html);
//$html = str_replace("</$k>", ":##:", $html);
//$html = strip_tags($html);
if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
//if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
$ret = $html;
//$ret = str_replace(":#:", "<$k>", $ret);
//$ret = str_replace(":##:", "</$k>", $ret);
}
}
return $ret;
}
*/
function ExtractDatePart($part,$datestamp)
{
switch($part)
{
case "month":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("m",$datestamp);
break;
case "day":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("d", $datestamp);
break;
case "year":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("Y", $datestamp);
break;
case "time_24hr":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("H:i", $datestamp);
break;
case "time_12hr":
if($datestamp<=0)
{
$ret = "";
}
else
$ret = adodb_date("g:i a",$datestamp);
break;
}
return $ret;
}
function GetLocalTime($TimeStamp,$TargetZone=NULL)
{
if($TargetZone==NULL)
$TargetZone = $objConfig->Get("Config_Site_Time");
$server = $objConfig->Get("Config_Server_Time");
if($TargetZone!=$server)
{
$offset = ($server - $TargetZone) * -1;
$TimeStamp = $TimeStamp + (3600 * $offset);
}
return $TimeStamp;
}
function _unhtmlentities ($string)
{
$trans_tbl = get_html_translation_table (HTML_ENTITIES);
$trans_tbl = array_flip ($trans_tbl);
return strtr ($string, $trans_tbl);
}
function getLastStr($hay, $need){
$getLastStr = 0;
$pos = strpos($hay, $need);
if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
while($pos) {
$getLastStr = $getLastStr + $pos + strlen($need);
$hay = substr ($hay , $pos + strlen($need));
$pos = strpos($hay, $need);
}
return $getLastStr - strlen($need);
} else {
return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
}
}
function ReplaceSingleTag($tag,$text)
{
$opentag = "[".$tag;
$closetag = "[/".$tag."]";
if(strstr($text,$opentag))
{
$pos = strpos($text,$opentag." ");
if($pos === false)
{
$pos = strpos($text,$opentag."]");
}
$endopen = strpos($text,"]",$pos);
$closepos = strpos($text,$closetag,$pos);
if($closepos)
{
$taglength = ($closepos - $endopen) + strlen($closetag);
$tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos);
$innerText = substr($text,$endopen+1,$closepos - $endopen-1);
if($tag=="UL")
$innerText = str_replace("[*]","<LI>",$innerText);
$tagText = substr($tagText,1,($endopen - $pos)-1);
//echo "Matched $tagText <br>\n";
$tagText = "<".$tagText.">";
$replace_text = $tagText.$innerText."</".$tag.">";
$text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
return $text;
}
else
return $text;
}
else
return $text;
}
function ReplaceTag($tag,$text)
{
$new_text = ReplaceSingleTag($tag,$text);
while($new_text != $text)
{
$text = $new_text;
$new_text = ReplaceSingleTag($tag,$text);
}
return $new_text;
}
function ReplaceURL($text)
{
while(strstr($text,"[URL"))
{
$urlpos = strpos($text,"[URL");
$endopen = strpos($text,"]",$urlpos);
if($endopen)
{
$url = "<A TARGET=\"_blank\"".substr($text,$urlpos+4,$endopen - ($urlpos+4));
$url .= ">";
$url = _unhtmlentities($url);
$text = substr($text,0,$urlpos).$url.substr($text,$endopen+1);
}
}
$text = str_replace("[/URL]","</A>",$text);
return $text;
}
function ReplaceBBCode($text)
{
global $objConfig;
$tags = explode(",",$objConfig->Get("BBTags"));
for($i=0;$i<count($tags);$i++)
{
$text = ReplaceTag(strtoupper($tags[$i]),$text);
}
$text = ReplaceURL($text);
return $text;
}
function GetMinValue($Table,$Field, $Where=NULL)
{
$ret = 0;
$sql = "SELECT min($Field) as val FROM $Table ";
if(strlen($where))
$sql .= "WHERE $Where";
$ado = GetADODBConnection();
$rs = $ado->execute($sql);
if($rs)
$ret = (int)$rs->fields["val"];
return $ret;
}
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
function SetMissingDataErrors($f)
{
global $FormError;
$count = 0;
if(is_array($_POST))
{
if(is_array($_POST["required"]))
{
foreach($_POST["required"] as $r)
{
$found = FALSE;
if(is_array($_FILES))
{
if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
}
if(!strlen(trim($_POST[$r])) && !$found)
{
$count++;
if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
$r = "dob";
- $tag = $_POST["errors"][$r];
+ $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
if(!strlen($tag))
$tag = "lu_ferror_".$f."_".$r;
$FormError[$f][$r] = language($tag);
}
}
}
}
return $count;
}
function makepassword($length=10)
{
$pass_length=$length;
$p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2=array('a','e','i','o','u');
$p3=array('1','2','3','4','5','6','7','8','9');
$p4=array('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1=21;// this is the count of $p1
$s2=5; // this is the count of $p2
$s3=9; // this is the count of $p3
$s4=5; // this is the count of $p4
// possible readable combinations
$c1='121'; // will be like 'bab'
$c2='212'; // will be like 'aba'
$c3='12'; // will be like 'ab'
$c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3
// $c5='4'; // uncomment to active the strong stuff
$comb='4'; // the amount of combinations you made above (and did not comment out)
for ($p=0;$p<$pass_length;)
{
mt_srand((double)microtime()*1000000);
$strpart=mt_rand(1,$comb);
// checking if the stringpart is not the same as the previous one
if($strpart<>$previous)
{
$pass_structure.=${'c'.$strpart};
// shortcutting the loop a bit
$p=$p+strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g=0;$g<strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
$sel=substr($pass_structure,$g,1);
$pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
}
return $pass;
}
function LogEntry($text,$writefile=FALSE)
{
global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
static $last;
if(strlen($g_LogFile))
{
$el = str_pad(getmicrotime()- $timestart,10," ");
if($last>0)
$elapsed = getmicrotime() - $last;
if(strlen($el)>10)
$el = substr($el,0,10);
$indent = str_repeat(" ",$LogLevel);
$text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
$LogData .= "$el:". round($elapsed,6).":$indent $text";
$last = getmicrotime();
if($writefile==TRUE && is_writable($g_LogFile))
{
if(!$LogFile)
{
if(file_exists($g_LogFile))
unlink($g_LogFile);
$LogFile=@fopen($g_LogFile,"w");
}
if($LogFile)
{
fputs($LogFile,$LogData);
}
}
}
}
function ValidEmail($email)
{
if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
{
return TRUE;
}
else
{
return FALSE;
}
}
function language($phrase,$LangId=0)
{
global $objSession, $objLanguageCache, $objLanguages;
if($LangId==0)
$LangId = $objSession->Get("Language");
if($LangId==0)
$LangId = $objLanguages->GetPrimary();
$translation = $objLanguageCache->GetTranslation($phrase,$LangId);
return $translation;
}
function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
{
global $objSession, $objLanguageCache, $objLanguages;
//echo "Language passed: $lang<br>";
if($lang==0)
$lang = $objSession->Get("Language");
//echo "Language from session: $lang<br>";
if($lang==0)
$lang = $objLanguages->GetPrimary();
//echo "Language after primary: $lang<br>";
//echo "Phrase: $phrase<br>";
$translation = $objLanguageCache->GetTranslation($phrase,$lang);
if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
{
$res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
return $res;
}
else
return $translation;
}
function prompt_language($phrase,$lang=0)
{
return admin_language($phrase,$lang,TRUE);
}
function GetPrimaryTranslation($Phrase)
{
global $objLanguages;
$l = $objLanguages->GetPrimary();
return language($Phrase,$l);
}
function CategoryNameCount($ParentId,$Name)
{
$cat_table = GetTablePrefix()."Category";
$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
$ado = GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["Name"];
$rs->MoveNext();
}
return $ret;
}
function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
{
$cat_table = GetTablePrefix()."CategoryItems";
$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
//echo $sql."<br>\n ";
$ado = GetADODBConnection();
$rs = $ado->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields[$Field];
$rs->MoveNext();
}
return $ret;
}
function &GetItemCollection($ItemName)
{
global $objItemTypes;
if(is_numeric($ItemName))
{
$item = $objItemTypes->GetItem($ItemName);
}
else
$item = $objItemTypes->GetTypeByName($ItemName);
if(is_object($item))
{
$module = $item->Get("Module");
$prefix = ModuleTagPrefix($module);
$func = $prefix."_ItemCollection";
if(function_exists($func))
{
$var =& $func();
}
}
return $var;
}
function UpdateCategoryCount($ItemTypeName=0,$ListType=NULL)
{
global $objCountCache, $objItemTypes;
if(is_numeric($ItemName))
{
$item = $objItemTypes->GetItem($ItemName);
}
else
$item = $objItemTypes->GetTypeByName($ItemName);
if(is_object($item))
{
$ItemType = $item->Get("ItemType");
$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
if(is_numeric($ListType))
{
$sql .= " AND ListType=$ListType";
}
$objCountCache->adodbConnection->Execute($sql);
}
}
function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
{
}
function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
{
}
function GetTagCache($module,$tag,$attribs,$env)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $n => $val)
{
$name .= "-".$val;
}
}
$CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
}
else
$CachedValue="";
return $CachedValue;
}
function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
{
global $objSystemCache, $objSession, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$name = $tag;
if(is_array($attribs))
{
foreach($attribs as $a => $val)
{
$name .= "-".$val;
}
}
$objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
}
}
function DeleteTagCache($name,$extraparams, $env="")
{
global $objSystemCache, $objConfig;
if($objConfig->Get("SystemTagCache"))
{
$where = "Name LIKE '$name%".$extraparams."'";
if(strlen($env))
$where .= " AND Context LIKE $env";
$objSystemCache->DeleteCachedItem($where);
}
}
function ParseTagLibrary()
{
$objTagList = new clsTagList();
$objTagList->ParseInportalTags();
unset($objTagList);
}
function GetDateFormat($LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$fmt = $l->Get("DateFormat");
}
else
$fmt = "m-d-Y";
return $fmt;
}
function GetTimeFormat($LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$fmt = $l->Get("TimeFormat");
}
else
$fmt = "H:i:s";
return $fmt;
}
function LangDate($TimeStamp=NULL,$LangId=0)
{
$fmt = GetDateFormat($LangId);
$ret = adodb_date($fmt,$TimeStamp);
return $ret;
}
function LangTime($TimeStamp=NULL,$LangId=0)
{
$fmt = GetTimeFormat($LangId);
$ret = adodb_date($fmt,$TimeStamp);
return $ret;
}
function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
{
global $objLanguages;
if(!$LangId)
$LangId= $objLanguages->GetPrimary();
$l = $objLanguages->GetItem($LangId);
if(is_object($l))
{
$ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
}
else
$ret = $num;
return $ret;
}
function replacePngTags($x, $spacer="images/spacer.gif")
{
global $rootURL,$pathtoroot;
// make sure that we are only replacing for the Windows versions of Internet
// Explorer 5+, and not Opera identified as MSIE
$msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
$opera='/opera\s+[0-9]+/i';
if(!isset($_SERVER['HTTP_USER_AGENT']) ||
!preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
return $x;
// find all the png images in backgrounds
preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
for($i=0;$i<count($background[0]);$i++){
// simply replace:
// "background-image: url('image.png');"
// with:
// "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
// enabled=true, sizingMethod=scale src='image.png');"
// haven't tested to see if background-repeat styles work...
$x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
' src=\''.$background[1][$i].'\');',$x);
}
// OK, time to find all the IMG tags with ".png" in them
preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
while(list($imgnum,$v)=@each($images[0])){
$original=$v;
$atts=''; $width=0; $height=0;
// If the size is defined by styles, find
preg_match_all('/style=".*(width: ([0-9]+))px.*'.
'(height: ([0-9]+))px.*"/Ui',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
// size was defined by styles, get values
$width=$arr2[2][0];
$height=$arr2[4][0];
}
// size was not defined by styles, get values
preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$width=$arr2[1][0];
}
preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
if(is_array($arr2) && count($arr2[0])){
$height=$arr2[1][0];
}
preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
if(isset($arr2[1][0]) && !empty($arr2[1][0]))
$image=$arr2[1][0];
else
$image=NULL;
// We do this so that we can put our spacer.gif image in the same
// directory as the image
$tmp=split('[\\/]',$image);
array_pop($tmp);
$image_path=join('/',$tmp);
if(substr($image,0,strlen($rootURL))==$rootURL)
{
$path = str_replace($rootURL,$pathtoroot,$image);
}
else
{
$path = $pathtoroot."themes/telestial/$image";
}
// echo "Sizing $path.. <br>\n";
// echo "Full Tag: ".htmlentities($image)."<br>\n";
//if(!$height || !$width)
//{
$g = imagecreatefrompng($path);
if($g)
{
$height = imagesy($g);
$width = imagesx($g);
}
//}
if(strlen($image_path)) $image_path.='/';
// end quote is already supplied by originial src attribute
$replace_src_with=$spacer.'" style="width: '.$width.
'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
'\'scale\')';
// now create the new tag from the old
$new_tag=str_replace($image,$replace_src_with,$original);
// now place the new tag into the content
$x=str_replace($original,$new_tag,$x);
}
return $x;
}
function print_pre($str)
{
// no comments here :)
echo '<pre>'.print_r($str, true).'</pre>';
}
function GetOptions($field) // by Alex
{
// get dropdown values from custom field
$tmp =& new clsCustomField();
$tmp->LoadFromDatabase($field, 'FieldName');
$tmp_values = $tmp->Get('ValueList');
unset($tmp);
$tmp_values = explode(',', $tmp_values);
foreach($tmp_values as $mixed)
{
$elem = explode('=', trim($mixed));
$ret[ $elem[0] ] = $elem[1];
}
return $ret;
}
function ResetPage($module_prefix, $page_variable = 'p')
{
// resets page in specific module when category is changed
global $objSession;
if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
{
global $var_list, $SessionQueryString, $FrontEnd;
//if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
}
//echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')<br>';
$last_cat = $objSession->GetVariable('last_category');
$prev_cat = $objSession->GetVariable('prev_category');
//echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
}
-function GetVar($name)
+function GetVar($name, $post_priority = false)
{
- return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
+ if(!$post_priority) // follow gpc_order in php.ini
+ return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
+ else // get variable from post 1stly if not found then from get
+ return isset($_POST[$name]) && $_POST[$name] ? $_POST[$name] : isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false;
}
function PassVar(&$source)
{
// source array + any count of key names in passed array
$params = func_get_args();
array_shift($params);
if( count($params) )
{
$ret = Array();
foreach($params as $var_name)
if( isset($source[$var_name]) )
$ret[] = $var_name.'='.$source[$var_name];
$ret = '&'.implode('&', $ret);
}
return $ret;
}
function GetSubmitVariable(&$array, $postfix)
{
// gets edit status of module
// used in case if some modules share
// common action parsed by kernel parser,
// but each module uses own EditStatus variable
$modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic');
foreach($modules as $module => $prefix)
if( isset($array[$prefix.$postfix]) )
return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
return false;
}
function GetModuleByAction()
{
$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
$action = $_REQUEST['Action'];
$module_prefix = explode('_', $action);
return $prefix2module[ $module_prefix[0] ];
}
function dir_size($dir) {
// calculates folder size based on filesizes inside it (recursively)
$totalsize=0;
if ($dirstream = @opendir($dir)) {
while (false !== ($filename = readdir($dirstream))) {
if ($filename!="." && $filename!="..")
{
if (is_file($dir."/".$filename))
$totalsize+=filesize($dir."/".$filename);
if (is_dir($dir."/".$filename))
$totalsize+=dir_size($dir."/".$filename);
}
}
}
closedir($dirstream);
return $totalsize;
}
function size($bytes) {
// shows formatted file/directory size
$types = Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
$current = 0;
while ($bytes > 1024) {
$current++;
$bytes /= 1024;
}
return round($bytes,2)." ".language($types[$current]);
}
function echod($str)
{
// echo debug output
echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';
}
function PrepareParams($source, $to_lower, $mapping)
{
// prepare array with form values to use with item
$result = Array();
foreach($to_lower as $field)
$result[ $field ] = $source[ strtolower($field) ];
if( is_array($mapping) )
{
foreach($mapping as $field_from => $field_to)
$result[$field_to] = $source[$field_from];
}
return $result;
}
function GetELT($field, $phrases = Array())
{
// returns FieldOptions equivalent in In-Portal
$ret = Array();
foreach($phrases as $phrase)
$ret[] = admin_language($phrase);
$ret = "'".implode("','", $ret)."'";
return 'ELT('.$field.','.$ret.')';
}
function GetModuleImgPath($module)
{
global $rootURL, $admin;
return $rootURL.$module.'/'.$admin.'/images';
}
function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
{
// each action postprocessing stuff from admin
if( !isset($_REQUEST[$StatusField]) ) return false;
$list =& $GLOBALS[$ListObjectName];
if( !is_object($list) ) $list = new $ListClass();
$SFValue = $_REQUEST[$StatusField]; // status field value
switch($SFValue)
{
case 1: // User hit "Save" button
$list->CopyFromEditTable($IDField);
break;
case 2: // User hit "Cancel" button
$list->PurgeEditTable($IDField);
break;
}
if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
if($SFValue == 1 || $SFValue == 2) $list->Clear();
}
function GetElem(&$array, $index)
{
// returns array element by index if
// such index exists
return isset($array[$index]) ? $array[$index] : false;
}
function MakeHTMLTag($element, $attrib_prefix)
{
$result = Array();
$ap_length = strlen($attrib_prefix);
foreach($element->attributes as $attib_name => $attr_value)
if( substr($attib_name, $ap_length) == $ap_length )
$result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
return count($result) ? implode(' ', $result) : false;
}
function GetImportScripts()
{
// return currently installed import scripts
static $import_scripts = Array();
if( count($import_scripts) == 0 )
{
$sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id';
$db =& GetADODBConnection();
$rs = $db->Execute($sql);
while(!$rs->EOF)
{
$rec =& $rs->fields;
$import_scripts[] = Array( 'label' => $rec['is_label'], 'url' => $rec['is_script'],
'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields']);
$rs->MoveNext();
}
}
return $import_scripts;
}
function GetImportScript($id)
{
$scripts = GetImportScripts();
return isset($scripts[$id]) ? $scripts[$id] : false;
}
+function GetNextTemplate($current_template)
+{
+ // used on front, returns next template to make
+ // redirect to
+ $dest = GetVar('dest', true);
+ if(!$dest) $dest = GetVar('DestTemplate', true);
+ return $dest ? $dest : $current_template;
+}
+
?>
Property changes on: trunk/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.14
\ No newline at end of property
+1.15
\ No newline at end of property

Event Timeline