<?PHP

#
#   Axis--StandardLibrary.php
#   A Collection of Utility Routines
#
#   Copyright 1999-2002 Axis Data
#   This code is free software that can be used or redistributed under the
#   terms of Version 2 of the GNU General Public License, as published by the
#   Free Software Foundation (http://www.fsf.org).
#
#   Author:  Edward Almasy (almasy@axisdata.com)
#
#   Part of the AxisPHP library v1.2.4
#   For more information see http://www.axisdata.com/AxisPHP/
#


# (accepts a date string in the form YYYY-MM-DD and adds or subtracts days)
function CalcDate($DateString, $DaysToAdd)
{
    # parse date string
    $Pieces = explode("-", $DateString);

    # convert to value of date in seconds (a la Unix timestamp)
    $DateInSeconds = mktime(1, 1, 1, $Pieces[1], $Pieces[2], $Pieces[0]);

    # perform date arithmetic
    $DateInSeconds = $DateInSeconds + ($DaysToAdd * (60 * 60 * 24));

    # return YYYY-MM-DD date string to caller
    return date("Y-m-d", $DateInSeconds);
}

function GetHtmlEscapedString($String)
{
    return htmlentities(stripslashes($String));
}

function GetUnHtmlEscapedString($String)
{
    $TranslationTable = get_html_translation_table(HTML_ENTITIES);
    $TranslationTable = array_flip($TranslationTable);
    return strtr($String, $TranslationTable);
}

function HtmlSafePrint($String)
{
    print(GetHtmlEscapedString($String));
}

function PrintAutoRefreshPage($Title, $NewUrl)
{
    </script>

        <html>
        <head>
            <title><?php  printf("%s", $Title);  ?></title>
            <meta http-equiv="refresh" content="0; URL=<?php  print($NewUrl);  ?>">
        </head>
        <body bgcolor="white">
        </body>
        </html>

    <script language="php">
}

function GetOrdinalSuffix($Number)
{
    if (($Number > 10) && ($Number < 20))
    {
        $Suffix = "th";
    }
    else
    {
        $Digit = $Number % 10;
        if ($Digit == 1)
        {
            $Suffix = "st";
        }
        elseif ($Digit == 2)
        {
            $Suffix = "nd";
        }
        elseif ($Digit == 3)
        {
            $Suffix = "rd";
        }
        else
        {
            $Suffix = "th";
        }
    }

    return $Suffix;
}

function GetOrdinalNumber($Number)
{
    return $Number.GetOrdinalSuffix($Number);
}

function GetMonthName($MonthNumber)
{
    $MonthNames = array(
            1 => "January",
            2 => "February",
            3 => "March",
            4 => "April",
            5 => "May",
            6 => "June",
            7 => "July",
            8 => "August",
            9 => "September",
            10 => "October",
            11 => "November",
            12 => "December");

    return $MonthNames[$MonthNumber];
}

function PrintOptionList($ResultVar, $Items,
                         $SelectedValue = NULL,
                         $SubmitOnChange = "",
                         $Size = 1,
                         $PrintEvenIfEmpty = 1,
                         $MultipleAllowed = false,
                         $OnChangeAction = NULL,
                         $Width = NULL,
                         $DisabledOptions = NULL)
{
    if ((count($Items) > 0) || $PrintEvenIfEmpty)
    {
        # determine forced display width for option list (if needed)
        if ($Width)
        {
            # width given in px
            if (is_numeric($Width))
            {
                $ForcedWidthAttrib = " style=\"width: ".$Width."px;\"";
            }

            # width given with type specifier (%, px, etc)
            else
            {
                $ForcedWidthAttrib = " style=\"width: ".$Width.";\"";
            }
        }
        else
        {
            $Labels = $Items;
            sort($Labels);
            $MatchingCharThreshold = 11;
            $MaxMatchingChars = $MatchingCharThreshold;
            foreach ($Labels as $Label)
            {
                if (isset($PreviousLabel))
                {
                    $Len = ($MaxMatchingChars + 1);
                    while (substr($Label, 0, $Len) ==
                           substr($PreviousLabel, 0, $Len)
                           && ($Len < strlen($Label)))
                    {
                        $MaxMatchingChars = $Len;
                        $Len++;
                    }
                }
                $PreviousLabel = $Label;
            }
            if ($MaxMatchingChars > $MatchingCharThreshold)
            {
                $ExtraCharsToDisplayBeyondMatch = 6;
                $ForcedWidth = $MaxMatchingChars + $ExtraCharsToDisplayBeyondMatch;;
                $ForcedWidthAttrib = " style=\"width: ".$ForcedWidth."ex;\"";
            }
            else
            {
                $ForcedWidthAttrib = " style=\"width: auto;\"";
            }
        }

        # print option list begin
        print("<select name=\"".$ResultVar."\""
              ." size=\"".$Size."\""
              ." id=\"".$ResultVar."\""
              .($SubmitOnChange ? " onChange=\"submit()\"" : "")
              .($OnChangeAction ? " onChange=\"".$OnChangeAction."\"" : "")
              .($MultipleAllowed ? " multiple" : "")
              .$ForcedWidthAttrib
              .">\n");

        # for each element in list
        reset($Items);
        while (list($Value, $Label) = each($Items))
        {
            # print option list item
            printf("    <option value=\"%s\"", htmlspecialchars($Value));
            if ((is_array($SelectedValue) && in_array($Value, $SelectedValue))
                    || ($Value == $SelectedValue)) {  printf(" selected");  }
            if ( !is_null($DisabledOptions)
                 && isset($DisabledOptions[$Label]))
            {
                printf(" disabled");
            }
            printf(">%s</option>\n", GetHtmlEscapedString($Label));
        }

        # print option list end
        printf("</select>\n");
    }
}

function PrintOptionListsOfDateComponents($FieldPrefix, $AllowNullDate = 0, $Year = -1, $Month = -1, $Day = -1, $SubmitOnChange = "")
{
    # if no date passed in
    if (($Year == -1) && ($AllowNullDate))
    {
        # if null date allowed
        if ($AllowNullDate)
        {
            # use null date
            $Year = 0;
            $Month = 0;
            $Day = 0;
        }
        else
        {
            # use current date
            $Year = date("Y");
            $Month = date("n");
            $Day = date("j");
        }
    }

    # if date string passed in
    if ((strlen($Year) > 4) && ($Month == -1))
    {
        # split into component parts
        list($Year, $Month, $Day) = split("[-/]", $Year);
    }

    # print option list for months if month value supplied
    if ($Month != -1)
    {
        $Index = 1;
        print("\n    <select name=\"".$FieldPrefix."Month\""
              ." id=\"".$FieldPrefix."Month\""
              .($SubmitOnChange ? " onChange='submit()'" : "")
              .">\n");
        if ($AllowNullDate)
        {
            print("<option value='0'>--</option>\n");
        }
        while ($Index <= 12)
        {
            if ($Index == $Month)
            {
                printf("        <option value='%s' selected>%s</option>\n", $Index, GetMonthName($Index));
            }
            else
            {
                printf("        <option value='%s'>%s</option>\n", $Index, GetMonthName($Index));
            }
            $Index++;
        }
        printf("    </select>\n");
    }

    # print option list for days if day value supplied
    if ($Day != -1)
    {
        $Index = 1;
        print("\n    <select name=\"".$FieldPrefix."Day\""
              ." id=\"".$FieldPrefix."Day\""
              .($SubmitOnChange ? " onChange='submit()'" : "")
              .">\n");
        if ($AllowNullDate)
        {
            print("<option value='0'>--</option>\n");
        }
        while ($Index <= 31)
        {
            if ($Index == $Day)
            {
                printf("        <option value='%s' selected>%s</option>\n", $Index, GetOrdinalNumber($Index));
            }
            else
            {
                printf("        <option value='%s'>%s</option>\n", $Index, GetOrdinalNumber($Index));
            }
            $Index++;
        }
        printf("    </select>\n");
    }

    # print option list for years
    $Index = date("Y") - 45;
    $EndIndex = $Index + 45;
    print("\n    <select name=\"".$FieldPrefix."Year\""
          ." id=\"".$FieldPrefix."Year\""
          .($SubmitOnChange ? " onChange='submit()'" : "")
          .">\n");
    if ($AllowNullDate)
    {
        print("<option value='0'>--</option>\n");
    }
    while ($Index <= $EndIndex)
    {
        if ($Index == $Year)
        {
            printf("        <option value=\"%s\" selected>%s</option>\n", $Index, $Index);
        }
        else
        {
            printf("        <option value=\"%s\">%s</option>\n", $Index, $Index);
        }
        $Index++;
    }
    printf("    </select>\n");
}

function PrintOptionListsOfTimeComponents($FieldPrefix, $Hour = -1, $Minute = -1)
{
    # use current date if no date passed in
    if ($Hour == -1)
    {
        $Hour = date("G");
        $Minute = date("i");
    }

    # print option list for hours if hour value supplied
    $Index = 0;
    print("\n    <select name=\"".$FieldPrefix."Hour\" id=\"".$FieldPrefix."Hour\">\n");
    while ($Index < 24)
    {
        if ($Index == $Hour)
        {
            printf("        <option value='%s' selected>%d</option>\n", $Index, $Index);
        }
        else
        {
            printf("        <option value='%s'>%d</option>\n", $Index, $Index);
        }
        $Index++;
    }
    printf("    </select>\n");

    # print option list for minutes if minute value supplied
    if ($Minute != -1)
    {
        $Index = 0;
        print("\n    <select name=\"".$FieldPrefix."Minute\" id=\"".$FieldPrefix."Minute\">\n");
        while ($Index < 60)
        {
            if ($Index == $Minute)
            {
                printf("        <option value='%s' selected>%02d</option>\n", $Index, $Index);
            }
            else
            {
                printf("        <option value='%s'>%02d</option>\n", $Index, $Index);
            }
            $Index++;
        }
        printf("    </select>\n");
    }
}

function LongestStringLineLength($String)
{
    # split string on newlines
    $Pieces = explode("\n", $String);

    # for each line in string
    $MaxLen = 0;
    for ($Index = 0;  $Index < count($Pieces);  $Index++)
    {
        # save length if longer than current max
        if (strlen($Pieces[$Index]) > $MaxLen)
        {
            $MaxLen = strlen($Pieces[$Index]);
        }
    }

    # return length of longest segment to caller
    return $MaxLen;
}

function PrintOptionListFromDB($DB, $Table, $Condition, $SortBy, $ResultVar, $ValueQuery, $LabelQuery, $SelectedValue, $Size = 1, $SubmitOnChange = "", $PrintEvenIfEmpty = 0)
{
    # set up condition and sorting parameters
    if ($Condition != "") {  $Condition = "WHERE ".$Condition;  }
    if ($SortBy != "") {  $SortBy = "ORDER BY ".$SortBy;  }

    # grab records to be listed from database
    $QueryString = sprintf("SELECT * FROM %s %s %s",
            $Table, $Condition, $SortBy);
    $DB->Query($QueryString);

    # if records were found
    if ($DB->NumRowsSelected() > 0)
    {
        # build array of items
        while ($Row = $DB->FetchRow())
        {
            $Items[$Row[$ValueQuery]] = $Row[$LabelQuery];
        }

        # sort array if not already sorted
        if ($SortBy == "") {  asort($Items);  }
    }

    # print option list
    PrintOptionList($ResultVar, $Items, $SelectedValue, $SubmitOnChange, $Size, $PrintEvenIfEmpty);
}


?>
