
-- ----- SYSTEM --------------------------------------------------------------

-- system configuration
CREATE TABLE IF NOT EXISTS SystemConfiguration (
    TopLinkString           TEXT,
    TopLinkBeginLetter      TEXT,
    TopLinkEndLetter        TEXT,
    AdminEmail              TEXT,
    PasswordMailSubject     TEXT,
    PasswordMailBody        TEXT,
    PasswordResetMailSubject TEXT,
    PasswordResetMailBody   TEXT,
    MailChangeMailSubject   TEXT,
    MailChangeMailBody      TEXT,
    PortalName              TEXT,
    DefaultActiveUI         TEXT,
    DefaultCharacterSet     TEXT,
    DefaultRecordsPerPage   INT DEFAULT 5,
    NumResourcesForSearchFacets INT DEFAULT 5000,
    MaxFacetsPerField       INT DEFAULT 75,
    DefaultSortField        INT,
    CollapseMetadataFieldGroups INT DEFAULT 0,
    RequireEmailWithFeedback INT DEFAULT 0,
    UseMinimizedJavascript  INT DEFAULT 0,
    SearchEngineUpdatePriority  INT DEFAULT 3,
    RecommenderEngineUpdatePriority  INT DEFAULT 3,
    NumClassesPerBrowsePage INT DEFAULT 80,
    NumColumnsPerBrowsePage INT DEFAULT 2,
    BrowsingFieldId         INT DEFAULT 27,
    NumAnnounceOnHomePage   INT DEFAULT 2,
    NumResourcesOnHomePage  INT DEFAULT 5,
    LegalNotice             TEXT,
    SearchTermsRequired     INT,
    ShowNumResourcesEnabled INT DEFAULT 0,
    AnnouncementsEnabled    INT DEFAULT 1,
    ForumsEnabled           INT DEFAULT 1,
    ForumsAllowHTML         INT DEFAULT 1,
    ForumsUseWYSIWYG        INT DEFAULT 1,
    AllowMultipleUIsEnabled INT DEFAULT 0,
    ResourceLaunchesNewWindowEnabled    INT DEFAULT 1,
    UserAgentsEnabled       INT DEFAULT 0,
    ResourceRatingsEnabled  INT DEFAULT 1,
    ResourceCommentsEnabled INT DEFAULT 1,
    IncrementalKeywordSearchEnabled INT DEFAULT 0,
    ReleaseFlagApproved     INT DEFAULT 0,
    SearchDBEnabled         INT DEFAULT 1,
    RecommenderDBEnabled    INT DEFAULT 1,
    OAISQEnabled            INT DEFAULT 1,
    OaiIdDomain             TEXT,
    OaiIdPrefix             TEXT,
    OaiEarliestDate         TEXT,
    OaiDateGranularity      ENUM ("DATE", "DATETIME"),
    SiteKeywords            TEXT,
    AboutText               TEXT,
    CurrentTheme            TEXT,
    ContactName             TEXT,
    ContactEmail            TEXT,
    Organization            TEXT,
    OrganizationType        TEXT,
    SiteType                TEXT,
    OkayToListSite          INT,
    AddAWStatsScript        INT DEFAULT 0,
    AddGoogleAnalytics      INT DEFAULT 0,
    GoogleAnalyticsCode     TEXT,
    DisplayLimitsByDefault  INT DEFAULT 1,
    LastRegisteredOn        DATETIME,
    TitleField              INT DEFAULT -2147483647,
    DescriptionField        INT DEFAULT -2147483647,
    UrlField                INT DEFAULT -2147483647,
    FileField               INT DEFAULT -2147483647,
    ScreenshotField         INT DEFAULT -2147483647,
    PreferredLinkValue      ENUM ("URL", "FILE") DEFAULT "FILE",
    TitlesLinkTo            ENUM ("URL", "RECORD") DEFAULT "URL",
    SecureLogin             INT DEFAULT 1,
    DefaultUserPrivs        TEXT,
    EmailDeliverySettings   TEXT,
    EmailLineEnding         ENUM ("CRLF", "CR", "LF") NOT NULL DEFAULT "CRLF",
    SavedSearchMailTemplate INT DEFAULT -1
);

-- user interface style configuration
CREATE TABLE IF NOT EXISTS UIStyleConfiguration (
    StyleName                   TEXT,
    LogoFileName                TEXT,
    LogoAltText                 TEXT,
    LogoWidth                   INT,
    LogoHeight                  INT,
    PageCenterBackground        TEXT,
    PageSideBackground          TEXT,
    SPTTableHeaderBackground    TEXT,
    MDTTableHeaderBackground    TEXT,
    TableBodyBackground         TEXT,
    ForumDarkHeaderBackground   TEXT,
    ForumLightHeaderBackground  TEXT,
    ForumBodyBackground         TEXT,
    NavBoxBackground            TEXT,
    HomeBoxBackground           TEXT
);

-- portal news items or announcements
CREATE TABLE IF NOT EXISTS Announcements (
    AnnouncementId          INT NOT NULL AUTO_INCREMENT,
    AnnouncementHeading     TEXT,
    AnnouncementText        TEXT,
    DatePosted              DATETIME,
    PosterId                INT,
    INDEX                   (AnnouncementId)
);

-- saved searches
CREATE TABLE IF NOT EXISTS SavedSearches (
    SearchId            INT NOT NULL AUTO_INCREMENT,
    SearchName          TEXT,
    UserId              INT NOT NULL,
    DateLastRun         TIMESTAMP,
    Frequency           INT,
    INDEX               (UserId),
    INDEX               (SearchId)
);

-- saved search text parameters
CREATE TABLE IF NOT EXISTS SavedSearchTextParameters (
    SearchId            INT NOT NULL,
    FieldId             INT,
    SearchText          TEXT,
    INDEX               (SearchId)
);

-- saved search value ID parameters (used for controlled names, options, etc)
CREATE TABLE IF NOT EXISTS SavedSearchIdParameters (
    SearchId            INT NOT NULL,
    FieldId             INT,
    SearchValueId       INT,
    INDEX               (SearchId)
);

-- RSS Import Feeds
CREATE TABLE IF NOT EXISTS RSSFeeds (
    RSSId                   INT NOT NULL AUTO_INCREMENT,
    Title                   TEXT,
    URL                     TEXT,
    DisplayLocations        INT NOT NULL,
    NumberItemsToDisplay    INT,
    RefreshRate             INT NOT NULL,
    Enabled                 INT DEFAULT 0,
    INDEX                   (RSSId)
);

-- add additional fields to user records
ALTER TABLE APUsers ADD COLUMN ActiveUI TEXT;
ALTER TABLE APUsers ADD COLUMN BrowsingFieldId INT;
ALTER TABLE APUsers ADD COLUMN RecordsPerPage INT;
ALTER TABLE APUsers ADD COLUMN SearchSelections TEXT;

-- OAI-SQ search sites
CREATE TABLE IF NOT EXISTS GlobalSearchSites (
    SiteId                      INT NOT NULL AUTO_INCREMENT,
    SiteName                    TEXT,
    OaiUrl                      TEXT,
    SiteUrl                     TEXT,
    LastSearchDate              DATETIME,
    ConsecutiveFailures         INT DEFAULT 0,
    SearchAttempts              INT DEFAULT 0,
    SuccessfulSearches          INT DEFAULT 0,
    INDEX                       (SiteId)
);

-- user-defined privileges
CREATE TABLE IF NOT EXISTS CustomPrivileges (
    Id          INT NOT NULL,
    Name        TEXT,
    INDEX       (Id)
);

-- secure login data
CREATE TABLE LoginKeys (
  KeyPair TEXT,
  CreationTime TIMESTAMP
);

CREATE TABLE UsedLoginTokens (
  Token TEXT,
  KeyCTime TIMESTAMP,
  UserName TEXT
);

-- ----- RESOURCES AND RELATED DATA ------------------------------------------

-- metadata schemas
CREATE TABLE IF NOT EXISTS MetadataSchemas (
    SchemaId                INT NOT NULL,
    Name                    TEXT,
    ResourceName            TEXT,
    AuthoringPrivileges     BLOB,
    EditingPrivileges       BLOB,
    ViewingPrivileges       BLOB,
    ViewPage                TEXT,
    INDEX                   (SchemaId)
);

-- metadata fields
CREATE TABLE IF NOT EXISTS MetadataFields (
    FieldId                         INT NOT NULL,
    FieldName                       TEXT NOT NULL,
    FieldType                       ENUM("Text", "Number", "Date", "TimeStamp",
                                            "Paragraph", "Flag", "Tree",
                                            "ControlledName", "Option", "User",
                                            "Still Image", "File", "Url",
                                            "Point", "Reference"),
    SchemaId                        INT NOT NULL DEFAULT 0,
    Label                           TEXT,
    Description                     TEXT,
    Instructions                    TEXT,
    Owner                           TEXT,
    EnableOnOwnerReturn             INT DEFAULT 0,
    RequiredBySPT                   INT DEFAULT 0,
    Enabled                         INT DEFAULT 1,
    Optional                        INT DEFAULT 1,
    Editable                        INT DEFAULT 1,
    AllowMultiple                   INT DEFAULT 0,
    IncludeInKeywordSearch          INT DEFAULT 0,
    IncludeInAdvancedSearch         INT DEFAULT 0,
    IncludeInFacetedSearch          INT DEFAULT 0,
    IncludeInSortOptions            INT DEFAULT 1,
    IncludeInRecommender            INT DEFAULT 0,
    DisplayAsListForAdvancedSearch  INT DEFAULT 0,
    TextFieldSize                   INT,
    MaxLength                       INT,
    ParagraphRows                   INT,
    ParagraphCols                   INT,
    DefaultValue                    TEXT,
    MinValue                        INT,
    `MaxValue`                      INT,
    FlagOnLabel                     TEXT,
    FlagOffLabel                    TEXT,
    DateFormat                      TEXT,
    DateFormatIsPerRecord           INT,
    SearchWeight                    INT,
    RecommenderWeight               INT,
    MaxHeight                       INT,
    MaxWidth                        INT,
    MaxPreviewHeight                INT,
    MaxPreviewWidth                 INT,
    MaxThumbnailHeight              INT,
    MaxThumbnailWidth               INT,
    DefaultAltText                  TEXT,
    ImagePreviewPrivilege           INT DEFAULT 0,
    UsesQualifiers                  INT DEFAULT 0,
    HasItemLevelQualifiers          INT DEFAULT 0,
    DefaultQualifier                INT,
    DateLastModified                TIMESTAMP,
    LastModifiedById                INT,
    UseForOaiSets                   INT DEFAULT 0,
    NumAjaxResults                  INT DEFAULT 50,
    OptionListThreshold             INT DEFAULT 25,
    AjaxThreshold                   INT DEFAULT 50,
    ViewingPrivilege                INT DEFAULT 0,
    AuthoringPrivilege              INT DEFAULT 12,
    EditingPrivilege                INT DEFAULT 3,
    ViewingUserIsValue              INT DEFAULT 0,
    AuthoringUserIsValue            INT DEFAULT 0,
    EditingUserIsValue              INT DEFAULT 0,
    ViewingUserValue                INT,
    AuthoringUserValue              INT,
    EditingUserValue                INT,
    PointPrecision                  INT DEFAULT 8,
    PointDecimalDigits              INT DEFAULT 5,
    UpdateMethod                    ENUM("NoAutoUpdate", "OnRecordCreate",
                                            "Button", "OnRecordEdit",
                                            "OnRecordChange")
                                            DEFAULT "NoAutoUpdate",
    AllowHTML                       INT DEFAULT 0,
    UseWysiwygEditor                INT DEFAULT 0,
    TreeBrowsingPrivilege           INT DEFAULT 0,
    ShowQualifiers                  INT DEFAULT 0,
    UserPrivilegeRestrictions       TEXT,
    AuthoringPrivileges             BLOB,
    EditingPrivileges               BLOB,
    ViewingPrivileges               BLOB,
    PreviewingPrivileges            BLOB,
    INDEX                           (FieldId),
    INDEX                           (FieldType)
);

-- resource metadata field orders
CREATE TABLE IF NOT EXISTS MetadataFieldOrders (
    SchemaId                  INT NOT NULL,
    OrderId                   INT NOT NULL,
    OrderName                 TEXT
);

-- field qualifiers
CREATE TABLE IF NOT EXISTS Qualifiers (
    QualifierId            INT NOT NULL,
    QualifierName          TEXT,
    QualifierNamespace     TEXT,
    QualifierUrl           TEXT,
    INDEX                  (QualifierId)
);

-- intersection between MetadataFields and Qualifiers
CREATE TABLE IF NOT EXISTS FieldQualifierInts (
    MetadataFieldId        INT NOT NULL,
    QualifierId            INT NOT NULL,
    INDEX                  (MetadataFieldId),
    INDEX                  (QualifierId),
    UNIQUE                 (MetadataFieldId, QualifierId)
);

-- resource records
CREATE TABLE IF NOT EXISTS Resources (
    ResourceId              INT NOT NULL,
    SchemaId                INT NOT NULL DEFAULT 0,
    Title                   TEXT,
    AlternateTitle          TEXT,
    Description             TEXT,
    Url                     TEXT,
    ReleaseFlag             INT,
    Source                  TEXT,
    Relation                TEXT,
    Coverage                TEXT,
    Rights                  TEXT,
    EmailAddress            TEXT,
    DateIssuedBegin         DATE,
    DateIssuedEnd           DATE,
    DateIssuedPrecision     INT,
    DateOfRecordCreation    DATETIME,
    DateOfRecordRelease     DATETIME,
    DateRecordChecked       DATETIME,
    DateLastModified        DATETIME,
    VerificationAttempts    INT,
    AddedById               INT,
    LastModifiedById        INT,
    CumulativeRating        INT DEFAULT 0,
    Screenshot              INT,
    INDEX                   (ResourceId),
    INDEX                   (SchemaId)
);

-- references/links between source resources to destination resources
CREATE TABLE IF NOT EXISTS ReferenceInts (
    FieldId       INT,
    SrcResourceId INT,
    DstResourceId INT,
    INDEX         (FieldId, SrcResourceId),
    UNIQUE        (FieldId, SrcResourceId, DstResourceId)
);

-- text values associated with resources
CREATE TABLE IF NOT EXISTS TextValues (
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    TextValue               TEXT,
    INDEX                   (ResourceId, FieldId)
);

-- numeric values associated with resources
CREATE TABLE IF NOT EXISTS NumberValues (
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    NumberValue             INT,
    INDEX                   (ResourceId, FieldId)
);

-- date/time values associated with resources
CREATE TABLE IF NOT EXISTS DateValues (
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    DateBegin               DATETIME,
    DateEnd                 DATETIME,
    DatePrecision           INT,
    INDEX                   (ResourceId, FieldId)
);

-- user ratings of resources
CREATE TABLE IF NOT EXISTS ResourceRatings (
    ResourceId              INT NOT NULL,
    UserId                  INT NOT NULL,
    DateRated               DATETIME,
    Rating                  INT,
    Comments                TEXT,
    CommentApproved         INT,
    INDEX                   (ResourceId),
    INDEX                   (UserId)
);

-- controlled names (publishers, authors, etc)
CREATE TABLE IF NOT EXISTS ControlledNames (
    ControlledNameId        INT NOT NULL AUTO_INCREMENT,
    ControlledName          TEXT,
    FieldId                 INT NOT NULL,
    QualifierId             INT,
    LastAssigned            TIMESTAMP NULL,
    INDEX                   (ControlledNameId),
    INDEX                   (ControlledName(16)),
    INDEX                   (FieldId),
    INDEX                   (LastAssigned)
);

-- possible variants on controlled names
CREATE TABLE IF NOT EXISTS VariantNames (
    ControlledNameId        INT NOT NULL,
    VariantName             TEXT,
    INDEX                   (ControlledNameId),
    INDEX                   (VariantName(16))
);
-- add at least one variant name to avoid MySQL-related query problem
INSERT INTO VariantNames (ControlledNameId, VariantName) VALUES (-1, "DUMMY");

-- classifications (subjects, categories, etc)
CREATE TABLE IF NOT EXISTS Classifications (
    ClassificationId        INT NOT NULL AUTO_INCREMENT,
    FieldId                 INT NOT NULL,
    ClassificationName      TEXT,
    Depth                   INT,
    ParentId                INT NOT NULL,
    SegmentName             TEXT,
    ResourceCount           INT,
    FullResourceCount       INT,
    LinkString              TEXT,
    QualifierId             INT,
    LastAssigned            TIMESTAMP NULL,
    INDEX                   (ClassificationId),
    INDEX                   (ParentId),
    INDEX                   (FieldId),
    INDEX                   (FieldId, ParentId),
    INDEX                   (LastAssigned),
    FULLTEXT                (SegmentName, ClassificationName)
);

-- counts of resources per classification
CREATE TABLE IF NOT EXISTS ClassResourceCounts (
    ClassificationId        INT NOT NULL,
    ConditionalId           INT NOT NULL,
    INDEX                   (ClassificationId)
);

-- hash values for class resource count conditions
CREATE TABLE IF NOT EXISTS ClassResourceConditionals (
    ConditionalId           INT NOT NULL,
    ConditionalHash         TEXT,
    INDEX                   (ConditionalId),
    INDEX                   (ConditionalHash(32))
);

-- intersection table between Resources and ControlledNames
CREATE TABLE IF NOT EXISTS ResourceNameInts (
    ResourceId              INT NOT NULL,
    ControlledNameId        INT NOT NULL,
    INDEX                   (ResourceId),
    INDEX                   (ControlledNameId),
    UNIQUE                  (ResourceId, ControlledNameId)
);

-- intersection table between Resources and Classifications
CREATE TABLE IF NOT EXISTS ResourceClassInts (
    ResourceId              INT NOT NULL,
    ClassificationId        INT NOT NULL,
    INDEX                   (ResourceId),
    INDEX                   (ClassificationId),
    UNIQUE                  (ResourceId, ClassificationId)
);

-- intersection table between Resources and Images
CREATE TABLE IF NOT EXISTS ResourceImageInts (
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    ImageId                 INT NOT NULL,
    INDEX                   (ResourceId, FieldId),
    INDEX                   (ImageId),
    UNIQUE                  (ResourceId, FieldId, ImageId)
);

-- image information
CREATE TABLE IF NOT EXISTS Images (
    ImageId                 INT NOT NULL AUTO_INCREMENT,
    Format                  INT,
    AltText                 TEXT,
    Width                   INT,
    Height                  INT,
    PreviewWidth            INT,
    PreviewHeight           INT,
    ThumbnailWidth          INT,
    ThumbnailHeight         INT,
    INDEX                   (ImageId)
);

-- attached files
CREATE TABLE IF NOT EXISTS Files (
    FileId                  INT NOT NULL AUTO_INCREMENT,
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    FileName                TEXT,
    FileComment             TEXT,
    FileLength              INT,
    FileType                TEXT,
    SecretString            TEXT,
    INDEX                   (ResourceId),
    INDEX                   (FileId),
    INDEX                   (ResourceId, FieldId)
);

-- resource modification timestamps
CREATE TABLE IF NOT EXISTS ResourceFieldTimestamps (
    ResourceId      INT NOT NULL,
    FieldId         INT NOT NULL,
    Timestamp       DATETIME,
    ModifiedBy      INT NOT NULL,
    INDEX           (ResourceId, FieldId),
    INDEX           (Timestamp)
);


-- ----- FORUMS --------------------------------------------------------------

-- forums (top level of forum content hierarchy)
CREATE TABLE IF NOT EXISTS Forums (
    ForumId                 INT NOT NULL AUTO_INCREMENT,
    ForumName               TEXT,
    ForumDescription        TEXT,
    TopicCount              INT,
    MessageCount            INT,
    ModeratorId             INT,
    INDEX                   (ForumId)
);

-- topics within forums (second level of forum content hierarchy)
-- also:  resource annotation topics
CREATE TABLE IF NOT EXISTS Topics (
    TopicId                 INT NOT NULL AUTO_INCREMENT,
    ForumId                 INT NOT NULL,
    CreatorId               INT,
    DateCreated             DATETIME,
    TopicName               TEXT,
    ViewCount               INT,
    MessageCount            INT,
    INDEX                   (TopicId, ForumId)
);

-- messages within forum topics (lowest level of forum content hierarchy)
CREATE TABLE IF NOT EXISTS Messages (
    MessageId               INT NOT NULL AUTO_INCREMENT,
    ParentId                INT NOT NULL,
    ParentType              INT NOT NULL,
    DatePosted              DATETIME,
    DateEdited              DATETIME,
    PosterId                INT,
    EditorId                INT,
    Subject                 TEXT,
    Body                    TEXT,
    INDEX                   (MessageId, ParentId)
);

-- resource searches performed by users or set up for use with user agents
CREATE TABLE IF NOT EXISTS Searches (
    SearchId                INT NOT NULL AUTO_INCREMENT,
    UserId                  INT NOT NULL,
    DateLastRun             DATETIME,
    Keywords                TEXT,
    RunInterval             INT,
    INDEX                   (SearchId)
);


-- ----- RECOMMENDER SYSTEM --------------------------------------------------

-- correlation values for recommender system
CREATE TABLE IF NOT EXISTS RecContentCorrelations (
    ItemIdA                 INT NOT NULL,
    ItemIdB                 INT NOT NULL,
    Correlation             SMALLINT NOT NULL,
    INDEX                   (ItemIdA, ItemIdB)
);


-- ----- OAI EXPORT ----------------------------------------------------------

-- OAI formats table
CREATE TABLE IF NOT EXISTS OAIFormats (
    FormatId        INT NOT NULL AUTO_INCREMENT,
    FormatName      TEXT,
    TagName         TEXT,
    SchemaLocation  TEXT,
    INDEX           (FormatId)
);

-- OAI format namespaces table
CREATE TABLE IF NOT EXISTS OAIFormatNamespaces (
    FormatId        INT NOT NULL,
    NamespaceName   TEXT,
    NamespaceURI    TEXT,
    INDEX           (FormatId)
);

-- OAI field mappings table
CREATE TABLE IF NOT EXISTS OAIFieldMappings (
    FormatName          TEXT NOT NULL,
    SPTFieldId          INT NOT NULL,
    OAIFieldName        TEXT,
    INDEX               (SPTFieldId)
);

-- OAI qualifier mappings table
CREATE TABLE IF NOT EXISTS OAIQualifierMappings (
    FormatName          TEXT NOT NULL,
    SPTQualifierId      INT NOT NULL,
    OAIQualifierName    TEXT,
    INDEX               (SPTQualifierId)
);

-- Count of resources assigned to each defined ControlledName
CREATE TABLE IF NOT EXISTS ResourceCounts (
    FieldId INT,
    ClassName TEXT,
    CountType TEXT,
    Count INT
);

CREATE TABLE IF NOT EXISTS CachedValues (
    Name TEXT,
    Value TEXT,
    Updated TIMESTAMP
);


-- ----- FOLDERS ------------------------------------------------------------

-- folders for storing groups of items
CREATE TABLE IF NOT EXISTS Folders (
    FolderId                INT NOT NULL AUTO_INCREMENT,
    PreviousFolderId        INT,
    NextFolderId            INT,
    OwnerId                 INT,
    FolderName              TEXT,
    NormalizedName          TEXT,
    FolderNote              TEXT,
    IsShared                INT DEFAULT 0,
    ContentType             INT DEFAULT -1,
    INDEX                   (OwnerId),
    INDEX                   (FolderId)
);

-- intersection table indicating which items are in which folders
CREATE TABLE IF NOT EXISTS FolderItemInts (
    FolderId                INT NOT NULL,
    ItemId                  INT NOT NULL,
    ItemTypeId              INT DEFAULT -1,
    PreviousItemId          INT DEFAULT -1,
    PreviousItemTypeId      INT DEFAULT -1,
    NextItemId              INT DEFAULT -1,
    NextItemTypeId          INT DEFAULT -1,
    ItemNote                TEXT,
    INDEX                   (FolderId),
    INDEX                   (ItemId)
);

-- mapping of item type names to numerical item type IDs
CREATE TABLE IF NOT EXISTS FolderContentTypes (
    TypeId                  INT NOT NULL AUTO_INCREMENT,
    TypeName                TEXT,
    NormalizedTypeName      TEXT,
    INDEX                   (TypeId)
);
