Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 12:19 PM

in-portal

Index: trunk/admin/install/upgrades/inportal_upgrade_v1.1.1.sql
===================================================================
--- trunk/admin/install/upgrades/inportal_upgrade_v1.1.1.sql (revision 2260)
+++ trunk/admin/install/upgrades/inportal_upgrade_v1.1.1.sql (revision 2261)
@@ -1,36 +1,37 @@
INSERT INTO ConfigurationAdmin VALUES ('User_LoggedInGroup', 'la_Text_General', 'la_users_assign_all_to', 'select', NULL, '0=lu_none,<SQL>SELECT GroupId as OptionName, Name as OptionValue FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 3, 1);
INSERT INTO ConfigurationValues VALUES ('User_LoggedInGroup', '15', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationAdmin VALUES ('User_MembershipExpirationReminder', 'la_Text_General', 'la_MembershipExpirationReminder', 'text', NULL , '', '5', '1');
INSERT INTO ConfigurationValues VALUES ('User_MembershipExpirationReminder', '10', 'In-Portal:Users', 'in-portal:configure_users');
ALTER TABLE StylesheetSelectors ADD UNIQUE UniqueIdName (StylesheetId,SelectorName);
DELETE FROM StylesheetSelectors WHERE StylesheetId = 8 AND SelectorName LIKE '.calendar%';
INSERT INTO StylesheetSelectors VALUES (169, 8, 'Calendar''s selected days', '.calendar tbody .selected', 'a:0:{}', '', 1, 'font-weight: bold;\r\nbackground-color: #9ED7ED;\r\nborder: 1px solid #83B2C5;', 0);
INSERT INTO StylesheetSelectors VALUES (170, 8, 'Calendar''s weekends', '.calendar .weekend', 'a:0:{}', '', 1, 'color: #990000;', 0);
INSERT INTO StylesheetSelectors VALUES (171, 8, 'Calendar''s highlighted day', '.calendar tbody .hilite', 'a:0:{}', '', 1, 'background-color: #f6f6f6;\r\nborder: 1px solid #83B2C5 !important;', 0);
INSERT INTO StylesheetSelectors VALUES (172, 8, 'Calendar''s top and bottom titles', '.calendar .title', 'a:0:{}', '', 1, 'color: #FFFFFF;\r\nbackground-color: #62A1DE;\r\nborder: 1px solid #107DC5;\r\nborder-top: 0px;\r\npadding: 1px;', 0);
INSERT INTO StylesheetSelectors VALUES (173, 8, 'Calendar''s control buttons', '.calendar .calendar_button', 'a:0:{}', '', 1, 'color: black;\r\nfont-size: 12px;\r\nbackground-color: #eeeeee;', 0);
INSERT INTO StylesheetSelectors VALUES (174, 8, 'Calendar''s day names', '.calendar thead .name', 'a:0:{}', '', 1, 'background-color: #DEEEF6;\r\nborder-bottom: 1px solid #000000;', 0);
INSERT INTO StylesheetSelectors VALUES (175, 8, 'Calendar''s days', '.calendar tbody .day', 'a:0:{}', '', 1, 'text-align: right;\r\npadding: 2px 4px 2px 2px;\r\nwidth: 2em;\r\nborder: 1px solid #fefefe;', 0);
ALTER TABLE UserGroup ADD MembershipExpires INT UNSIGNED DEFAULT NULL AFTER GroupId;
ALTER TABLE UserGroup ADD ExpirationReminderSent TINYINT DEFAULT '0' NOT NULL;
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('CATEGORY.VIEW', -1, 0, 0, 0);
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('CATEGORY.ADD', -1, 0, 0, 0);
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('CATEGORY.DELETE', -1, 0, 0, 0);
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('CATEGORY.ADD.PENDING', -1, 0, 0, 0);
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('CATEGORY.MODIFY', -1, 0, 0, 0);
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('FAVORITES', -1, 0, 0, 0);
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP_EXPIRED', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expired', '0');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP_EXPIRED', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expired', '1');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP_EXPIRATION_NOTICE', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expiration_notice', '0');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP_EXPIRATION_NOTICE', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expiration_notice', '1');
ALTER TABLE UserGroup ADD MembershipExpires INT UNSIGNED DEFAULT NULL AFTER GroupId;
+ALTER TABLE PersistantSessionData ADD PRIMARY KEY (PortalUserId, VariableName);
UPDATE Modules SET Version = '1.1.1' WHERE Name = 'In-Portal';
\ No newline at end of file
Property changes on: trunk/admin/install/upgrades/inportal_upgrade_v1.1.1.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/admin/install/inportal_schema.sql
===================================================================
--- trunk/admin/install/inportal_schema.sql (revision 2260)
+++ trunk/admin/install/inportal_schema.sql (revision 2261)
@@ -1,678 +1,678 @@
CREATE TABLE BanRules (
RuleId int(11) NOT NULL auto_increment,
RuleType tinyint(4) NOT NULL default '0',
ItemField varchar(255) default NULL,
ItemVerb tinyint(4) NOT NULL default '0',
ItemValue varchar(255) NOT NULL default '',
ItemType int(11) NOT NULL default '0',
Priority int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '1',
ErrorTag varchar(255) default NULL,
PRIMARY KEY (RuleId)
)
# --------------------------------------------------------
CREATE TABLE Category (
CategoryId int(11) NOT NULL auto_increment,
Type int(11) NOT NULL default '0',
ParentId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
Description text NOT NULL,
CreatedOn int(11) NOT NULL default '0',
EditorsPick tinyint(4) default NULL,
Status tinyint(4) NOT NULL default '0',
Pop tinyint(4) default NULL,
Priority int(11) NOT NULL default '0',
MetaKeywords varchar(255) default NULL,
CachedDescendantCatsQty int(11) default NULL,
CachedNavbar text NOT NULL,
CreatedById int(11) NOT NULL default '0',
ResourceId int(11) default NULL,
ParentPath text NOT NULL,
MetaDescription varchar(255) default NULL,
HotItem int(11) NOT NULL default '2',
NewItem int(11) NOT NULL default '2',
PopItem int(11) NOT NULL default '2',
Modified int(11) NOT NULL default '0',
ModifiedById int(11) NOT NULL default '0',
PRIMARY KEY (CategoryId),
KEY ParentId (ParentId),
UNIQUE KEY ResourceId (ResourceId),
KEY Modified (Modified),
KEY Priority (Priority),
KEY sorting (Name,Priority)
)
# --------------------------------------------------------
CREATE TABLE CategoryItems (
CategoryId int(11) NOT NULL default '0',
ItemResourceId int(11) NOT NULL default '0',
PrimaryCat tinyint(4) NOT NULL default '0',
KEY CategoryId (CategoryId),
KEY ItemResourceId (ItemResourceId),
KEY PrimaryCat (PrimaryCat)
)
# --------------------------------------------------------
CREATE TABLE ConfigurationAdmin (
VariableName varchar(80) NOT NULL default '',
heading varchar(255) default NULL,
prompt varchar(255) default NULL,
element_type varchar(20) NOT NULL default '',
validation varchar(255) default NULL,
ValueList text default NULL,
DisplayOrder int(11) NOT NULL default '0',
Install int(11) NOT NULL default '1',
PRIMARY KEY (VariableName)
)
# --------------------------------------------------------
CREATE TABLE ConfigurationValues (
VariableName varchar(255) NOT NULL default '',
VariableValue varchar(255) default NULL,
ModuleOwner varchar(20) default 'In-Portal',
Section varchar(255) NOT NULL default '',
PRIMARY KEY (VariableName)
)
# --------------------------------------------------------
CREATE TABLE CountCache (
ListType int(11) NOT NULL default '0',
ItemType int(11) NOT NULL default '-1',
Value int(11) NOT NULL default '0',
CountCacheId int(11) NOT NULL auto_increment,
LastUpdate int(11) NOT NULL default '0',
ExtraId varchar(50) default NULL,
TodayOnly tinyint(4) NOT NULL default '0',
PRIMARY KEY (CountCacheId)
)
# --------------------------------------------------------
CREATE TABLE CustomField (
CustomFieldId int(11) NOT NULL auto_increment,
Type int(11) NOT NULL default '0',
FieldName varchar(255) NOT NULL default '',
FieldLabel varchar(40) default NULL,
Heading varchar(60) default NULL,
Prompt varchar(60) default NULL,
ElementType varchar(50) NOT NULL default '',
ValueList varchar(255) default NULL,
DisplayOrder int(11) NOT NULL default '0',
OnGeneralTab tinyint(4) NOT NULL default '0',
PRIMARY KEY (CustomFieldId),
KEY Type (Type)
)
# --------------------------------------------------------
CREATE TABLE CustomMetaData (
CustomDataId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
CustomFieldId int(11) NOT NULL default '0',
Value text NOT NULL,
l1_Value text NOT NULL,
l2_Value text NOT NULL,
l3_Value text NOT NULL,
l4_Value text NOT NULL,
l5_Value text NOT NULL,
PRIMARY KEY (CustomDataId),
KEY ResourceId (ResourceId),
KEY CustomFieldId (CustomFieldId)
)
# --------------------------------------------------------
CREATE TABLE EmailMessage (
EmailMessageId int(10) NOT NULL auto_increment,
Template longtext,
MessageType enum('html','text') NOT NULL default 'text',
LanguageId int(11) NOT NULL default '0',
EventId int(11) NOT NULL default '0',
PRIMARY KEY (EmailMessageId)
)
# --------------------------------------------------------
CREATE TABLE EmailQueue (
Subject text NOT NULL,
toaddr text NOT NULL,
fromaddr text NOT NULL,
message blob,
headers blob,
queued timestamp NOT NULL
)
# --------------------------------------------------------
CREATE TABLE EmailSubscribers (
EmailMessageId int(11) NOT NULL default '0',
PortalUserId int(11) NOT NULL default '0'
)
# --------------------------------------------------------
CREATE TABLE Events (
EventId int(11) NOT NULL auto_increment,
Event varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
FromUserId int(11) NOT NULL default '0',
Module varchar(40) NOT NULL default '',
Description varchar(255) NOT NULL default '',
Type int(11) NOT NULL default '0',
PRIMARY KEY (EventId)
)
# --------------------------------------------------------
CREATE TABLE Favorites (
FavoriteId int(11) NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '0',
ResourceId int(11) NOT NULL default '0',
ItemTypeId int(11) NOT NULL default '0',
Modified int(11) NOT NULL default '0',
PRIMARY KEY (FavoriteId),
UNIQUE KEY main (PortalUserId,ResourceId)
)
# --------------------------------------------------------
CREATE TABLE IdGenerator (
lastid int(11) default NULL
)
# --------------------------------------------------------
CREATE TABLE Images (
ImageId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
Url varchar(255) NOT NULL default '',
Name varchar(255) NOT NULL default '',
AltName varchar(255) default NULL,
ImageIndex int(11) NOT NULL default '0',
LocalImage tinyint(4) NOT NULL default '1',
LocalPath varchar(240) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
DefaultImg int(11) NOT NULL default '0',
ThumbUrl varchar(255) default NULL,
Priority int(11) NOT NULL default '0',
ThumbPath varchar(255) default NULL,
LocalThumb tinyint(4) NOT NULL default '0',
SameImages tinyint(4) NOT NULL default '0',
PRIMARY KEY (ImageId),
KEY ResourceId (ResourceId)
)
# --------------------------------------------------------
CREATE TABLE ItemRating (
RatingId int(11) NOT NULL auto_increment,
IPAddress varchar(255) NOT NULL default '',
CreatedOn double NOT NULL default '0',
RatingValue int(11) NOT NULL default '0',
ItemId int(11) NOT NULL default '0',
PRIMARY KEY (RatingId)
)
# --------------------------------------------------------
CREATE TABLE ItemReview (
ReviewId int(11) NOT NULL auto_increment,
CreatedOn double NOT NULL default '0',
ReviewText longtext NOT NULL,
IPAddress varchar(255) NOT NULL default '',
ItemId int(11) NOT NULL default '0',
CreatedById int(11) NOT NULL default '0',
ItemType tinyint(4) NOT NULL default '0',
Priority int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '0',
TextFormat int(11) NOT NULL default '0',
Module varchar(255) NOT NULL default '',
PRIMARY KEY (ReviewId)
)
# --------------------------------------------------------
CREATE TABLE ItemTypes (
ItemType int(11) NOT NULL default '0',
Module varchar(50) NOT NULL default '',
SourceTable varchar(100) NOT NULL default '',
TitleField varchar(50) default NULL,
CreatorField varchar(255) NOT NULL default '',
PopField varchar(255) default NULL,
RateField varchar(255) default NULL,
LangVar varchar(255) NOT NULL default '',
PrimaryItem int(11) NOT NULL default '0',
EditUrl varchar(255) NOT NULL default '',
ClassName varchar(40) NOT NULL default '',
ItemName varchar(50) NOT NULL default '',
PRIMARY KEY (ItemType),
KEY Module (Module)
)
# --------------------------------------------------------
CREATE TABLE Language (
LanguageId int(11) NOT NULL auto_increment,
PackName varchar(40) NOT NULL default '',
LocalName varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '0',
PrimaryLang int(11) NOT NULL default '0',
IconURL varchar(255) default NULL,
DateFormat varchar(50) NOT NULL default '',
TimeFormat varchar(50) NOT NULL default '',
DecimalPoint char(2) NOT NULL default '.',
ThousandSep char(1) NOT NULL default ',',
Charset varchar(20) NOT NULL default '',
UnitSystem tinyint(4) NOT NULL default '1',
PRIMARY KEY (LanguageId)
)
# --------------------------------------------------------
CREATE TABLE Modules (
Name varchar(255) NOT NULL default '',
Path varchar(255) NOT NULL default '',
Var varchar(10) NOT NULL default '',
Version varchar(10) NOT NULL default '',
Loaded tinyint(4) NOT NULL default '1',
LoadOrder tinyint(4) NOT NULL default '0',
TemplatePath varchar(255) NOT NULL default '',
RootCat int(11) NOT NULL default '0',
BuildDate double NOT NULL default '0',
PRIMARY KEY (Name)
)
# --------------------------------------------------------
CREATE TABLE PermCache (
PermCacheId int(11) NOT NULL auto_increment,
CategoryId int(11) NOT NULL default '0',
PermId int(11) NOT NULL default '0',
ACL varchar(255) NOT NULL default '',
DACL varchar(255) NOT NULL default '',
PRIMARY KEY (PermCacheId),
KEY CategoryId (CategoryId),
KEY PermId (PermId)
)
# --------------------------------------------------------
CREATE TABLE PermissionConfig (
PermissionConfigId int(11) NOT NULL auto_increment,
PermissionName varchar(30) NOT NULL default '',
Description varchar(255) NOT NULL default '',
ErrorMessage varchar(255) NOT NULL default '',
ModuleId varchar(20) NOT NULL default '0',
PRIMARY KEY (PermissionConfigId),
KEY PermissionName (PermissionName)
)
# --------------------------------------------------------
CREATE TABLE Permissions (
PermissionId int(11) NOT NULL auto_increment,
Permission varchar(30) NOT NULL default '',
GroupId int(11) default '0',
PermissionValue int(11) NOT NULL default '0',
Type tinyint(4) NOT NULL default '0',
CatId int(11) NOT NULL default '0',
PRIMARY KEY (PermissionId)
)
# --------------------------------------------------------
CREATE TABLE PersistantSessionData (
PortalUserId int(11) NOT NULL default '0',
VariableName varchar(255) NOT NULL default '',
VariableValue text NOT NULL,
+ PRIMARY KEY (PortalUserId,VariableName),
KEY UserId (PortalUserId),
KEY VariableName (VariableName)
)
-
# --------------------------------------------------------
CREATE TABLE Phrase (
Phrase varchar(255) NOT NULL default '',
Translation varchar(255) NOT NULL default '',
PhraseType int(11) NOT NULL default '0',
PhraseId int(11) NOT NULL auto_increment,
LanguageId int(11) NOT NULL default '0',
LastChanged int(10) unsigned NOT NULL default '0',
LastChangeIP varchar(15) NOT NULL default '',
Module varchar(30) NOT NULL default '',
PRIMARY KEY (PhraseId),
KEY LanguageId (LanguageId),
INDEX Phrase_Index (Phrase)
)
# --------------------------------------------------------
CREATE TABLE PhraseCache (
Template varchar(40) NOT NULL default '',
PhraseList text NOT NULL,
CacheDate int(11) NOT NULL default '0',
ThemeId int(11) NOT NULL default '0',
StylesheetId int(10) unsigned NOT NULL default '0',
PRIMARY KEY (Template)
)
# --------------------------------------------------------
CREATE TABLE PortalGroup (
GroupId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Description varchar(255) default NULL,
CreatedOn double NOT NULL default '0',
System tinyint(4) NOT NULL default '0',
Personal tinyint(4) NOT NULL default '0',
Enabled tinyint(4) NOT NULL default '1',
ResourceId int(11) NOT NULL default '0',
PRIMARY KEY (GroupId),
UNIQUE KEY Name (Name),
UNIQUE KEY ResourceId (ResourceId),
KEY Personal (Personal),
KEY Enabled (Enabled)
)
# --------------------------------------------------------
CREATE TABLE PortalUser (
PortalUserId int(11) NOT NULL auto_increment,
Login varchar(255) default NULL,
Password varchar(255) default NULL,
FirstName varchar(255) default NULL,
LastName varchar(255) default NULL,
Email varchar(255) NOT NULL default '',
CreatedOn double NOT NULL default '0',
Phone varchar(20) default NULL,
Street varchar(255) default NULL,
City varchar(20) default NULL,
State VARCHAR(20) NOT NULL,
Zip varchar(20) default NULL,
Country varchar(20) NOT NULL default '',
ResourceId int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '2',
Modified int(11) NOT NULL default '0',
dob double NOT NULL default '0',
tz int(11) default NULL,
ip varchar(20) default NULL,
IsBanned tinyint(1) NOT NULL default '0',
PassResetTime bigint(20),
PwResetConfirm varchar(255),
PwRequestTime bigint(25),
MinPwResetDelay int(11) NOT NULL default '1800',
PRIMARY KEY (PortalUserId),
UNIQUE KEY Login (Login),
UNIQUE KEY ResourceId (ResourceId),
KEY CreatedOn (CreatedOn)
)
# --------------------------------------------------------
CREATE TABLE Relationship (
RelationshipId int(11) NOT NULL auto_increment,
SourceId int(11) default NULL,
TargetId int(11) default NULL,
SourceType tinyint(4) NOT NULL default '0',
TargetType tinyint(4) NOT NULL default '0',
Type int(11) NOT NULL default '0',
Enabled int(11) NOT NULL default '1',
Priority int(11) NOT NULL default '0',
PRIMARY KEY (RelationshipId),
KEY RelSource (SourceId),
KEY RelTarget (TargetId)
)
# --------------------------------------------------------
CREATE TABLE SearchConfig (
TableName varchar(40) NOT NULL default '',
FieldName varchar(40) NOT NULL default '',
SimpleSearch tinyint(4) NOT NULL default '0',
AdvancedSearch tinyint(4) NOT NULL default '0',
Description varchar(255) default NULL,
DisplayName varchar(80) default NULL,
ModuleName varchar(20) default NULL,
ConfigHeader varchar(255) default NULL,
DisplayOrder int(11) NOT NULL default '0',
SearchConfigId int(11) NOT NULL auto_increment,
Priority int(11) NOT NULL default '0',
FieldType varchar(20) NOT NULL default 'text',
ForeignField TEXT,
JoinClause TEXT,
IsWhere text,
IsNotWhere text,
ContainsWhere text,
NotContainsWhere text,
CustomFieldId int(11) NOT NULL default '0',
PRIMARY KEY (SearchConfigId)
)
# --------------------------------------------------------
CREATE TABLE SearchLog (
SearchLogId int(11) NOT NULL auto_increment,
Keyword varchar(255) NOT NULL default '',
Indices bigint(20) NOT NULL default '0',
SearchType int(11) NOT NULL default '0',
PRIMARY KEY (SearchLogId)
)
# --------------------------------------------------------
CREATE TABLE SessionData (
SessionKey varchar(50) NOT NULL default '',
VariableName varchar(255) NOT NULL default '',
VariableValue text NOT NULL,
PRIMARY KEY (SessionKey,VariableName),
KEY SessionKey (SessionKey),
KEY VariableName (VariableName)
)
# --------------------------------------------------------
CREATE TABLE SpamControl (
ItemResourceId int(11) NOT NULL default '0',
IPaddress varchar(20) NOT NULL default '',
Expire double NOT NULL default '0',
PortalUserId int(11) NOT NULL default '0',
DataType varchar(20) default NULL
)
# --------------------------------------------------------
CREATE TABLE StatItem (
StatItemId int(11) NOT NULL auto_increment,
Module varchar(20) NOT NULL default '',
ValueSQL varchar(255) default NULL,
ResetSQL varchar(255) default NULL,
ListLabel varchar(255) NOT NULL default '',
Priority int(11) NOT NULL default '0',
AdminSummary int(11) NOT NULL default '0',
PRIMARY KEY (StatItemId)
)
# --------------------------------------------------------
CREATE TABLE Theme (
ThemeId int(11) NOT NULL auto_increment,
Name varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
Description varchar(255) default NULL,
PrimaryTheme int(11) NOT NULL default '0',
CacheTimeout int(11) NOT NULL default '0',
StylesheetId INTEGER(10) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (ThemeId)
)
# --------------------------------------------------------
CREATE TABLE ThemeFiles (
FileId int(11) NOT NULL auto_increment,
ThemeId int(11) NOT NULL default '0',
FileName varchar(255) NOT NULL default '',
FilePath varchar(255) NOT NULL default '',
Description varchar(255) default NULL,
FileType int(11) NOT NULL default '0',
PRIMARY KEY (FileId),
KEY theme (ThemeId)
)
# --------------------------------------------------------
CREATE TABLE UserGroup (
PortalUserId int(11) NOT NULL default '0',
GroupId int(11) NOT NULL default '0',
MembershipExpires int(10) unsigned default NULL,
PrimaryGroup tinyint(4) NOT NULL default '1',
ExpirationReminderSent tinyint(4) NOT NULL default '0',
PRIMARY KEY (PortalUserId,GroupId),
KEY GroupId (GroupId),
KEY PrimaryGroup (PrimaryGroup)
)
# --------------------------------------------------------
CREATE TABLE UserSession (
SessionKey varchar(50) NOT NULL default '',
CurrentTempKey varchar(50) default NULL,
PrevTempKey varchar(50) default NULL,
LastAccessed double NOT NULL default '0',
PortalUserId varchar(255) NOT NULL default '',
Language varchar(255) NOT NULL default '',
Theme varchar(255) NOT NULL default '',
GroupId int(11) NOT NULL default '0',
IpAddress varchar(20) NOT NULL default '0.0.0.0',
Status int(11) NOT NULL default '1',
GroupList varchar(255) default NULL,
tz int(11) default NULL,
PRIMARY KEY (SessionKey),
KEY UserId (PortalUserId),
KEY LastAccessed (LastAccessed)
)
# --------------------------------------------------------
CREATE TABLE SuggestMail (
email varchar(255) NOT NULL default '',
sent double,
PRIMARY KEY (email)
)
# --------------------------------------------------------
CREATE TABLE SysCache (
SysCacheId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Value mediumtext,
Expire double NOT NULL default '0',
Module varchar(20) default NULL,
Context varchar(255) default NULL,
GroupList varchar(255) NOT NULL default '',
PRIMARY KEY (SysCacheId),
KEY Name (Name)
)
# --------------------------------------------------------
CREATE TABLE TagLibrary (
TagId int(11) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
description text,
example text,
scope varchar(20) NOT NULL default 'global',
PRIMARY KEY (TagId)
)
# --------------------------------------------------------
CREATE TABLE TagAttributes (
AttrId int(11) NOT NULL auto_increment,
TagId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
AttrType varchar(20) default NULL,
DefValue varchar(255) default NULL,
Description TEXT,
Required int(11) NOT NULL default '0',
PRIMARY KEY (AttrId)
)
# --------------------------------------------------------
CREATE TABLE EmailLog (
EmailLogId int(11) NOT NULL auto_increment,
fromuser varchar(200) default NULL,
addressto varchar(255) default NULL,
subject varchar(255) default NULL,
timestamp bigint(20) default '0',
event varchar(100) default NULL,
PRIMARY KEY (EmailLogId)
)
# --------------------------------------------------------
CREATE TABLE ImportScripts (
is_id smallint(5) unsigned NOT NULL auto_increment,
is_Module varchar(50) NOT NULL default '',
is_string_id varchar(10) NOT NULL default '',
is_script varchar(100) NOT NULL default '',
is_label varchar(255) NOT NULL default '',
is_field_prefix varchar(50) NOT NULL default '',
is_requred_fields varchar(255) NOT NULL default '',
is_enabled tinyint(1) unsigned NOT NULL default '0',
PRIMARY KEY (is_id)
)
# --------------------------------------------------------
CREATE TABLE Cache (
VarName varchar(255) NOT NULL default '',
Data longtext,
Cached int(11) default NULL,
PRIMARY KEY (VarName),
KEY Cached (Cached)
)
# --------------------------------------------------------
CREATE TABLE StylesheetSelectors (
SelectorId int(11) NOT NULL auto_increment,
StylesheetId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
SelectorName varchar(255) NOT NULL default '',
SelectorData text NOT NULL,
Description text NOT NULL,
Type tinyint(4) NOT NULL default '0',
AdvancedCSS text NOT NULL,
ParentId int(11) NOT NULL default '0',
PRIMARY KEY (SelectorId),
UNIQUE KEY UniqueIdName (StylesheetId,SelectorName)
)
# --------------------------------------------------------
CREATE TABLE Stylesheets (
StylesheetId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Description varchar(255) NOT NULL default '',
AdvancedCSS text NOT NULL,
LastCompiled int(10) unsigned NOT NULL default '0',
Enabled int(11) NOT NULL default '0',
PRIMARY KEY (StylesheetId)
)
# --------------------------------------------------------
CREATE TABLE StdDestinations (
DestId int(11) NOT NULL auto_increment,
DestType int(11) NOT NULL default '0',
DestParentId int(11) default NULL,
DestName varchar(255) NOT NULL default '',
DestAbbr char(3) NOT NULL default '',
DestAbbr2 char(2) default '',
PRIMARY KEY (DestId)
)
# --------------------------------------------------------
\ No newline at end of file
Property changes on: trunk/admin/install/inportal_schema.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.24
\ No newline at end of property
+1.25
\ No newline at end of property
Index: trunk/core/kernel/utility/utilities.php
===================================================================
--- trunk/core/kernel/utility/utilities.php (revision 2260)
+++ trunk/core/kernel/utility/utilities.php (nonexistent)
@@ -1,41 +0,0 @@
-<?php
-
- // OLD STUFF
-
-class Utilites extends kBase {
-
- function ExtractByMask($array, $mask, $key_id=1, $ret_mode=1)
- {
-// echo "extracting from <br>";
-// print_pre($array);
- $rets = Array();
- foreach ($array as $name => $val)
- {
- $regs = Array();
-// echo "checking $name<br>";
- if (eregi($mask, $name, $regs)) {
-// echo "matched<br>";
-// print_pre($regs);
- if ($ret_mode == 1) {
- $rets[$regs[$key_id]] = $val;
- }
- else {
- array_push($regs, $val);
- $a_key = $regs[$key_id];
- $i = 0;
- while (array_key_exists($a_key, $rets)) {
- $a_key.=$i;
- $i++;
- }
- $rets[$a_key] = $regs;
- }
- }
- }
-// echo "returning ";
-// print_pre($rets);
- return $rets;
- }
-
-}
-
-?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/utilities.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.4
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/core/kernel/utility/iterator.php
===================================================================
--- trunk/core/kernel/utility/iterator.php (revision 2260)
+++ trunk/core/kernel/utility/iterator.php (nonexistent)
@@ -1,51 +0,0 @@
-<?php
-
- // OLD STUFF
-
-class MyIterator {
-
- var $Items;
- var $Index;
- var $Count;
- var $CurrentIndex;
-
- function MyIterator(&$items)
- {
- $this->Items =& $items;
- $this->IndexItems();
- $this->CurrentIndex = 0;
- }
-
- function IndexItems()
- {
- $i = 0;
- foreach ($this->Items as $key => $item) {
- $this->Index[$i] = $key; // ?????? $i++
- $i++;
- }
- $this->Count = $i;
- }
-
- function HasMore()
- {
- return $this->CurrentIndex < $this->Count;
- }
-
- function GoNext()
- {
- $this->CurrentIndex++;
- }
-
- function &GetItem()
- {
- return $this->Items[$this->Index[$this->CurrentIndex]];
- }
-
- function GetKey()
- {
- return $this->Index[$this->CurrentIndex];
- }
-
-}
-
-?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/iterator.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.4
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/core/kernel/utility/configuration.php
===================================================================
--- trunk/core/kernel/utility/configuration.php (revision 2260)
+++ trunk/core/kernel/utility/configuration.php (nonexistent)
@@ -1,87 +0,0 @@
-<?php
-
-
-// need to be rewrited
-
-class ConfigItem extends kDBItem
-{
- var $Application;
-
- function ConfigItem($Id)
- {
- $this->Application =& KernelApplication::Instance();
- $this->id_field = 'name';
- $this->table_name = 'config';
- $this->CreateField('name','',1,1);
- $this->CreateField('value','',1,1);
- $this->CreateField('config_description','', 0, 0);
- $this->DisplayErrors = 0;
- $this->DisplayQueries = 0;
- parent::DBItem($Id);
- }
-
- function Update()
- {
- $ret = parent::Update();
- // echo " update ".$this->GetDBField('name')."<br>";
- if ( $ret AND ereg("(per_page)",$this->GetDBField('name'))) {
- $this->Application->StoreVar(
- $this->GetDBField('name'),
- $this->GetDBField('value')
- );
- }
- return $ret;
- }
-}
-
-class ConfigList extends kDBList
-{
- function ConfigList($sql, $query_now=0, $owner=null)
- {
- parent::kDBList($sql, $query_now, $owner);
- $this->Special = $owner->Params['special'];
- switch ($this->Special)
- {
- default:
- $this->sql = " SELECT * FROM config ";
- };
- $this->DisplayQueries = 0;
- }
-
- function &NewItem ()
- {
- $new_item = new ConfigItem(NULL);
- return $new_item;
- }
-
- function GetOption($name)
- {
- if ($this->Find('name', $name))
- return $this->GetCurrentFieldValue('value');
- else
- return false;
- }
-
- function SetOption($name, $value)
- {
- if ($this->Find('name', $name)) {;
- $this->SetCurrentFieldValue('value', $value);
- $tmp =& $this->GetCurrentRec();
- $tmp->Update();
- }
- else {
- $push_hash = Array('name'=>$name, 'value'=>$value);
- $id = array_push($this->Records, $push_hash);
- if (count($this->IndexFields) > 0) {
- foreach ($this->IndexFields as $key) {
- if (is_string($push_hash[$key])) $store_key = strtolower($push_hash[$key]);
- else $store_key = $push_hash[$key];
- $this->Indexes[$key][$store_key] = $id-1;
- }
- }
- $this->last_rec++;
- }
- }
-}
-
-?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/configuration.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.3
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/core/kernel/utility/temp_handler.php
===================================================================
--- trunk/core/kernel/utility/temp_handler.php (revision 2260)
+++ trunk/core/kernel/utility/temp_handler.php (revision 2261)
@@ -1,581 +1,581 @@
<?php
class kTempTablesHandler extends kBase {
var $Tables = Array();
/**
* Master table name for temp handler
*
* @var string
* @access private
*/
var $MasterTable = '';
/**
* IDs from master table
*
* @var Array
* @access private
*/
var $MasterIDs = Array();
var $AlreadyProcessed = Array();
/**
* Description
*
- * @var DBConnection
+ * @var kDBConnection
* @access public
*/
var $Conn;
function kTempTablesHandler()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
function SetTables($tables)
{
// set tablename as key for tables array
$ret = Array();
$this->Tables = $tables;
$this->MasterTable = $tables['TableName'];
}
/**
* Get temp table name
*
* @param string $table
* @return string
*/
function GetTempName($table)
{
// function is sometimes called as static, so we CAN'T use $this->GetTempTablePrefix() here
return TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_edit_'.$table;
}
function GetTempTablePrefix()
{
return TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_edit_';
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
if( preg_match('/'.TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_edit_(.*)/',$temp_table,$rets) )
{
return $rets[1];
}
else
{
return $temp_table;
}
}
function IsTempTable($table)
{
return strpos($table, TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_edit_') !== false;
}
/**
* Return temporary table name for master table
*
* @return string
* @access public
*/
function GetMasterTempName()
{
return $this->GetTempName($this->MasterTable);
}
function CreateTempTable($table)
{
$query = sprintf("CREATE TABLE %s SELECT * FROM %s WHERE 0",
$this->GetTempName($table),
$table);
$this->Conn->Query($query);
}
function BuildTables($prefix, $ids)
{
$tables = Array(
'TableName' => $this->Application->getUnitOption($prefix,'TableName'),
'IdField' => $this->Application->getUnitOption($prefix,'IDField'),
'IDs' => $ids,
'Prefix' => $prefix,
);
$SubItems = $this->Application->getUnitOption($prefix,'SubItems');
if (is_array($SubItems)) {
foreach ($SubItems as $prefix) {
$this->AddTables($prefix, $tables);
}
}
$this->SetTables($tables);
}
function AddTables($prefix, &$tables)
{
$tmp = Array(
'TableName' => $this->Application->getUnitOption($prefix,'TableName'),
'IdField' => $this->Application->getUnitOption($prefix,'IDField'),
'ForeignKey' => $this->Application->getUnitOption($prefix,'ForeignKey'),
'ParentTableKey' => $this->Application->getUnitOption($prefix,'ParentTableKey'),
'Prefix' => $prefix,
'AutoClone' => $this->Application->getUnitOption($prefix,'AutoClone'),
'AutoDelete' => $this->Application->getUnitOption($prefix,'AutoDelete'),
);
$constrain = $this->Application->getUnitOption($prefix,'Constrain');
if ($constrain) $tmp['Constrain'] = $constrain;
$SubItems = $this->Application->getUnitOption($prefix,'SubItems');
$same_sub_counter = 1;
if (is_array($SubItems)) {
foreach ($SubItems as $prefix) {
if (preg_match("/^SAME:(.*)/", $prefix, $regs)) {
$same_sub = $tmp;
$same_sub['Prefix'] = $tmp['Prefix'].'.'.$same_sub_counter;
$same_sub['Constrain'] = $regs[1];
$same_sub['ParentTableKey'] = $tmp['IdField'];
$same_sub['ForeignKey'] = $this->Application->getUnitOption($tmp['Prefix'],'ForeignKey'.$same_sub_counter);
$tmp['SubTables'][] = $same_sub;
$same_sub_counter++;
}
else {
$this->AddTables($prefix, $tmp);
}
}
}
if ( !is_array(getArrayValue($tables, 'SubTables')) ) {
$tables['SubTables'] = array();
}
$tables['SubTables'][] = $tmp;
}
function CloneItems($prefix, $special, $ids, $master=null, $foreign_key=null, $parent_prefix=null)
{
if (!isset($master)) $master = $this->Tables;
if( strpos($prefix,'.') !== false ) list($prefix,$special) = explode('.', $prefix, 2);
$prefix_special = rtrim($prefix.'.'.$special, '.');
//recalling by different name, because we may get kDBList, if we recall just by prefix
$recall_prefix = $prefix_special.($special ? '' : '.').'-item';
$this->Application->setUnitOption($prefix, 'AutoLoad', false);
$object =& $this->Application->recallObject($recall_prefix, $prefix);
foreach ($ids as $id)
{
$mode = 'create';
if ( $cloned_ids = getArrayValue($this->AlreadyProcessed, $master['TableName']) ) {
// if we have already cloned the id, replace it with cloned id and set mode to update
// update mode is needed to update second ForeignKey for items cloned by first ForeignKey
if ( getArrayValue($cloned_ids, $id) ) {
$id = $cloned_ids[$id];
$mode = 'update';
}
}
$object->Load($id);
$original_values = $object->FieldValues;
$object->NameCopy($master, $foreign_key);
if (isset($foreign_key)) {
$master_foreign_key_field = is_array($master['ForeignKey']) ? $master['ForeignKey'][$parent_prefix] : $master['ForeignKey'];
$object->SetDBField($master_foreign_key_field, $foreign_key);
}
if ($mode == 'create') {
$this->RaiseEvent('OnBeforeClone', $master['Prefix'], Array($object->GetId()) );
}
$res = $mode == 'update' ? $object->Update() : $object->Create();
if( $res )
{
if ( $mode == 'create' && is_array( getArrayValue($master, 'ForeignKey')) ) {
// remember original => clone mapping for dual ForeignKey updating
$this->AlreadyProcessed[$master['TableName']][$id] = $object->GetId();
}
if($object->mode == 't') $object->setTempID();
if ($mode == 'create') {
$this->RaiseEvent('OnAfterClone', $master['Prefix'], Array($object->GetId()) );
}
if ( is_array(getArrayValue($master, 'SubTables')) ) {
foreach($master['SubTables'] as $sub_table) {
if (!getArrayValue($sub_table, 'AutoClone')) continue;
$sub_TableName = ($object->mode == 't') ? $this->GetTempName($sub_table['TableName']) : $sub_table['TableName'];
$foreign_key_field = is_array($sub_table['ForeignKey']) ? $sub_table['ForeignKey'][$master['Prefix']] : $sub_table['ForeignKey'];
$parent_key_field = is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$master['Prefix']] : $sub_table['ParentTableKey'];
$query = 'SELECT '.$sub_table['IdField'].' FROM '.$sub_TableName.'
WHERE '.$foreign_key_field.' = '.$original_values[$parent_key_field];
$sub_ids = $this->Conn->GetCol($query);
if ( is_array(getArrayValue($sub_table, 'ForeignKey')) ) {
// $sub_ids could containt newly cloned items, we need to remove it here
// to escape double cloning
$cloned_ids = getArrayValue($this->AlreadyProcessed, $sub_table['TableName']);
if ( !$cloned_ids ) $cloned_ids = Array();
$new_ids = array_values($cloned_ids);
$sub_ids = array_diff($sub_ids, $new_ids);
}
$parent_key = $object->GetDBField($parent_key_field);
$this->CloneItems($sub_table['Prefix'], '', $sub_ids, $sub_table, $parent_key, $master['Prefix']);
}
}
}
}
}
function DeleteItems($prefix, $special, $ids, $master=null, $foreign_key=null)
{
if (!isset($master)) $master = $this->Tables;
if( strpos($prefix,'.') !== false ) list($prefix,$special) = explode('.', $prefix, 2);
$prefix_special = rtrim($prefix.'.'.$special, '.');
//recalling by different name, because we may get kDBList, if we recall just by prefix
$recall_prefix = $prefix_special.($special ? '' : '.').'-item';
$this->Application->setUnitOption($prefix,'AutoLoad',false);
$object =& $this->Application->recallObject($recall_prefix, $prefix);
foreach ($ids as $id)
{
$object->Load($id);
$original_values = $object->FieldValues;
$object->Delete($id);
if ( is_array(getArrayValue($master, 'SubTables')) ) {
foreach($master['SubTables'] as $sub_table) {
if (!getArrayValue($sub_table, 'AutoDelete')) continue;
$sub_TableName = ($object->mode == 't') ? $this->GetTempName($sub_table['TableName']) : $sub_table['TableName'];
$foreign_key_field = is_array($sub_table['ForeignKey']) ? $sub_table['ForeignKey'][$master['Prefix']] : $sub_table['ForeignKey'];
$parent_key_field = is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$master['Prefix']] : $sub_table['ParentTableKey'];
$query = 'SELECT '.$sub_table['IdField'].' FROM '.$sub_TableName.'
WHERE '.$foreign_key_field.' = '.$original_values[$parent_key_field];
$sub_ids = $this->Conn->GetCol($query);
$parent_key = $object->GetDBField($sub_table['ParentTableKey']);
$this->DeleteItems($sub_table['Prefix'], '', $sub_ids, $sub_table, $parent_key);
}
}
}
}
function DoCopyLiveToTemp($master, $ids, $parent_prefix=null)
{
// when two tables refers the same table as sub-sub-table, and ForeignKey and ParentTableKey are arrays
// the table will be first copied by first sub-table, then dropped and copied over by last ForeignKey in the array
// this should not do any problems :)
if ( !preg_match("/.*\.[0-9]+/", $master['Prefix']) ) {
$this->DropTempTable($master['TableName']);
$this->CreateTempTable($master['TableName']);
}
if (is_array($ids)) {
$ids = join(',', $ids);
}
if ($ids != '') {
if ( getArrayValue($master, 'ForeignKey') ) {
if ( is_array($master['ForeignKey']) ) {
$key_field = $master['ForeignKey'][$parent_prefix];
}
else {
$key_field = $master['ForeignKey'];
}
}
else {
$key_field = $master['IdField'];
}
$query = 'INSERT INTO '.$this->GetTempName($master['TableName']).'
SELECT * FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain'];
$this->Conn->Query($query);
$query = 'SELECT '.$master['IdField'].' FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain'];
$this->RaiseEvent( 'OnAfterCopyToTemp', $master['Prefix'], $this->Conn->GetCol($query) );
}
if ( getArrayValue($master, 'SubTables') ) {
foreach ($master['SubTables'] as $sub_table) {
$parent_key = is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$master['Prefix']] : $sub_table['ParentTableKey'];
if ( $ids != '' && $parent_key != $key_field ) {
$query = 'SELECT '.$parent_key.' FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
$sub_foreign_keys = join(',', $this->Conn->GetCol($query));
}
else {
$sub_foreign_keys = $ids;
}
$this->DoCopyLiveToTemp($sub_table, $sub_foreign_keys, $master['Prefix']);
}
}
}
function GetForeignKeys($master, $sub_table, $live_id, $temp_id=null)
{
$mode = 1; //multi
if (!is_array($live_id)) {
$live_id = Array($live_id);
$mode = 2; //single
}
if (isset($temp_id) && !is_array($temp_id)) $temp_id = Array($temp_id);
if ( isset($sub_table['ParentTableKey']) ) {
if ( is_array($sub_table['ParentTableKey']) ) {
$parent_key_field = $sub_table['ParentTableKey'][$master['Prefix']];
}
else {
$parent_key_field = $sub_table['ParentTableKey'];
}
}
else {
$parent_key_field = $master['IdField'];
}
if ( $cached = getArrayValue($this->FKeysCache, $master['TableName'].'.'.$parent_key_field) ) {
if ( array_key_exists(serialize($live_id), $cached) ) {
list($live_foreign_key, $temp_foreign_key) = $cached[serialize($live_id)];
if ($mode == 1) {
return $live_foreign_key;
}
else {
return Array($live_foreign_key[0], $temp_foreign_key[0]);
}
}
}
if ($parent_key_field != $master['IdField']) {
$query = 'SELECT '.$parent_key_field.' FROM '.$master['TableName'].'
WHERE '.$master['IdField'].' IN ('.join(',', $live_id).')';
$live_foreign_key = $this->Conn->GetCol($query);
if (isset($temp_id)) {
$query = 'SELECT '.$parent_key_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$master['IdField'].' IN ('.join(',', $temp_id).')';
$temp_foreign_key = $this->Conn->GetCol($query);
}
else {
$temp_foreign_key = Array();
}
}
else {
$live_foreign_key = $live_id;
$temp_foreign_key = $temp_id;
}
$this->FKeysCache[$master['TableName'].'.'.$parent_key_field][serialize($live_id)] = Array($live_foreign_key, $temp_foreign_key);
if ($mode == 1) {
return $live_foreign_key;
}
else {
return Array($live_foreign_key[0], $temp_foreign_key[0]);
}
}
function DoCopyTempToOriginal($master, $parent_prefix=null)
{
$query = 'SELECT '.$master['IdField'].' FROM '.$this->GetTempName($master['TableName']);
if (isset($master['Constrain'])) $query .= ' WHERE '.$master['Constrain'];
$current_ids = $this->Conn->GetCol($query);
if ($current_ids) {
// delete all ids from live table - for MasterTable ONLY!
// because items from Sub Tables get deteleted in CopySubTablesToLive !BY ForeignKey!
if ($master['TableName'] == $this->MasterTable) {
$this->RaiseEvent( 'OnBeforeDeleteFromLive', $master['Prefix'], $current_ids );
$query = 'DELETE FROM '.$master['TableName'].' WHERE '.$master['IdField'].' IN ('.join(',', $current_ids).')';
$this->Conn->Query($query);
}
if ( getArrayValue($master, 'SubTables') ) {
foreach ($current_ids AS $id) {
$this->RaiseEvent( 'OnBeforeCopyToLive', $master['Prefix'], Array($id) );
//reset negative ids to 0, so autoincrement in live table works fine
if ($id < 0) {
$query = 'UPDATE '.$this->GetTempName($master['TableName']).'
SET '.$master['IdField'].' = 0
WHERE '.$master['IdField'].' = '.$id;
$this->Conn->Query($query);
$id_to_copy = 0;
}
else {
$id_to_copy = $id;
}
//copy current id_to_copy (0 for new or real id) to live table
$query = 'INSERT INTO '.$master['TableName'].'
SELECT * FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$master['IdField'].' = '.$id_to_copy;
$this->Conn->Query($query);
$insert_id = $id_to_copy == 0 ? $this->Conn->getInsertID() : $id_to_copy;
$this->RaiseEvent( 'OnAfterCopyToLive', $master['Prefix'], Array($insert_id) );
$this->UpdateForeignKeys($master, $insert_id, $id);
//delete already copied record from master temp table
$query = 'DELETE FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$master['IdField'].' = '.$id_to_copy;
$this->Conn->Query($query);
}
// when all of ids in current master has been processed, copy all sub-tables data
$this->CopySubTablesToLive($master, $current_ids);
}
else { //If current master doesn't have sub-tables - we could use mass operations
// We don't need to delete items from live here, as it get deleted in the beggining of the method for MasterTable
// or in parent table processing for sub-tables
$this->RaiseEvent('OnBeforeCopyToLive', $master['Prefix'], $current_ids);
// reset ALL negative IDs to 0 so it get inserted into live table with autoincrement
$query = 'UPDATE '.$this->GetTempName($master['TableName']).'
SET '.$master['IdField'].' = 0
WHERE '.$master['IdField'].' < 0';
if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain'];
$this->Conn->Query($query);
// copy ALL records to live table
$query = 'INSERT INTO '.$master['TableName'].'
SELECT * FROM '.$this->GetTempName($master['TableName']);
if (isset($master['Constrain'])) $query .= ' WHERE '.$master['Constrain'];
$this->Conn->Query($query);
/*
!!! WE NEED TO FIND A WAY TO DETERMINE IF OnAfterCopyToLive is not an empty method, and do on-by-one insert
and pass Ids to OnAfterCopyToLive, otherwise it's not smart to do on-by-one insert for any object
OR WE COULD FIND A WAY TO GET ALL INSERTED IDS as an array and iterate them !!!
$this->RaiseEvent('OnAfterCopyToLive', IDS ??? );
*/
// no need to clear temp table - it will be dropped by next statement
}
}
if ( is_array(getArrayValue($master, 'ForeignKey')) ) { //if multiple ForeignKeys
if ( $master['ForeignKey'][$parent_prefix] != end($master['ForeignKey']) ) {
return; // Do not delete temp table if not all ForeignKeys have been processed (current is not the last)
}
}
$this->DropTempTable($master['TableName']);
}
function UpdateForeignKeys($master, $live_id, $temp_id) {
foreach ($master['SubTables'] as $sub_table) {
list ($live_foreign_key, $temp_foreign_key) = $this->GetForeignKeys($master, $sub_table, $live_id, $temp_id);
$foreign_key_field = is_array($sub_table['ForeignKey']) ? $sub_table['ForeignKey'][$master['Prefix']] : $sub_table['ForeignKey'];
//Update ForeignKey in sub TEMP table
if ($live_foreign_key != $temp_foreign_key) {
$query = 'UPDATE '.$this->GetTempName($sub_table['TableName']).'
SET '.$foreign_key_field.' = '.$live_foreign_key.'
WHERE '.$foreign_key_field.' = '.$temp_foreign_key;
$this->Conn->Query($query);
}
}
}
function CopySubTablesToLive($master, $current_ids) {
foreach ($master['SubTables'] as $sub_table) {
// delete records from live table by foreign key, so that records deleted from temp table
// get deleted from live
if (count($current_ids) > 0) {
$foreign_keys = $this->GetForeignKeys($master, $sub_table, $current_ids);
$foreign_key_field = is_array($sub_table['ForeignKey']) ? $sub_table['ForeignKey'][$master['Prefix']] : $sub_table['ForeignKey'];
if (count($foreign_keys) > 0) {
$query = 'SELECT '.$sub_table['IdField'].' FROM '.$sub_table['TableName'].'
WHERE '.$foreign_key_field.' IN ('.join(',', $foreign_keys).')';
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
$this->RaiseEvent( 'OnBeforeDeleteFromLive', $sub_table['Prefix'], $this->Conn->GetCol($query) );
$query = 'DELETE FROM '.$sub_table['TableName'].'
WHERE '.$foreign_key_field.' IN ('.join(',', $foreign_keys).')';
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
$this->Conn->Query($query);
}
}
//sub_table passed here becomes master in the method, and recursively updated and copy its sub tables
$this->DoCopyTempToOriginal($sub_table, $master['Prefix']);
}
}
function RaiseEvent($name, $prefix, $ids)
{
if ( !is_array($ids) ) return;
foreach ($ids as $id) {
$event = new kEvent( Array('name'=>$name, 'prefix'=>$prefix, 'special'=>'') );
$event->setEventParam('id', $id);
$this->Application->HandleEvent($event);
}
}
function DropTempTable($table)
{
$query = sprintf("DROP TABLE IF EXISTS %s",
$this->GetTempName($table)
);
$this->Conn->Query($query);
}
function PrepareEdit()
{
$this->DoCopyLiveToTemp($this->Tables, $this->Tables['IDs']);
}
function SaveEdit($skip_master=0)
{
$this->DoCopyTempToOriginal($this->Tables);
}
function CancelEdit($master=null)
{
if (!isset($master)) $master = $this->Tables;
$this->DropTempTable($master['TableName']);
if ( getArrayValue($master, 'SubTables') ) {
foreach ($master['SubTables'] as $sub_table) {
$this->CancelEdit($sub_table);
}
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/temp_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.5
\ No newline at end of property
Index: trunk/core/kernel/db/db_tag_processor.php
===================================================================
--- trunk/core/kernel/db/db_tag_processor.php (revision 2260)
+++ trunk/core/kernel/db/db_tag_processor.php (revision 2261)
@@ -1,1228 +1,1228 @@
<?php
class kDBTagProcessor extends TagProcessor {
/**
* Description
*
- * @var DBConnection
+ * @var kDBConnection
* @access public
*/
var $Conn;
function kDBTagProcessor()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
function IsNew($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params );
return $object->GetID();
}
/**
* Returns view menu name for current prefix
*
* @param Array $params
* @return string
*/
function GetItemName($params)
{
$item_name = $this->Application->getUnitOption($this->Prefix,'ViewMenuPhrase');
return $this->Application->Phrase($item_name);
}
function ViewMenu($params)
{
$block_params = $params;
unset($block_params['block']);
$block_params['name'] = $params['block'];
$list =& $this->GetList($params);
$block_params['PrefixSpecial'] = $list->getPrefixSpecial();
return $this->Application->ParseBlock($block_params);
}
function SearchKeyword($params)
{
$list =& $this->GetList($params);
return $this->Application->RecallVar($list->getPrefixSpecial().'_search_keyword');
}
/**
* Draw filter menu content (for ViewMenu) based on filters defined in config
*
* @param Array $params
* @return string
*/
function DrawFilterMenu($params)
{
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $params['spearator_block'];
$separator = $this->Application->ParseBlock($block_params);
$filter_menu = $this->Application->getUnitOption($this->Prefix,'FilterMenu');
// Params: label, filter_action, filter_status
$block_params['name'] = $params['item_block'];
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
if($view_filter === false)
{
$event_params = Array('prefix'=>$this->Prefix,'special'=>$this->Special,'name'=>'OnRemoveFilters');
$this->Application->HandleEvent( new kEvent($event_params) );
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
}
$view_filter = unserialize($view_filter);
$filters = Array();
$prefix_special = $this->getPrefixSpecial();
foreach($filter_menu['Filters'] as $filter_key => $filter_params)
{
if(!$filter_params)
{
$filters[] = $separator;
continue;
}
$block_params['label'] = addslashes( $this->Application->Phrase($filter_params['label']) );
if( getArrayValue($view_filter,$filter_key) )
{
$submit = 0;
$status = 1;
}
else
{
$submit = 1;
$status = 0;
}
$block_params['filter_action'] = 'set_filter("'.$prefix_special.'","'.$filter_key.'","'.$submit.'");';
$block_params['filter_status'] = $status;
$filters[] = $this->Application->ParseBlock($block_params);
}
return implode('', $filters);
}
function IterateGridFields($params)
{
$mode = $params['mode'];
$def_block = $params['block'];
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$grid_config = $grids[$params['grid']]['Fields'];
$std_params['pass_params']='true';
$std_params['PrefixSpecial']=$this->getPrefixSpecial();
$o = '';
foreach ($grid_config as $field => $options) {
$block_params = Array();
$block_params['name'] = isset($options[$mode.'_block']) ? $options[$mode.'_block'] : $def_block;
$block_params['field'] = $field;
$block_params['sort_field'] = isset($options['sort_field']) ? $options['sort_field'] : $field;
$block_params = array_merge($std_params, $block_params, $options);
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList($params)
{
// $list =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List',$params);
$list =& $this->GetList($params);
$id_field = $this->Application->getUnitOption($this->Prefix,'IDField');
$list->Query();
$o = '';
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['pass_params'] = 'true';
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET
$o.= $this->Application->ParseBlock($block_params, 1);
$list->GoNext();
}
$this->Application->SetVar( $this->getPrefixSpecial().'_id', '');
return $o;
}
function InitList($params)
{
$list_name = $params['list_name'];
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
if( !getArrayValue($names_mapping,$list_name) )
{
$list =& $this->GetList($params);
}
}
function BuildListSpecial($params)
{
return $this->Special;
}
/**
* Enter description here...
*
* @param unknown_type $params
* @return kDBList
*/
function &GetList($params)
{
$list_name = $this->SelectParam($params, 'list_name,name');
if (!$list_name) {
$list_name = $this->Application->Parser->GetParam('list_name');
}
$requery = getArrayValue($params, 'requery');
if ($list_name && !$requery){
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
$special = getArrayValue($names_mapping, $list_name);
if(!$special)
{
$special = $this->BuildListSpecial($params);
}
}
else
{
$special = $this->BuildListSpecial($params);
}
$prefix_special = rtrim($this->Prefix.'.'.$special, '.');
$params['skip_counting'] = true;
$list =& $this->Application->recallObject( $prefix_special, $this->Prefix.'_List',$params);
$list->Query();
$this->Special = $special;
if ($list_name) {
$names_mapping[$list_name] = $special;
$this->Application->SetVar('NamesToSpecialMapping', $names_mapping);
}
return $list;
}
function ListMarker($params)
{
$list =& $this->GetList($params);
return $list->getPrefixSpecial();
}
function SubmitName($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
return 'events['.$prefix_special.']['.$params['event'].']';
}
function CombinedSortingDropDownName($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
return $prefix_special.'_CombinedSorting';
}
function SortingSelected($params)
{
$list =& $this->GetList($params);
$user_sorting_start = $this->getUserSortIndex();
$sorting = strtolower($list->GetOrderField($user_sorting_start).'|'.$list->GetOrderDirection($user_sorting_start));
if ($sorting == strtolower($params['sorting'])) return $params['selected'];
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList2($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
$o = '';
$direction = (isset($params['direction']) && $params['direction']=="H")?"H":"V";
$columns = (isset($params['columns'])) ? $params['columns'] : 1;
$id_field = (isset($params['id_field'])) ? $params['id_field'] : $this->Application->getUnitOption($this->Prefix, 'IDField');
if ($columns>1 && $direction=="V") {
$list->Records = $this->LinearToVertical($list->Records, $columns, $list->GetPerPage());
$list->SelectedCount=count($list->Records);
ksort($list->Records);
}
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name']=$this->SelectParam($params, 'render_as,block');
$block_params['pass_params']='true';
$block_start_row_params=$this->prepareTagParams($params);
$block_start_row_params['name'] = $this->SelectParam($params, 'row_start_render_as,block_row_start,row_start_block');
$block_end_row_params=$this->prepareTagParams($params);
$block_end_row_params['name'] = $this->SelectParam($params, 'row_end_render_as,block_row_end,row_end_block');
$block_empty_cell_params = $this->prepareTagParams($params);
$block_empty_cell_params['name'] = $this->SelectParam($params, 'empty_cell_render_as,block_empty_cell,empty_cell_block');
$i=0;
$backup_id=$this->Application->GetVar($this->Prefix."_id");
$displayed = array();
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET
$this->Application->SetVar( $this->Prefix.'_id', $list->GetDBField($id_field) );
if ($i % $columns == 0) {
$o.= $block_start_row_params['name'] ? $this->Application->ParseBlock($block_start_row_params, 1) : '<tr>';
}
if (!$list->getCurrentRecord()){
$o.= $block_empty_cell_params['name'] ? $this->Application->ParseBlock($block_params, 1) : '<td>&nbsp;</td>';
}
else {
$o.= $this->Application->ParseBlock($block_params, 1);
array_push($displayed, $list->GetDBField($id_field));
}
if (($i+1) % $columns == 0) {
$o.= $block_end_row_params['name'] ? $this->Application->ParseBlock($block_end_row_params, 1) : '</tr>';
}
$list->GoNext();
$i++;
}
$cur_displayed = $this->Application->GetVar($this->Prefix.'_displayed_ids');
if (!$cur_displayed) {
$cur_displayed = Array();
}
else {
$cur_displayed = explode(',', $cur_displayed);
}
$displayed = array_unique(array_merge($displayed, $cur_displayed));
$this->Application->SetVar($this->Prefix.'_displayed_ids', implode(',',$displayed));
$this->Application->SetVar( $this->Prefix.'_id', $backup_id);
$this->Application->SetVar( $this->getPrefixSpecial().'_id', '');
if (isset($params['more_link_render_as'])) {
$block_params = $params;
$params['render_as'] = $params['more_link_render_as'];
$o .= $this->MoreLink($params);
}
return $o;
}
function MoreLink($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
if ($list->PerPage < $list->RecordsCount) {
$block_params = array();
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
return $this->Application->ParseBlock($block_params, 1);
}
}
function NotLastItem($params)
{
$list =& $this->Application->recallObject($this->getPrefixSpecial());
return ($list->CurrentIndex < min($list->PerPage, $list->RecordsCount)-1);
}
function PageLink($params)
{
$t = isset($params['template']) ? $param['template'] : '';
if (!$t) $t = $this->Application->GetVar('t');
if (isset($params['page'])) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $params['page']);
}
$pass = Array('pass' => 'all,'.$this->getPrefixSpecial());
// $pass = Array('pass' => 'all');
$http_query =& $this->Application->recallObject('HTTPQuery');
$get = $http_query->Get;
unset($get['env']);
// $pass = array_merge($get, $pass);
return $this->Application->HREF($t, '', $pass);
}
function ColumnWidth($params)
{
$columns = $this->Application->Parser->GetParam('columns');
return round(100/$columns).'%';
}
/**
* Append prefix and special to tag
* params (get them from tagname) like
* they were really passed as params
*
* @param Array $tag_params
* @return Array
* @access protected
*/
function prepareTagParams($tag_params=Array())
{
$ret=$tag_params;
$ret['Prefix']=$this->Prefix;
$ret['Special']=$this->Special;
$ret['PrefixSpecial']=$this->getPrefixSpecial();
return $ret;
}
function GetISO($currency)
{
if ($currency == 'selected') {
$iso = $this->Application->RecallVar('curr_iso');
}
elseif ($currency == 'primary' || $currency == '') {
$iso = $this->Application->GetPrimaryCurrency();
}
else { //explicit currency
$iso = $currency;
}
return $iso;
}
function ConvertCurrency($value, $iso)
{
$converter =& $this->Application->recallObject('kCurrencyRates');
// convery primary currency to selected (if they are the same, converter will just return)
$value = $converter->Convert($value, 'PRIMARY', $iso);
return $value;
}
function AddCurrencySymbol($value, $iso)
{
$this->Application->setUnitOption('curr', 'AutoLoad', false);
$currency =& $this->Application->recallObject('curr.-'.$iso);
if (!$currency->Loaded) {
$currency->Load($iso, 'ISO');
}
$symbol = $currency->GetDBField('Symbol');
if (!$symbol) $symbol = $currency->GetDBField('ISO').'&nbsp;';
if ($currency->GetDBField('SymbolPosition') == 0) {
$value = $symbol.$value;
}
if ($currency->GetDBField('SymbolPosition') == 1) {
$value = $value.$symbol;
}
return $value;
}
/**
* Get's requested field value
*
* @param Array $params
* @return string
* @access public
*/
function Field($params)
{
$field = $this->SelectParam($params, 'name,field');
if( !$this->Application->IsAdmin() ) $params['no_special'] = 'no_special';
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
if ( getArrayValue($params, 'db') !== false )
{
$value = $object->GetDBField($field);
}
else
{
if (isset($params['currency'])) {
$iso = $this->GetISO($params['currency']);
$original = $object->GetDBField($field);
$value = $this->ConvertCurrency($original, $iso);
$object->SetDBField($field, $value);
$object->Fields[$field]['converted'] = true;
}
$format = getArrayValue($params, 'format');
if( !$format || $format == '$format' )
{
$format = null;
}
else
{
if(preg_match("/_regional_(.*)/", $format, $regs))
{
$lang =& $this->Application->recallObject('lang.current');
$format = $lang->GetDBField($regs[1]);
}
}
$value = $object->GetField($field, $format);
if (isset($params['currency'])) {
$value = $this->AddCurrencySymbol($value, $iso);
$params['no_special'] = 1;
}
}
if( getArrayValue($params,'nl2br' ) ) $value = nl2br($value);
if( !$this->HasParam($params, 'no_special') ) $value = htmlspecialchars($value);
if( getArrayValue($params,'checked' ) ) $value = ($value == 1) ? 'checked' : '';
if( getArrayValue($params,'as_label') ) $value = $this->Application->Phrase($value);
$first_chars = $this->SelectParam($params,'first_chars,cut_first');
if($first_chars)
{
$needs_cut = strlen($value) > $first_chars;
$value = substr($value,0,$first_chars);
if($needs_cut) $value .= ' ...';
}
if ($value != '') $this->Application->Parser->DataExists = true;
if (isset($params['currency'])) {
//restoring value in original currency, for other Field tags to work properly
$object->SetDBField($field, $original);
}
return $value;
}
/**
* Checks if parameter is passed
* Note: works like Tag and line simple method too
*
* @param Array $params
* @param string $param_name
* @return bool
*/
function HasParam($params, $param_name = null)
{
if( !isset($param_name) )
{
$param_name = $this->SelectParam($params, 'name');
$params = $this->Application->Parser->Params;
}
$value = getArrayValue($params, $param_name);
return $value && ($value != '$'.$param_name);
}
function PhraseField($params)
{
$field_label = $this->Field($params);
$translation = $this->Application->Phrase( $field_label );
return $translation;
}
function Error($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$msg = $object->GetErrorMsg($field);
return $msg;
}
function HasError($params)
{
if ($params['field'] == 'any') {
$object =& $this->Application->recallObject($this->getPrefixSpecial());
return $object->HasErrors();
}
else {
return $this->Error($params) != '';
}
}
function IsRequired($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$options = $object->GetFieldOptions($field);
return getArrayValue($options,'required');
}
function PredefinedOptions($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$value = $object->GetDBField($field);
$options = $object->GetFieldOptions($field);
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['field'] = $params['field'];
$block_params['pass_params'] = 'true';
$selected_param_name = getArrayValue($params,'selected_param');
if(!$selected_param_name) $selected_param_name = $params['selected'];
$selected = $params['selected'];
$o = '';
if( $this->HasParam($params,'no_empty') && !getArrayValue($options['options'],'') ) array_shift($options['options']);
foreach ($options['options'] as $key => $val) {
$block_params['key'] = $key;
$block_params['option'] = $val;
$block_params['field_name'] = $this->InputName($params);
$block_params[$selected_param_name] = ( $key == $value ? ' '.$selected : '');
$block_params['PrefixSpecial'] = $this->getPrefixSpecial();
$o .= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function Format($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$options = $object->GetFieldOptions($field);
$formatter_class = getArrayValue($options,'formatter');
if($formatter_class)
{
$formatter =& $this->Application->recallObject($formatter_class);
$human_format = getArrayValue($params,'human');
$edit_size = getArrayValue($params,'edit_size');
$sample = getArrayValue($params,'sample');
if($sample)
{
return $formatter->GetSample($field, $options, $object);
}
elseif($human_format || $edit_size)
{
$format = $formatter->HumanFormat($options['format']);
return $edit_size ? strlen($format) : $format;
}
}
return $options['format'];
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintPages($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
$total_pages = $list->GetTotalPages();
if ($total_pages) $this->Application->Parser->DataExists = true;
$o = '';
// what are these 2 lines for?
$this->Application->SetVar($prefix_special.'_event','');
$this->Application->SetVar($prefix_special.'_id','');
$current_page = $this->Application->RecallVar($prefix_special.'_Page');
$block_params = $this->prepareTagParams($params);
$split = ( isset($params['split'] ) ? $params['split'] : 10 );
$split_start = $current_page - ceil($split/2);
if ($split_start < 1){
$split_start = 1;
}
$split_end = $split_start + $split-1;
if ($split_end > $total_pages) {
$split_end = $total_pages;
$split_start = max($split_end - $split + 1, 1);
}
if ($current_page > 1){
$prev_block_params = $this->prepareTagParams();
if ($total_pages > $split){
$prev_block_params['page'] = max($current_page-$split, 1);
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_split_render_as,prev_page_split_block');
if ($prev_block_params['name']){
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
$prev_block_params['name'] = 'page';
$prev_block_params['page'] = $current_page-1;
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_render_as,block_prev_page,prev_page_block');
if ($prev_block_params['name']) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page-1);
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
else {
if ( $no_prev_page_block = $this->SelectParam($params, 'no_prev_page_render_as,block_no_prev_page') ) {
$block_params['name'] = $no_prev_page_block;
$o .= $this->Application->ParseBlock($block_params, 1);
}
}
$separator_params['name'] = $this->SelectParam($params, 'separator_render_as,block_separator');
for ($i = $split_start; $i <= $split_end; $i++)
{
if ($i == $current_page) {
$block = $this->SelectParam($params, 'current_render_as,active_render_as,block_current,active_block');
}
else {
$block = $this->SelectParam($params, 'link_render_as,inactive_render_as,block_link,inactive_block');
}
$block_params['name'] = $block;
$block_params['page'] = $i;
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $i);
$o .= $this->Application->ParseBlock($block_params, 1);
if ($this->SelectParam($params, 'separator_render_as,block_separator')
&& $i < $split_end)
{
$o .= $this->Application->ParseBlock($separator_params, 1);
}
}
if ($current_page < $total_pages){
$next_block_params = $this->prepareTagParams();
$next_block_params['page']=$current_page+1;
$next_block_params['name'] = $this->SelectParam($params, 'next_page_render_as,block_next_page,next_page_block');
if ($next_block_params['name']){
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page+1);
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
if ($total_pages > $split){
$next_block_params['page']=min($current_page+$split, $total_pages);
$next_block_params['name'] = $this->SelectParam($params, 'next_page_split_render_as,next_page_split_block');
if ($next_block_params['name']){
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
}
}
return $o;
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PaginationBar($params)
{
return $this->PrintPages($params);
}
/**
* Returns input field name to
* be placed on form (for correct
* event processing)
*
* @param Array $params
* @return string
* @access public
*/
function InputName($params)
{
$prefix_special=$this->getPrefixSpecial();
$object =& $this->Application->recallObject($prefix_special);
if ( $formatter = getArrayValue($object->Fields, $params['field'], 'formatter') ) {
if ( $formatter == 'kMultiLanguage' ) {
$formatter =& $this->Application->recallObject($formatter);
$params['field'] = $formatter->LangFieldName($params['field']);
}
}
if ( $idfield = getArrayValue($params, 'IdField') ) {
$id = $object->GetDBField($idfield);
}
else {
$id = $object->GetID();
}
return $prefix_special.'['.$id.']['.$params['field'].']';
}
/**
* Returns index where 1st changable sorting field begins
*
* @return int
* @access private
*/
function getUserSortIndex()
{
$list_sortings = $this->Application->getUnitOption($this->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $this->Special) ? $this->Special : '';
$user_sorting_start = 0;
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
$user_sorting_start = count($forced_sorting);
}
return $user_sorting_start;
}
/**
* Returns order direction for given field
*
*
*
* @param Array $params
* @return string
* @access public
*/
function Order($params)
{
$field = $params['field'];
$user_sorting_start = $this->getUserSortIndex();
$list =& $this->GetList($params);
if ($list->GetOrderField($user_sorting_start) == $field)
{
return strtolower($list->GetOrderDirection($user_sorting_start));
}
elseif($list->GetOrderField($user_sorting_start+1) == $field)
{
return '2_'.strtolower($list->GetOrderDirection($user_sorting_start+1));
}
else
{
return 'no';
}
}
/**
* Get's information of sorting field at "pos" position,
* like sorting field name (type="field") or sorting direction (type="direction")
*
* @param Array $params
* @return mixed
*/
function OrderInfo($params)
{
$user_sorting_start = $this->getUserSortIndex() + --$params['pos'];
$list =& $this->GetList($params);
// $object =& $this->Application->recallObject( $this->getPrefixSpecial() );
if($params['type'] == 'field') return $list->GetOrderField($user_sorting_start);
if($params['type'] == 'direction') return $list->GetOrderDirection($user_sorting_start);
}
/**
* Checks if sorting field/direction matches passed field/direction parameter
*
* @param Array $params
* @return bool
*/
function IsOrder($params)
{
$params['type'] = isset($params['field']) ? 'field' : 'direction';
$value = $this->OrderInfo($params);
if( isset($params['field']) ) return $params['field'] == $value;
if( isset($params['direction']) ) return $params['direction'] == $value;
}
/**
* Returns list perpage
*
* @param Array $params
* @return int
*/
function PerPage($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
return $object->PerPage;
}
/**
* Checks if list perpage matches value specified
*
* @param Array $params
* @return bool
*/
function PerPageEquals($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
return $object->PerPage == $params['value'];
}
function SaveEvent($params)
{
// SaveEvent is set during onbuild, but we may need it before any other tag calls onBuild
$prefix_special = $this->getPrefixSpecial();
$item = $this->Application->recallObject($prefix_special);
return $this->Application->GetVar($prefix_special.'_SaveEvent');
}
function NextId($params)
{
$prefix_special=$this->getPrefixSpecial();
$ids = explode(',', $this->Application->RecallVar($prefix_special.'_selected_ids'));
$item = $this->Application->recallObject($prefix_special);
$cur_id = $item->GetId();
$i = array_search($cur_id,$ids);
if ($i !== false) {
return $i < count($ids)-1 ? $ids[$i+1] : '';
}
return '';
}
function PrevId($params)
{
$prefix_special=$this->getPrefixSpecial();
$ids = explode(',', $this->Application->RecallVar($prefix_special.'_selected_ids'));
$item = $this->Application->recallObject($prefix_special);
$cur_id = $item->GetId();
$i = array_search($cur_id,$ids);
if ($i !== false) {
return $i > 0 ? $ids[$i-1] : '';
}
return '';
}
function IsSingle($params)
{
return ($this->NextId($params) === '' && $this->PrevId($params) === '');
}
function IsLast($params)
{
return ($this->NextId($params) === '');
}
function IsFirst($params)
{
return ($this->PrevId($params) === '');
}
/**
* Checks if field value is equal to proposed one
*
* @param Array $params
* @return bool
*/
function FieldEquals($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$ret = $object->GetDBField($this->SelectParam($params, 'name,field')) == $params['value'];
// if( getArrayValue($params,'inverse') ) $ret = !$ret;
return $ret;
}
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$icons =& $grids[ $params['grid'] ]['Icons'];
$key = '';
$status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField');
if(!$status_fields) return $icons['default'];
foreach($status_fields as $status_field)
{
$key .= $object->GetDBField($status_field).'_';
}
$key = rtrim($key,'_');
$value = ($key !== false) ? $key : 'default';
return isset($icons[$value]) ? $icons[$value] : $icons['default'];
}
/**
* Generates bluebar title + initializes prefixes used on page
*
* @param Array $params
* @return string
*/
function SectionTitle($params)
{
$title_presets = $this->Application->getUnitOption($this->Prefix,'TitlePresets');
$title_info = getArrayValue($title_presets, $params['title_preset'] );
if($title_info === false) return $params['title'];
if( getArrayValue($title_presets,'default') )
{
// use default labels + custom labels specified in preset used
$title_info = array_merge_recursive2($title_presets['default'], $title_info);
}
$title = $title_info['format'];
// 1. get objects in use for title construction
$objects = Array();
$object_status = Array();
$status_labels = Array();
$prefixes = getArrayValue($title_info,'prefixes');
if($prefixes)
{
foreach($prefixes as $prefix_special)
{
$prefix_data = $this->Application->processPrefix($prefix_special);
$prefix_data['prefix_special'] = rtrim($prefix_data['prefix_special'],'.');
$objects[ $prefix_data['prefix_special'] ] =& $this->Application->recallObject($prefix_data['prefix_special'], $prefix_data['prefix'], $params);
$object_status[ $prefix_data['prefix_special'] ] = $objects[ $prefix_data['prefix_special'] ]->GetID() ? 'edit' : 'new';
// a. set object's status field (adding item/editing item) for each object in title
if( getArrayValue($title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ],$prefix_data['prefix_special']) )
{
$status_labels[ $prefix_data['prefix_special'] ] = $title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ][ $prefix_data['prefix_special'] ];
$title = str_replace('#'.$prefix_data['prefix_special'].'_status#', $status_labels[ $prefix_data['prefix_special'] ], $title);
}
// b. setting object's titlefield value (in titlebar ONLY) to default in case if object beeing created with no titlefield filled in
if( $object_status[ $prefix_data['prefix_special'] ] == 'new' )
{
$new_value = $this->getInfo( $objects[ $prefix_data['prefix_special'] ], 'titlefield' );
if(!$new_value && getArrayValue($title_info['new_titlefield'],$prefix_data['prefix_special']) ) $new_value = $this->Application->Phrase($title_info['new_titlefield'][ $prefix_data['prefix_special'] ]);
$title = str_replace('#'.$prefix_data['prefix_special'].'_titlefield#', $new_value, $title);
}
}
}
// 2. replace phrases if any found in format string
$title = $this->Application->ReplaceLanguageTags($title,false);
// 3. find and replace any replacement vars
preg_match_all('/#(.*_.*)#/Uis',$title,$rets);
if($rets[1])
{
$replacement_vars = array_keys( array_flip($rets[1]) );
foreach($replacement_vars as $replacement_var)
{
$var_info = explode('_',$replacement_var,2);
$object =& $objects[ $var_info[0] ];
$new_value = $this->getInfo($object,$var_info[1]);
$title = str_replace('#'.$replacement_var.'#', $new_value, $title);
}
}
$cut_first = getArrayValue($params,'cut_first');
if( $cut_first && strlen($title) > $cut_first && !preg_match('/<a href="(.*)">(.*)<\/a>/',$title) ) $title = substr($title, 0, $cut_first).' ...';
return $title;
}
function getInfo(&$object, $info_type)
{
switch ($info_type)
{
case 'titlefield':
$field = $this->Application->getUnitOption($object->Prefix,'TitleField');
return $field !== false ? $object->GetField($field) : 'TitleField Missing';
break;
case 'recordcount':
$of_phrase = $this->Application->Phrase('la_of');
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' '.$of_phrase.' '.$object->NoFilterCount : $object->RecordsCount;
break;
default:
break;
}
}
/**
* Parses block depending on its element type.
* For radio and select elements values are taken from 'value_list_field' in key1=value1,key2=value2
* format. key=value can be substituted by <SQL>SELECT f1 AS OptionName, f2 AS OptionValue... FROM <PREFIX>TableName </SQL>
* where prefix is TABLE_PREFIX
*
* @param Array $params
* @return string
*/
function ConfigFormElement($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
$field = $params['field'];
$helper = $this->Application->recallObject('InpCustomFieldsHelper');
$element_type = $object->GetDBField($params['element_type_field']);
if($element_type=='label') $element_type='text';
$params['name']= $params['blocks_prefix'] . $element_type;
switch ($element_type){
case 'select':
case 'radio':
$field_options = $object->GetFieldOptions($field, 'options');
$field_options['options'] = $helper->GetValuesHash( $object->GetDBField($params['value_list_field']) );
$object->SetFieldOptions($field, $field_options);
break;
case 'textarea':
$params['field_params'] = $helper->ParseConfigSQL($object->GetDBField($params['value_list_field']));
break;
case 'password':
case 'text':
case 'checkbox':
default:
break;
}
return $this->Application->ParseBlock($params, 1);
}
/**
* Get's requested custom field value
*
* @param Array $params
* @return string
* @access public
*/
function CustomField($params)
{
$prefix = $this->Prefix;
$object =& $this->Application->recallObject( $prefix );
$field = $this->SelectParam($params, 'name,field');
$lang_id = $this->Application->GetVar('m_lang');
$sql = ' SELECT cv.l'.$lang_id.'_Value FROM '.TABLE_PREFIX.'CustomField cf
LEFT JOIN '.TABLE_PREFIX.'CustomMetaData cv
ON cf.CustomFieldId = cv.CustomFieldId
WHERE cf.Type = '.$this->Application->getUnitOption($prefix, 'ItemType').'
AND cv.ResourceId = '.$object->GetDBField('ResourceId').'
AND cf.FieldName = "'.$field.'"';
return $this->Conn->GetOne($sql);
}
function CustomFieldLabel($params)
{
$prefix = $this->Prefix;
$object =& $this->Application->recallObject( $prefix );
$field = $this->SelectParam($params, 'name,field');
$sql = ' SELECT FieldLabel FROM '.TABLE_PREFIX.'CustomField WHERE FieldName = "'.$field.'"';
return $this->Application->Phrase($this->Conn->GetOne($sql));
}
/**
* transposes 1-dimensional array elements for vertical alignment according to given columns and per_page parameters
*
* @param array $arr
* @param int $columns
* @param int $per_page
* @return array
*/
function LinearToVertical(&$arr, $columns, $per_page)
{
$rows=$columns;
$cols=min(ceil($per_page/$columns), ceil(sizeof($arr)/$columns));
$imatrix=array();
for ($row=0; $row<$rows; $row++) {
for ($col=0; $col<$cols; $col++){
$imatrix[$col*$rows+$row]=$arr[$row*$cols+$col];
}
}
ksort($imatrix);
reset($imatrix);
return $imatrix;
}
/**
* If data was modfied & is in TempTables mode, then parse block with name passed;
* remove modification mark if not in TempTables mode
*
* @param Array $params
* @return string
* @access public
* @author Alexey
*/
function SaveWarning($params)
{
$main_prefix = getArrayValue($params, 'main_prefix');
if($main_prefix && $main_prefix != '$main_prefix')
{
$top_prefix = $main_prefix;
}
else
{
$top_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
}
$temp_tables = $this->Application->GetVar($top_prefix.'_mode') == 't';
$modified = $this->Application->RecallVar($top_prefix.'_modified');
if($temp_tables && $modified)
{
return $this->Application->ParseBlock($params);
}
$this->Application->RemoveVar($top_prefix.'_modified');
return '';
}
/**
* Returns list record count queries (on all pages)
*
* @param Array $params
* @return int
*/
function TotalRecords($params)
{
$list =& $this->GetList($params);
if (!$list->Counted) $list->CountRecs();
return $list->RecordsCount;
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/db/db_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.12
\ No newline at end of property
Index: trunk/core/kernel/db/db_event_handler.php
===================================================================
--- trunk/core/kernel/db/db_event_handler.php (revision 2260)
+++ trunk/core/kernel/db/db_event_handler.php (revision 2261)
@@ -1,1447 +1,1447 @@
<?php
define('EH_CUSTOM_PROCESSING_BEFORE',1);
define('EH_CUSTOM_PROCESSING_AFTER',2);
/**
* Note:
* 1. When adressing variables from submit containing
* Prefix_Special as part of their name use
* $event->getPrefixSpecial(true) instead of
* $event->Prefix_Special as usual. This is due PHP
* is converting "." symbols in variable names during
* submit info "_". $event->getPrefixSpecial optional
* 1st parameter returns correct corrent Prefix_Special
* for variables beeing submitted such way (e.g. variable
* name that will be converted by PHP: "users.read_only_id"
* will be submitted as "users_read_only_id".
*
* 2. When using $this->Application-LinkVar on variables submitted
* from form which contain $Prefix_Special then note 1st item. Example:
* LinkVar($event->getPrefixSpecial(true).'_varname',$event->Prefix_Special.'_varname')
*
*/
/**
* EventHandler that is used to process
* any database related events
*
*/
class kDBEventHandler extends kEventHandler {
/**
* Description
*
- * @var DBConnection
+ * @var kDBConnection
* @access public
*/
var $Conn;
/**
* Adds ability to address db connection
*
* @return kDBEventHandler
* @access public
*/
function kDBEventHandler()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
function mapEvents()
{
$events_map = Array('OnRemoveFilters' => 'FilterAction',
'OnApplyFilters' => 'FilterAction');
$this->eventMethods = array_merge($this->eventMethods, $events_map);
}
/**
* Returns ID of current item to be edited
* by checking ID passed in get/post as prefix_id
* or by looking at first from selected ids, stored.
* Returned id is also stored in Session in case
* it was explicitly passed as get/post
*
* @param kEvent $event
* @return int
*/
function getPassedID(&$event)
{
//$ret = $this->Application->GetLinkedVar($event->getPrefixSpecial(true).'_id', $event->getPrefixSpecial().'_id');
// ?? We don't need to store selected id in session, as long as we have pass=all by default, which
// means that main item id will be passed to all sub-item screens by default
// another prove of that is that sub-items relay on main item '_mode' = 't' for switching to temp tables
// Also having id in session raised problems with the id of deleted item stuck in session
// 1. get id from post (used in admin)
$ret = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if($ret) return $ret;
// 2. get id from env (used in front)
$ret = $this->Application->GetVar($event->getPrefixSpecial().'_id');
if($ret) return $ret;
// recall selected ids array and use the first one
$ids=$this->Application->GetVar($event->getPrefixSpecial().'_selected_ids');
if ($ids != '') {
$ids=explode(',',$ids);
if($ids) $ret=array_shift($ids);
}
else { // if selected ids are not yet stored
$this->StoreSelectedIDs($event);
return $this->Application->GetVar($event->getPrefixSpecial(true).'_id'); // StoreSelectedIDs sets this variable
}
return $ret;
}
/**
* Prepares and stores selected_ids string
* in Session and Application Variables
* by getting all checked ids from grid plus
* id passed in get/post as prefix_id
*
* @param kEvent $event
*/
function StoreSelectedIDs(&$event)
{
$ret = Array();
// May be we don't need this part: ?
$passed = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if($passed !== false && $passed != '')
{
array_push($ret, $passed);
}
$ids = Array();
// get selected ids from post & save them to session
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
foreach($items_info as $id => $field_values)
{
if( getArrayValue($field_values,$id_field) ) array_push($ids,$id);
}
//$ids=array_keys($items_info);
}
$ret = array_unique(array_merge($ret, $ids));
$this->Application->SetVar($event->getPrefixSpecial().'_selected_ids',implode(',',$ret));
$this->Application->LinkVar($event->getPrefixSpecial().'_selected_ids');
// This is critical - otherwise getPassedID will return last ID stored in session! (not exactly true)
// this smells... needs to be refactored
$first_id = getArrayValue($ret,0);
if($first_id === false) trigger_error('Requested ID for prefix <b>'.$event->getPrefixSpecial().'</b> <span class="debug_error">not passed</span>',E_USER_NOTICE);
$this->Application->SetVar($event->getPrefixSpecial(true).'_id', $first_id);
}
/**
* Returns stored selected ids as an array
*
* @param kEvent $event
* @return array
*/
function getSelectedIDs(&$event)
{
return explode(',', $this->Application->GetVar($event->getPrefixSpecial().'_selected_ids'));
}
/**
* Returs associative array of submitted fields for current item
* Could be used while creating/editing single item -
* meaning on any edit form, except grid edit
*
* @param kEvent $event
*/
function getSubmittedFields(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$field_values = $items_info ? array_shift($items_info) : Array();
return $field_values;
}
/**
* Removes any information about current/selected ids
* from Application variables and Session
*
* @param kEvent $event
*/
function clearSelectedIDs(&$event)
{
$prefix_special = $event->getPrefixSpecial();
$ids = $this->Application->RecallVar($prefix_special.'_selected_ids');
$event->setEventParam('ids', $ids);
$this->Application->RemoveVar($prefix_special.'_selected_ids');
$this->Application->SetVar($prefix_special.'_selected_ids', '');
$this->Application->SetVar($prefix_special.'_id', ''); // $event->getPrefixSpecial(true).'_id' too may be
}
/*function SetSaveEvent(&$event)
{
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnUpdate');
$this->Application->LinkVar($event->Prefix_Special.'_SaveEvent');
}*/
/**
* Common builder part for Item & List
*
* @param kDBBase $object
* @param kEvent $event
* @access private
*/
function dbBuild(&$object,&$event)
{
$object->Configure();
$this->PrepareObject($object, $event);
$live_table = $event->getEventParam('live_table');
if( $this->UseTempTables($event) && !$live_table )
{
$object->SwitchToTemp();
}
// This strange constuction creates hidden field for storing event name in form submit
// It pass SaveEvent to next screen, otherwise after unsuccsefull create it will try to update rather than create
$current_event = $this->Application->GetVar($event->Prefix_Special.'_event');
// $this->Application->setEvent($event->Prefix_Special, $current_event);
$this->Application->setEvent($event->Prefix_Special, '');
$save_event = $this->UseTempTables($event) && $this->Application->GetTopmostPrefix($event->Prefix) == $event->Prefix ? 'OnSave' : 'OnUpdate';
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent',$save_event);
}
/**
* Builds item (loads if needed)
*
* @param kEvent $event
* @access protected
*/
function OnItemBuild(&$event)
{
$object =& $event->getObject();
$this->dbBuild($object,$event);
$sql = $this->ItemPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
// 2. loads if allowed
$auto_load = $this->Application->getUnitOption($event->Prefix,'AutoLoad');
if($auto_load) $this->LoadItem($event);
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_GoTab', '');
$actions->Set($event->Prefix_Special.'_GoId', '');
}
/**
* Build subtables array from configs
*
* @param kEvent $event
*/
function OnTempHandlerBuild(&$event)
{
$object =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$object->BuildTables( $event->Prefix, $this->getSelectedIDs($event) );
}
/**
* Enter description here...
*
* @param kEvent $event
* @return unknown
*/
function UseTempTables(&$event)
{
$object = &$event->getObject();
$top_prefix = $this->Application->GetTopmostPrefix($event->Prefix);
return $this->Application->GetVar($top_prefix.'_mode') == 't';
}
/**
* Returns table prefix from event (temp or live)
*
* @param kEvent $event
* @return string
* @todo Needed? Should be refactored (by Alex)
*/
function TablePrefix(&$event)
{
return $this->UseTempTables($event) ? kTempTablesHandler::GetTempTablePrefix().TABLE_PREFIX : TABLE_PREFIX;
}
function LoadItem(&$event)
{
$object =& $event->getObject();
if ( $event->getEventParam('ByParent') ) {
$parent_prefix = $this->Application->getUnitOption($event->Prefix, 'ParentPrefix');
$parent_table_key = $this->Application->getUnitOption($event->Prefix, 'ParentTableKey');
$parent_object =& $this->Application->recallObject($parent_prefix);
$id = $parent_object->GetDBField($parent_table_key);
$id_field = $this->Application->getUnitOption($event->Prefix, 'ForeignKey');
}
else {
$id = $this->getPassedID($event);
$id_field = null;
}
if ($object->Load($id, $id_field)) {
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_id', $object->GetId());
}
}
/**
* Builds list
*
* @param kEvent $event
* @access protected
*/
function OnListBuild(&$event)
{
//$event->setPseudoClass('_List');
$object =& $event->getObject();
$this->dbBuild($object,$event);
$sql = $this->ListPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
$object->linkToParent( $this->getMainSpecial($event) );
// $object->linkToParent($special);
$this->AddFilters($event);
$this->SetCustomQuery($event); // new!, use this for dynamic queries based on specials for ex.
$this->SetPagination($event);
$this->SetSorting($event);
$actions =& $this->Application->recallObject('kActions');
$actions->Set('remove_specials['.$event->Prefix_Special.']', '0');
$actions->Set($event->Prefix_Special.'_GoTab', '');
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
$special = $event->getEventParam('main_special');
if($special === false || $special == '$main_special')
{
$special = $event->Special;
}
return $special;
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @access protected
* @see OnListBuild
*/
function SetCustomQuery(&$event)
{
}
/**
* Set's new perpage for grid
*
* @param kEvent $event
*/
function OnSetPerPage(&$event)
{
$per_page = $this->Application->GetVar($event->getPrefixSpecial(true).'_PerPage');
$this->Application->StoreVar( $event->getPrefixSpecial().'_PerPage', $per_page );
}
/**
* Set's correct page for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetPagination(&$event)
{
// get PerPage (forced -> session -> config -> 10)
$per_page = $this->getPerPage($event);
$object =& $event->getObject();
$object->SetPerPage($per_page);
$this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1);
$page = $this->Application->GetVar($event->getPrefixSpecial().'_Page');
if (!$page) {
$page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page');
}
if (!$page) {
$page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page');
}
else {
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
// $page = $this->Application->GetLinkedVar($event->getPrefixSpecial(true).'_Page', $event->getPrefixSpecial().'_Page');
if( !$event->getEventParam('skip_counting') )
{
$pages = $object->GetTotalPages();
if($page > $pages)
{
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1);
$page = 1;
}
}
$object->SetPage($page);
}
function getPerPage($event)
{
$per_page = $event->getEventParam('per_page');
$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
if ( $config_mapping ) {
switch ( $per_page ){
case 'short_list' :
$per_page = $this->Application->ConfigValue($config_mapping['ShortListPerPage']);
break;
case 'default' :
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
break;
}
}
if(!$per_page)
{
$per_page_var = $event->getPrefixSpecial().'_PerPage';
$per_page = $this->Application->RecallVar($per_page_var);
if(!$per_page)
{
if ( $config_mapping ) {
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
}
if(!$per_page) $per_page = 10;
}
}
return $per_page;
}
/**
* Set's correct sorting for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetSorting(&$event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject();
$cur_sort1 = $this->Application->RecallVar($event->Prefix_Special.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort1_Dir');
$cur_sort2 = $this->Application->RecallVar($event->Prefix_Special.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort2_Dir');
$sorting_configs = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $event->Special) ? $event->Special : '';
$tag_sort_by = $event->getEventParam('sort_by');
if ($tag_sort_by) {
list($by, $dir) = explode(',', $tag_sort_by);
if ($by == 'random') $by = 'RAND()';
$object->AddOrderField($by, $dir);
}
if ($sorting_configs && isset ($sorting_configs['DefaultSorting1Field'])){
$list_sortings[$sorting_prefix]['Sorting'] = Array(
$this->Application->ConfigValue($sorting_configs['DefaultSorting1Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting1Dir']),
$this->Application->ConfigValue($sorting_configs['DefaultSorting2Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting2Dir']),
);
}
// Use default if not specified
if ( !$cur_sort1 || !$cur_sort1_dir)
{
if ( $sorting = getArrayValue($list_sortings, $sorting_prefix, 'Sorting') ) {
reset($sorting);
$cur_sort1 = key($sorting);
$cur_sort1_dir = current($sorting);
if (next($sorting)) {
$cur_sort2 = key($sorting);
$cur_sort2_dir = current($sorting);
}
}
}
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
foreach ($forced_sorting as $field => $dir) {
$object->AddOrderField($field, $dir);
}
}
if($cur_sort1 != '' && $cur_sort1_dir != '')
{
$object->AddOrderField($cur_sort1, $cur_sort1_dir);
}
if($cur_sort2 != '' && $cur_sort2_dir != '')
{
$object->AddOrderField($cur_sort2, $cur_sort2_dir);
}
}
/**
* Add filters found in session
*
* @param kEvent $event
*/
function AddFilters(&$event)
{
$object =& $event->getObject();
$search_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_search_filter');
if($search_filter)
{
$search_filter = unserialize($search_filter);
foreach($search_filter as $search_field => $filter_params)
{
$filter_type = ($filter_params['type'] == 'having') ? HAVING_FILTER : WHERE_FILTER;
$object->addFilter($search_field, $filter_params['value'], $filter_type, FLT_SEARCH);
}
}
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
if($view_filter)
{
$view_filter = unserialize($view_filter);
$temp_filter =& $this->Application->makeClass('kMultipleFilter');
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
$group_key = 0; $group_count = count($filter_menu['Groups']);
while($group_key < $group_count)
{
$group_info = $filter_menu['Groups'][$group_key];
$temp_filter->setType( constant('FLT_TYPE_'.$group_info['mode']) );
$temp_filter->clearFilters();
foreach ($group_info['filters'] as $flt_id)
{
$sql_key = getArrayValue($view_filter,$flt_id) ? 'on_sql' : 'off_sql';
if ($filter_menu['Filters'][$flt_id][$sql_key] != '')
{
$temp_filter->addFilter('view_filter_'.$flt_id, $filter_menu['Filters'][$flt_id][$sql_key]);
}
}
$object->addFilter('view_group_'.$group_key, $temp_filter, $group_info['type'] , FLT_VIEW);
$group_key++;
}
}
}
/**
* Set's new sorting for list
*
* @param kEvent $event
* @access protected
*/
function OnSetSorting(&$event)
{
$cur_sort1 = $this->Application->RecallVar($event->Prefix_Special.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort1_Dir');
$cur_sort2 = $this->Application->RecallVar($event->Prefix_Special.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort2_Dir');
$passed_sort1 = $this->Application->GetVar($event->getPrefixSpecial(true).'_Sort1');
if ($cur_sort1 == $passed_sort1) {
$cur_sort1_dir = $cur_sort1_dir == 'asc' ? 'desc' : 'asc';
}
else {
$cur_sort2 = $cur_sort1;
$cur_sort2_dir = $cur_sort1_dir;
$cur_sort1 = $passed_sort1;
$cur_sort1_dir = 'asc';
}
$this->Application->StoreVar($event->Prefix_Special.'_Sort1', $cur_sort1);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1_Dir', $cur_sort1_dir);
$this->Application->StoreVar($event->Prefix_Special.'_Sort2', $cur_sort2);
$this->Application->StoreVar($event->Prefix_Special.'_Sort2_Dir', $cur_sort2_dir);
}
/**
* Set sorting directly to session
*
* @param kEvent $event
*/
function OnSetSortingDirect(&$event)
{
$combined = $this->Application->GetVar($event->getPrefixSpecial(true).'_CombinedSorting');
if ($combined) {
list($field,$dir) = explode('|',$combined);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1', $field);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1_Dir', $dir);
return;
}
$field_pos = $this->Application->GetVar($event->getPrefixSpecial(true).'_SortPos');
$this->Application->LinkVar( $event->getPrefixSpecial(true).'_Sort'.$field_pos, $event->Prefix_Special.'_Sort'.$field_pos);
$this->Application->LinkVar( $event->getPrefixSpecial(true).'_Sort'.$field_pos.'_Dir', $event->Prefix_Special.'_Sort'.$field_pos.'_Dir');
}
/**
* Reset grid sorting to default (from config)
*
* @param kEvent $event
*/
function OnResetSorting(&$event)
{
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1_Dir');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2_Dir');
}
/**
* Creates needed sql query to load item,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ItemPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix,'ItemSQLs');
return isset($sqls[$event->Special]) ? $sqls[$event->Special] : $sqls[''];
}
/**
* Creates needed sql query to load list,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ListPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix,'ListSQLs');
return isset( $sqls[$event->Special] ) ? $sqls[$event->Special] : $sqls[''];
}
/**
* Apply custom processing to item
*
* @param kEvent $event
*/
function customProcessing(&$event, $type)
{
}
/* Edit Events mostly used in Admin */
/**
* Creates new kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnCreate(&$event)
{
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
$object->SetFieldsFromHash($field_values);
}
$this->customProcessing($event,'before');
//look at kDBItem' Create for ForceCreateId description, it's rarely used and is NOT set by default
if( $object->Create($event->getEventParam('ForceCreateId')) )
{
if( $object->IsTempTable() ) $object->setTempID();
$this->customProcessing($event,'after');
$event->status=erSUCCESS;
$event->redirect_params = Array('opener'=>'u');
}
else
{
$event->status=erFAIL;
$event->redirect=false;
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
$object->setID($id);
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnUpdate(&$event)
{
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
break;
}
}
}
$event->redirect_params = Array('opener'=>'u');
}
/**
* Delete's kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnDelete(&$event)
{
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$object->ID = $this->getPassedID($event);
if( $object->Delete() )
{
$event->status = erSUCCESS;
}
else
{
$event->status = erFAIL;
$event->redirect = false;
}
}
/**
* Prepares new kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnNew(&$event)
{
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$object->setID(0);
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
$table_info = $object->getLinkedInfo();
$object->SetDBField($table_info['ForeignKey'], $table_info['ParentId']);
$this->Application->setUnitOption($event->Prefix,'AutoLoad',true);
$event->redirect = false;
}
/**
* Cancel's kDBItem Editing/Creation
*
* @param kEvent $event
* @access protected
*/
function OnCancel(&$event)
{
$event->redirect_params = Array('opener'=>'u');
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 0)) {
return;
}
$event->status=erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$this->StoreSelectedIDs($event);
$event->setEventParam('ids', $this->getSelectedIDs($event) );
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
*/
function OnEdit(&$event)
{
$this->StoreSelectedIDs($event);
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp->PrepareEdit();
$event->redirect=false;
}
/**
* Saves content of temp table into live and
* redirects to event' default redirect (normally grid template)
*
* @param kEvent $event
*/
function OnSave(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$skip_master=false;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
// newly created item
/*if($this->getPassedID($event) == 0)
{
$master_id = $temp->CopyMasterToOriginal();
$temp->UpdateForeignKeys($master_id); // save linked field values
$skip_master = true; //we've already copied master table to get the id
}*/
if (!$this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 0)) {
$temp->SaveEdit($skip_master);
}
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener'=>'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
}
}
/**
* Cancels edit
* Removes all temp tables and clears selected ids
*
* @param kEvent $event
*/
function OnCancelEdit(&$event)
{
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp->CancelEdit();
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener'=>'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
}
/**
* Saves edited item into temp table
* If there is no id, new item is created in temp table
*
* @param kEvent $event
*/
function OnPreSave(&$event)
{
//$event->redirect = false;
// if there is no id - it means we need to create an item
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',false);
}
$item_id = $this->getPassedID($event);
if($item_id == '')
{
$event->CallSubEvent('OnPreSaveCreated');
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',true);
}
return;
}
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->SetDefaultValues();
$object->Load($id);
$object->SetFieldsFromHash($field_values);
if( $object->Update($id) )
{
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
break;
}
}
}
}
/**
* Saves edited item in temp table and loads
* item with passed id in current template
* Used in Prev/Next buttons
*
* @param kEvent $event
*/
function OnPreSaveAndGo(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$event->redirect_params[$event->getPrefixSpecial(true).'_id'] = $this->Application->GetVar($event->Prefix_Special.'_GoId');
}
}
/**
* Saves edited item in temp table and goes
* to passed tabs, by redirecting to it with OnPreSave event
*
* @param kEvent $event
*/
function OnPreSaveAndGoToTab(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Saves editable list and goes to passed tab,
* by redirecting to it with empty event
*
* @param kEvent $event
*/
function OnUpdateAndGoToTab(&$event)
{
$event->setPseudoClass('_List');
$event->CallSubEvent('OnUpdate');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
$this->clearSelectedIDs($event);
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$object =& $event->getObject();
$temp =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$temp->PrepareEdit();
$object->setID(0);
$event->redirect=false;
}
/**
* Creates a new item in temp table and
* stores item id in App vars and Session on succsess
*
* @param kEvent $event
*/
function OnPreSaveCreated(&$event)
{
$this->Application->setUnitOption($event->Prefix,'AutoLoad',false);
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info) $field_values = array_shift($items_info);
$object =& $event->getObject();
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Create() )
{
$this->customProcessing($event, 'after');
$event->redirect_params[$event->getPrefixSpecial(true).'_id'] = $object->GetId();
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
$object->setID(0);
}
}
/* End of Edit events */
// III. Events that allow to put some code before and after Update,Load,Create and Delete methods of item
/**
* Occurse before loading item, 'id' parameter
* allows to get id of item beeing loaded
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemLoad(&$event)
{
}
/**
* Occurse after loading item, 'id' parameter
* allows to get id of item that was loaded
*
* @param kEvent $event
* @access public
*/
function OnAfterItemLoad(&$event)
{
}
/**
* Occurse before creating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemCreate(&$event)
{
}
/**
* Occurse after creating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemCreate(&$event)
{
}
/**
* Occurse before updating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemUpdate(&$event)
{
}
/**
* Occurse after updating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemUpdate(&$event)
{
}
/**
* Occurse before deleting item, id of item beeing
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemDelete(&$event)
{
}
/**
* Occurse after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @access public
*/
function OnAfterItemDelete(&$event)
{
}
/**
* Occurs after successful item validation
*
* @param kEvent $event
*/
function OnAfterItemValidate(&$event)
{
}
/**
* Occures after an item has been copied to temp
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToTemp(&$event)
{
}
/**
* Occures before an item is deleted from live table when copying from temp
* (temp handler deleted all items from live and then copy over all items from temp)
* Id of item being deleted is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeDeleteFromLive(&$event)
{
}
/**
* Occures before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeCopyToLive(&$event)
{
}
/**
* !!! NOT FULLY IMPLEMENTED - SEE TEMP HANDLER COMMENTS (search by event name)!!!
* Occures after an item has been copied to live table
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToLive(&$event)
{
}
/**
* Occures before an item is cloneded
* Id of ORIGINAL item is passed as event' 'id' param
* Do not call object' Update method in this event, just set needed fields!
*
* @param kEvent $event
*/
function OnBeforeClone(&$event)
{
}
/**
* Occures after an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterClone(&$event)
{
}
/**
* Ensures that popup will be closed automatically
* and parent window will be refreshed with template
* passed
*
* @param kEvent $event
* @access public
*/
function finalizePopup(&$event, $main_prefix, $t)
{
$event->redirect = 'incs/close_popup';
// 2. substitute opener
$opener_stack = $this->Application->RecallVar('opener_stack');
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array();
//array_pop($opener_stack);
$new_level = 'index4.php|'.ltrim($this->Application->BuildEnv($t, Array('m_opener' => 'u'), 'all'), ENV_VAR_NAME.'=');
array_push($opener_stack,$new_level);
$this->Application->StoreVar('opener_stack',serialize($opener_stack));
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @access protected
*/
function OnSearch(&$event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject();
$keyword = $this->Application->GetVar( $event->getPrefixSpecial(true).'_search_keyword');
$this->Application->StoreVar( $event->getPrefixSpecial().'_search_keyword', $keyword);
if(!$keyword)
{
$this->OnSearchReset($event);
return true;
}
$grid_name = $this->Application->GetVar('grid_name');
$grids = $this->Application->getUnitOption($event->Prefix,'Grids');
$search_fields = array_keys($grids[$grid_name]['Fields']);
$search_filter = Array();
foreach($search_fields as $search_field)
{
$filter_type = isset($object->VirtualFields[$search_field]) ? 'having' : 'where';
$field_type = getArrayValue($object->Fields[$search_field],'type');
if(!$field_type) $field_type = 'string'; // default LIKE filter for all fields without type
$keyword = trim($keyword);
$keyword = str_replace(Array('"',"'"),'',$keyword);
$filter_value = '';
$table_name = ($filter_type == 'where') ? '`'.$object->TableName.'`.' : '';
// get field clause by formatter name and/or parameters
$formatter = getArrayValue($object->Fields[$search_field],'formatter');
switch ($formatter)
{
case 'kOptionsFormatter':
$search_keys = Array();
$use_phrases = getArrayValue($object->Fields[$search_field], 'use_phrases');
foreach($object->Fields[$search_field]['options'] as $key => $val)
{
$pattern = '#'.$keyword.'#i';
if ( preg_match($pattern, $use_phrases ? $this->Application->Phrase($val) : $val) ) {
array_push($search_keys, $key);
}
}
if (count($search_keys) > 0) {
$filter_value = $table_name.'`'.$search_field.'` IN ('.implode(',', $search_keys).')';
}
$field_processed = true;
break;
default:
$field_processed = false;
break;
}
// if not already processed by formatter, then get clause by field type
if(!$field_processed)
{
switch($field_type)
{
case 'int':
case 'integer':
case 'numeric':
if( !is_numeric($keyword) ) break;
$filter_value = $table_name.'`'.$search_field.'` = \''.$keyword.'\'';
break;
case 'double':
case 'float':
case 'real':
if( !is_numeric($keyword) ) break;
$filter_value = 'ABS('.$table_name.'`'.$search_field.'` - \''.str_replace(',','.',$keyword).'\') <= 0.0001';
break;
case 'string':
$like_keyword = preg_replace( '/\'(.*)\'/U', '\\1', $this->Conn->qstr( str_replace('\\','\\\\', $keyword) ) );
$keywords = explode(' ', $like_keyword);
foreach($keywords as $keyword_pos => $keyword_value)
{
$keyword_value = trim($keyword_value);
if($keyword_value)
{
$keywords[$keyword_pos] = $table_name.'`'.$search_field.'` LIKE \'%'.$keyword_value.'%\'';
}
else
{
unset($keywords[$keyword_pos]);
}
}
$filter_value = '('.implode(') OR (',$keywords).')';
break;
}
}
if($filter_value) $search_filter[$search_field] = Array('type' => $filter_type, 'value' => $filter_value);
}
$this->Application->StoreVar($event->getPrefixSpecial().'_search_filter', serialize($search_filter) );
}
/**
* Clear search keywords
*
* @param kEvent $event
* @access protected
*/
function OnSearchReset(&$event)
{
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_filter');
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_keyword');
}
/**
* Set's new filter value (filter_id meaning from config)
*
* @param kEvent $event
*/
function OnSetFilter(&$event)
{
$filter_id = $this->Application->GetVar('filter_id');
$filter_value = $this->Application->GetVar('filter_value');
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
$view_filter = $view_filter ? unserialize($view_filter) : Array();
$view_filter[$filter_id] = $filter_value;
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
/**
* Add/Remove all filters applied to list from "View" menu
*
* @param kEvent $event
*/
function FilterAction(&$event)
{
$view_filter = Array();
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
switch ($event->Name)
{
case 'OnRemoveFilters':
$filter_value = 1;
break;
case 'OnApplyFilters':
$filter_value = 0;
break;
}
foreach($filter_menu['Filters'] as $filter_key => $filter_params)
{
if(!$filter_params) continue;
$view_filter[$filter_key] = $filter_value;
}
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndOpenTranslator(&$event)
{
$this->Application->SetVar('allow_translation', true);
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
// $url = $this->Application->HREF($t, '', Array('pass'=>'all', $event->getPrefixSpecial(true).'_id' => $object->GetId()));
// $field = $this->Application->GetVar('translator_field');
$event->redirect = $this->Application->GetVar('translator_t');
$event->redirect_params = Array('pass'=>'all,trans,'.$this->Application->GetVar('translator_prefixes'),
$event->getPrefixSpecial(true).'_id' => $object->GetId(),
'trans_event'=>'OnLoad',
'trans_prefix'=> $this->Application->GetVar('translator_prefixes'),
'trans_field'=>$this->Application->GetVar('translator_field'),
);
//$after_script = "openTranslator('".$event->getPrefixSpecial()."', '".$field."', '".$url."', '".$wnd_name."')";
}
// $this->Application->SetVar('after_script', $after_script);
// $event->redirect = false;
}
function RemoveRequiredFields(&$object)
{
// making all field non-required to achieve successful presave
foreach($object->Fields as $field => $options)
{
if(isset($options['required']))
{
unset($object->Fields[$field]['required']);
}
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/db/db_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.16
\ No newline at end of property
+1.17
\ No newline at end of property
Index: trunk/core/kernel/languages/phrases_cache.php
===================================================================
--- trunk/core/kernel/languages/phrases_cache.php (revision 2260)
+++ trunk/core/kernel/languages/phrases_cache.php (revision 2261)
@@ -1,185 +1,185 @@
<?php
class PhrasesCache extends kBase {
/**
* Connection to database
*
- * @var DBConnection
+ * @var kDBConnection
* @access public
*/
var $Conn;
var $Phrases = Array();
var $Ids = Array();
var $OriginalIds = Array(); //for comparing cache
var $LanguageId = 1;
var $fromTag = false;
function PhrasesCache($LanguageId=1)
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
$this->Phrases = Array();
$this->LanguageId = $LanguageId;
$this->LoadPhrases( $this->GetCachedIds() );
}
function GetCachedIds()
{
$query = sprintf("SELECT PhraseList FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(md5($this->Application->GetVar('t'))));
$phrases_ids = $this->Conn->GetOne($query);
return ($phrases_ids === false) ? Array() : explode(',', $phrases_ids);
}
function LoadPhrases($ids)
{
if ( !is_array($ids) || !implode('', $ids) ) return;
$query = sprintf("SELECT Translation,Phrase FROM %s WHERE LanguageId = %s AND PhraseId IN (%s)",
TABLE_PREFIX.'Phrase',
$this->LanguageId,
join(',', $ids));
$phrases = $this->Conn->GetCol($query,'Phrase');
foreach($phrases as $phrase => $tanslation)
{
$this->AddCachedPhrase(strtoupper($phrase), $tanslation);
}
$this->Ids = $ids;
$this->OriginalIds = $ids;
}
function AddCachedPhrase($label, $value)
{
$label = strtoupper($label);
$this->Phrases[$label] = $value;
}
function UpdateCache()
{
if (!is_array($this->Ids) || count($this->Ids) == 0) return;
if ($this->Ids == $this->OriginalIds) return; //nothing changed
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template)
VALUES (%s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Ids)),
mktime(),
$this->Conn->Qstr(md5($this->Application->GetVar('t'))));
$this->Conn->Query($query);
}
function GetPhrase($label)
{
if (ereg("^!.+!$", $label) > 0)
{
$label = substr($label, 1, -1); //cut exclamation marks
}
$original_label = $label;
$label = strtoupper($label);
if( isset($this->Phrases[$label]) )
{
$translated_label = $this->Phrases[$label];
if($this->Application->isDebugMode() && dbg_ConstOn('DBG_PHRASES_HILIGHT') && !$this->Application->IsAdmin())
$translated_label = '<span style="border: 1px solid #999999; background-color: #cccccc; color: #999999; ">'.$translated_label.'</span>';
return $translated_label;
}
$this->LoadPhraseByLabel($label, $original_label);
return $this->GetPhrase($label);
}
function LoadPhraseByLabel($label, $original_label)
{
$query = sprintf("SELECT PhraseId, Translation FROM %s WHERE LanguageId = %s AND UPPER(Phrase) = UPPER(%s)",
TABLE_PREFIX.'Phrase',
$this->LanguageId,
$this->Conn->qstr($label));
$res = $this->Conn->GetRow($query);
if ($res === false || count($res) == 0)
{
$translation = '!'.$label.'!';
if( $this->Application->isDebugMode() && dbg_ConstOn('DBG_PHRASES') )
{
list($edit_tpl, $index_file) = $this->Application->IsAdmin() ? Array('regional/phrases_edit', 'index4.php') : Array('phrases_edit', 'index.php');
$edit_url = $this->Application->HREF($edit_tpl,'',Array('m_opener'=>'d','phrases_label'=>$original_label,'phrases_event'=>'OnNew', 'pass'=>'all,phrases'), $index_file );
$translation = '<a href="'.$edit_url.'">!'.$label.'!</a>';
if($this->fromTag) $translation = $this->escapeTagReserved($translation);
}
$this->AddCachedPhrase($label, $translation); //add it as already cached, as long as we dont need to cache not found phrase
return false;
}
$this->Phrases[$label] = $res['Translation'];
array_push($this->Ids, $res['PhraseId']);
$this->Ids = array_unique($this->Ids); //just to make sure
return true;
}
/**
* Sort params by name and then by length
*
* @param string $a
* @param string $b
* @return int
* @access private
*/
function CmpParams($a, $b)
{
$a_len = strlen($a);
$b_len = strlen($b);
if ($a_len == $b_len) return 0;
return $a_len > $b_len ? -1 : 1;
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text,$forse_escaping=null)
{
$this->fromTag = true;
if( isset($forse_escaping) ) $this->fromTag = $forse_escaping;
preg_match_all("(!(la|lu)[^!]+!)", $text, $res, PREG_PATTERN_ORDER);
$language_tags = $res[0];
uasort($language_tags, Array(&$this, 'CmpParams') );
$values = Array();
$i = 0;
foreach ($language_tags as $label) {
array_push($values, $this->GetPhrase($label) );
//array_push($values, $this->Application->Phrase($label) );
$language_tags[$i] = '/' . $language_tags[$i] . '/';
$i++;
}
$this->fromTag = false;
return preg_replace($language_tags, $values, $text);
}
/**
* Escape chars in phrase translation, that could harm parser to process tag
*
* @param string $text
* @return string
* @access private
*/
function escapeTagReserved($text)
{
$reserved = Array('"',"'"); // =
$replacement = Array('\"',"\'"); // \=
return str_replace($reserved,$replacement,$text);
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/languages/phrases_cache.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/core/kernel/kbase.php
===================================================================
--- trunk/core/kernel/kbase.php (revision 2260)
+++ trunk/core/kernel/kbase.php (revision 2261)
@@ -1,472 +1,472 @@
<?php
/**
* Base
*
* Desciption
* @package kernel4
*/
class kBase {
/**
* Holds reference to global KernelApplication instance
* @access public
* @var kApplication
*/
var $Application;
/**
* Prefix, that was used
* to create an object
*
* @var string
* @access public
*/
var $Prefix='';
/**
* Special, that was used
* to create an object
*
* @var string
* @access public
*/
var $Special='';
var $OriginalParams;
/**
* Set's application
*
* @return kBase
* @access public
*/
function kBase()
{
$this->Application =& kApplication::Instance();
}
/**
* Create new instance of object
*
* @return kBase
*/
function &makeClass()
{
return new kBase();
}
/**
* Set's prefix and special
*
* @param string $prefix
* @param string $special
* @access public
*/
function Init($prefix,$special,$event_params=null)
{
$prefix=explode('_',$prefix,2);
$this->Prefix=$prefix[0];
$this->Special=$special;
$this->OriginalParams = $event_params;
}
/**
* Returns joined prefix
* and special if any
*
* @return string
* @access protected
*/
function getPrefixSpecial()
{
return rtrim($this->Prefix.'.'.$this->Special,'.');
}
function &getProperty($property_name)
{
return $this->$property_name;
}
function setProperty($property_name, &$property_value)
{
$this->$property_name =& $property_value;
}
}
class kDBBase extends kBase {
/**
* Connection to database
*
- * @var DBConnection
+ * @var kDBConnection
* @access public
*/
var $Conn;
/**
* Description
*
* @var string Name of primary key field for the item
* @access public
*/
var $IDField;
/**
* Holds SELECT, FROM, JOIN parts of SELECT query
*
* @var string
* @access public
*/
var $SelectClause;
/**
* Display queries executed by the class
*
* @var bool
* @access public
*/
var $DisplayQueries = false;
/**
* Fields allowed to be set (from table + virtual)
*
* @var Array
* @access private
*/
var $Fields=Array();
/**
* All virtual field names
*
* @var Array
* @access private
*/
var $VirtualFields=Array();
/**
* Fields that need to be queried using custom expression, e.g. IF(...) AS value
*
* @var Array
* @access private
*/
var $CalculatedFields = Array();
/**
* Description
*
* @var string Item' database table name, without prefix
* @access public
*/
var $TableName;
/**
* Allows to determine object's table status ('temp' - temp table, '' - live table)
*
* @var string
* @access public
*/
var $mode='';
function kDBBase()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Set current item' database table name
*
* @access public
* @param string $table_name
* @return void
*/
function setTableName($table_name)
{
$this->TableName = $table_name;
}
/**
* Set object' TableName to Live table from config
*
* @access public
*/
function SwitchToLive()
{
$this->TableName = $this->Application->getUnitOption($this->Prefix, 'TableName');
}
/**
* Set object' TableName to Temp table from config
*
* @access public
*/
function SwitchToTemp()
{
$this->TableName = $this->Application->getUnitOption($this->Prefix, 'TableName');
$this->SetTableName( kTempTablesHandler::GetTempName($this->TableName) );
$this->mode = 't';
}
/**
* Checks if object uses temp table
*
* @return bool
*/
function IsTempTable()
{
return kTempTablesHandler::IsTempTable($this->TableName);
}
/**
* Sets SELECT part of list' query
*
* @access public
* @param string $sql SELECT and FROM [JOIN] part of the query up to WHERE
* @return void
*/
function SetSelectSQL($sql)
{
$this->SelectClause = $sql;
}
function GetSelectSQL($base_query=null)
{
if( !isset($base_query) ) $base_query = $this->SelectClause;
return $q = str_replace( Array('%1$s','%s'), $this->TableName, $base_query);
}
/**
* Insert calculated fields sql into query in place of %2$s,
* return processed query.
*
* @param string $query
* @return string
*/
function addCalculatedFields($query)
{
if($this->CalculatedFields)
{
$sql = Array();
foreach($this->CalculatedFields as $field_name => $field_expression)
{
$sql[] = '('.$field_expression.') AS '.$field_name;
}
$sql = implode(',',$sql);
return $this->Application->ReplaceLanguageTags( str_replace('%2$s', ','.$sql, $query) );
}
else
{
return str_replace('%2$s', '', $query);
}
}
/**
* Adds calculated field declaration to object.
*
* @param string $name
* @param string $sql_clause
*/
function addCalculatedField($name, $sql_clause)
{
$this->CalculatedFields[$name] = $sql_clause;
}
/**
* Sets ID Field name used as primary key for loading items
*
* @access public
* @param string $field_name
* @return void
* @see kDBBase::IDField
*/
function setIDField($field_name)
{
$this->IDField = $field_name;
}
function Configure()
{
$this->setTableName( $this->Application->getUnitOption($this->Prefix, 'TableName') );
$this->setIDField( $this->Application->getUnitOption($this->Prefix, 'IDField') );
$this->setConfigFields( $this->Application->getUnitOption($this->Prefix, 'Fields') );
$this->setVirtualFields( $this->Application->getUnitOption($this->Prefix, 'VirtualFields') );
$this->setCalculatedFields( $this->Application->getUnitOption($this->Prefix, 'CalculatedFields') );
$this->prepareConfigOptions(); // this should go last, but before setDefaultValues, order is significant!
$this->SetDefaultValues();
}
function setCalculatedFields($fields)
{
$this->CalculatedFields = isset($fields[$this->Special]) ? $fields[$this->Special] : (isset($fields['']) ? $fields[''] : false);
}
/**
* Set's field names from table
* from config
*
* @param Array $fields
* @access public
*/
function setConfigFields($fields)
{
$this->Fields=$fields;
}
/**
* Set fields (+options) for fields that physically doesn't exist in database
*
* @param Array $fields
* @access public
*/
function setVirtualFields($fields)
{
if($fields)
{
$this->VirtualFields = $fields;
$this->Fields = array_merge_recursive2($this->VirtualFields, $this->Fields);
}
}
function SetDefaultValues()
{
foreach($this->Fields as $field => $options)
{
if( getArrayValue($options, 'default') === '#NOW#')
{
$this->Fields[$field]['default'] = mktime();
}
}
}
function SetFieldOptions($field, $options)
{
$this->Fields[$field] = $options;
}
function GetFieldOptions($field)
{
return isset($this->Fields[$field]) ? $this->Fields[$field] : Array();
}
/**
* Returns formatted field value
*
* @param string $field
* @return string
* @access public
*/
function GetField($name, $format=null)
{
$options = $this->GetFieldOptions($name);
$val = $this->GetDBField($name);
$res = $val;
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$res = $formatter->Format($val, $name, $this, $format );
}
return $res;
}
function HasField($name)
{
}
function GetFieldValues()
{
}
function UpdateFormattersSubFields()
{
foreach ($this->Fields as $field => $options) {
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateSubFields($field, $this->GetDBField($field), $options, $this);
}
}
}
function prepareConfigOptions()
{
foreach (array_keys($this->Fields) as $field_name)
{
$field_options =& $this->Fields[$field_name];
if( isset($field_options['options_sql']) )
{
// replace with query result
$select_clause = $field_options['option_title_field'].','.$field_options['option_key_field'];
$sql = sprintf($field_options['options_sql'], $select_clause);
$options_hash = getArrayValue($field_options,'options');
if($options_hash === false) $options_hash = Array();
$dynamic_options = $this->Conn->GetCol($sql, $field_options['option_key_field']);
$field_options['options'] = array_merge_recursive2($options_hash, $dynamic_options);
unset($field_options['options_sql']);
}
$this->PrepareOptions($field_name);
}
}
function PrepareOptions($field_name)
{
if( $formatter_class = getArrayValue($this->Fields[$field_name], 'formatter') )
{
$formatter =& $this->Application->recallObject($formatter_class);
$formatter->PrepareOptions($field_name, $this->Fields[$field_name], $this);
}
}
/**
* Returns unformatted field value
*
* @param string $field
* @return string
* @access public
*/
function GetDBField($field)
{
}
/**
* Returns ID of currently processed record
*
* @return int
* @access public
*/
function GetID()
{
return $this->GetDBField($this->IDField);
}
/**
* Returns parent table information
*
* @param bool $from_temp load parent item from temp table
* @param string $special special of main item
* @return Array
*/
function getLinkedInfo($special = '')
{
$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
if($parent_prefix)
{
// if this is linked table, then set id from main table
$table_info = Array(
'TableName' => $this->Application->getUnitOption($this->Prefix,'TableName'),
'IdField' => $this->Application->getUnitOption($this->Prefix,'IDField'),
'ForeignKey' => $this->Application->getUnitOption($this->Prefix,'ForeignKey'),
'ParentTableKey' => $this->Application->getUnitOption($this->Prefix,'ParentTableKey'),
'ParentPrefix' => $parent_prefix
);
$main_object = $this->Application->recallObject($parent_prefix.'.'.$special);
return array_merge($table_info, Array('ParentId'=> $main_object->GetDBField( $table_info['ParentTableKey'] ) ) );
}
return false;
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/kbase.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property

Event Timeline