<?PHP

# initialize page generation time clock
$PageGenerationBeginTime = microtime(TRUE);

# define privilege levels for SPT
define("PRIV_SYSADMIN", 1);
define("PRIV_NEWSADMIN", 2);
define("PRIV_RESOURCEADMIN", 3);
define("PRIV_FORUMADMIN", 4);
define("PRIV_CLASSADMIN", 5);
define("PRIV_NAMEADMIN", 6);
define("PRIV_RELEASEADMIN", 7);
define("PRIV_USERADMIN", 8);
define("PRIV_POSTTOFORUMS", 9);
define("PRIV_POSTCOMMENTS", 10);
define("PRIV_USERDISABLED", 11);
define("PRIV_MYRESOURCEADMIN", 12);
define("PRIV_COLLECTIONADMIN", 13);
$PrivDescriptions = array(
        PRIV_SYSADMIN        => "System Administrator",
        PRIV_NEWSADMIN       => "News Administrator",
        PRIV_RESOURCEADMIN   => "Master Resource Administrator",
        PRIV_MYRESOURCEADMIN => "Personal Resource Administrator",
        PRIV_FORUMADMIN      => "Forum Administrator",
        PRIV_CLASSADMIN      => "Classification Administrator",
        PRIV_NAMEADMIN       => "Controlled Name Administrator",
        PRIV_RELEASEADMIN    => "Release Flag Administrator",
        PRIV_USERADMIN       => "User Account Administrator",
        PRIV_COLLECTIONADMIN => "Collection Administrator",
        # following are user permissions, not admin privileges
        PRIV_POSTTOFORUMS    => "Can Post To Forums",
        PRIV_POSTCOMMENTS    => "Can Post Resource Comments",
        PRIV_USERDISABLED    => "User Account Disabled"
        );
$GLOBALS["G_PrivDescriptions"] = $PrivDescriptions;

# define display locations for RSS feed imports
define("RSSDISP_ALLPAGES",1);
define("RSSDISP_FRONTPAGE",2);
define("RSSDISP_ADMINPAGE",4);
define("RSSDISP_MTOOLPAGE",8);



class ErrorList {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    # object constructor
    function ErrorList()
    {
        $this->Messages = array();
        $this->FormMessages = array();
    }

    function AddMessage($Text, $FormFieldName = NULL)
    {
        if ($FormFieldName)
        {
            $this->FormMessages[$FormFieldName] = $Text;
        }
        else
        {
            $this->Messages[] = $Text;
        }
    }

    function GetMessagesAsUList()
    {
        $Text = "<ul>\n";
        foreach ($this->Messages as $Message)
        {
            $Text .= sprintf("<li>%s</li>\n", $Message);
        }
        foreach ($this->FormMessages as $Message)
        {
            $Text .= sprintf("<li>%s</li>\n", $Message);
        }
        $Text .= "</ul>\n";

        return $Text;
    }

    function HasErrors()
    {
        return (count($this->Messages) + count($this->FormMessages)) ? true : false;
    }

    function GetMessageForField($FormFieldName)
    {
        if (isset($this->FormMessages[$FormFieldName]))
        {
            return $this->FormMessages[$FormFieldName];
        }
        else
        {
            return NULL;
        }
    }


    # ---- PRIVATE INTERFACE -------------------------------------------------

    var $Messages;
    var $FormMessages;

}

# load system, session, and user information
$DB        = new Database();
$SysConfig = new SystemConfiguration($DB);
$G_SysConfig = $SysConfig;
$Session   = new Session($DB);
$User      = new CWUser();
$G_User    = $User;
if ($G_User->IsLoggedIn())
{
    $G_User->LastLocation(isset($_GET["P"]) ? $_GET["P"]
            : basename($_SERVER["SCRIPT_FILENAME"]));
}

# set whether to prefer HTTP_HOST using the system configuration setting
ApplicationFramework::PreferHttpHost($G_SysConfig->PreferHttpHost());

# set the root URL override using the system configuration setting
ApplicationFramework::RootUrlOverride($G_SysConfig->RootUrlOverride());

# initialize mail delivery settings
Email::DeliverySettings($G_SysConfig->Value("EmailDeliverySettings"));
Email::DefaultFrom(trim($GLOBALS["G_SysConfig"]->PortalName())
        ." <".trim($GLOBALS["G_SysConfig"]->AdminEmail()).">");

# initialize e-mail line ending from the configuration
function InitializeEmailLineEnding($SysConfig)
{
    $LineEndings = array("CRLF" => "\r\n", "CR" => "\r", "LF" => "\n");
    $LineEndingSetting = $SysConfig->EmailLineEnding();

    # use the setting from the configuration if valid
    if (isset($LineEndings[$LineEndingSetting]))
    {
        Email::LineEnding($LineEndings[$LineEndingSetting]);
    }

    # otherwise default to CRLF
    else
    {
        Email::LineEnding($LineEndings["CRLF"]);
    }
}
InitializeEmailLineEnding($G_SysConfig);

# set standard field mappings
function SetStandardFieldMappings($SysConfig)
{
    if (MetadataSchema::SchemaExistsWithId(MetadataSchema::SCHEMAID_DEFAULT))
    {
        $StandardFieldNames = array("Title", "Description", "Url", "Screenshot", "File");
        $Schema = new MetadataSchema(MetadataSchema::SCHEMAID_DEFAULT);
        foreach ($StandardFieldNames as $StdFieldName)
        {
            $SysConfigField = $StdFieldName."Field";
            $FieldId = $SysConfig->Value($SysConfigField);
            if ($FieldId == -2147483647)
            {
                $Field = $Schema->GetFieldByName($StdFieldName);
                if ($Field !== NULL)
                {
                    $SysConfig->Value($SysConfigField, $Field->Id());
                    MetadataSchema::StdNameToFieldMapping($StdFieldName, $Field->Id());
                }
            }
            else
            {
                MetadataSchema::StdNameToFieldMapping($StdFieldName, $FieldId);
            }
        }
    }
}
SetStandardFieldMappings($G_SysConfig);

function CreateTempDirectories()
{
    $Cwd = getcwd();
    $Directories = array("tmp", "tmp/caches");

    foreach ($Directories as $Dir)
    {
        # the directory must have a forward slash in the beginning since the
        # directory from getcwd() will not have a trailing slash
        $Dir = ($Dir{0} != "/") ? "/".$Dir : $Dir;

        $Dir = $Cwd.$Dir;
        if (!is_dir($Dir) && !file_exists($Dir))
        {
            @mkdir($Dir);
        }
        else if (is_dir($Dir) && !is_writable($Dir))
        {
            @chmod($Dir, "a+w");
        }
    }
}
CreateTempDirectories();

# load software version number
if (file_exists("VERSION"))
{
    $VersionArray = file("VERSION");
}
elseif (file_exists("../VERSION"))
{
    $VersionArray = file("../VERSION");
}
else
{
    $SPT_SoftwareVersion = "--";
    $SPT_SoftwareVersionToDisplay = $SPT_SoftwareVersion;
}
if (!isset($SPT_SoftwareVersion))
{
    $SPT_SoftwareVersion = chop($VersionArray[0]);
    $SPT_SoftwareVersionToDisplay = $SPT_SoftwareVersion;
}
define("CWIS_VERSION", $SPT_SoftwareVersion);

# hook any local periodic maintenance functions
if (LocalFunctionExists("HourlyMaintenance"))
{
    $GLOBALS["AF"]->HookEvent("EVENT_HOURLY", "Local_HourlyMaintenance");
}
if (LocalFunctionExists("DailyMaintenance"))
{
    $GLOBALS["AF"]->HookEvent("EVENT_DAILY", "Local_DailyMaintenance");
}
if (LocalFunctionExists("WeeklyMaintenance"))
{
    $GLOBALS["AF"]->HookEvent("EVENT_WEEKLY", "Local_WeeklyMaintenance");
}

# hook saved search mailings to run hourly
$GLOBALS["AF"]->HookEvent("EVENT_HOURLY", "CheckForSavedSearchMailings");
function CheckForSavedSearchMailings()
{
    require_once("include/SavedSearchMailings.php");
    RunSavedSearchMailings();
}
