<?php
// file: inc_util.php
// author: Bill MacAllister
//
// Functions defined here should be completely self-contained and
// not depends on any variables or functions outside of this file.

// Some global constants
$sys_msg_ok   = '<font color="green">';
$sys_msg_warn = '<font color="red">';
$sys_msg_end  = "</font><br/>\n";

$DATE_PATTERN = '/^(\d+)[-:](\d+)[-:](\d+)(\s|-|:)(\d+)[-:](\d+)[-:](\d+)/';
$DATE_FORMAT  = '%04d-%02d-%02d %02d:%02d:%02d';

//-------------------------------------------------------------
// Calculate the size of a picture that will be contained within
// the bounding box $max_x, $max_y.  Change the image size only
// if it is too big for the box.

function calc_size ($max_x, $max_y, $width, $height) {
    $new_x  = $width;
    $new_y  = $height;

    if ($new_x > $max_x) {
        $new_y = intval(($max_x / $new_x) * $new_y);
        $new_x = $max_x;
    }
    if ($new_y > $max_y) {
        $new_x = intval(($max_y / $new_y) * $new_x);
        $new_y = $max_y;
    }
    return array($new_x, $new_y);
}

//-------------------------------------------------------------
// get a value from the REQUEST array if it exists

function get_request ($idx, $default = NULL) {
    if (array_key_exists($idx, $_REQUEST)) {
        $val = $_REQUEST[$idx];
    } else {
        if ($default !== '') {
            $val = $default;
        } else {
            $val = '';
        }
    }
    return $val;
}

//-------------------------------------------------------------
// printable date time

function format_date_time ($in) {

    $ret_date = $in;

    if (preg_match("/(\d{4,4}).(\d{2,2}).(\d{2,2}).(\d{2,2}.\d{2,2}.*)/",
                   $in,
                   $matches)) {
        $a_yr   = $matches[1];
        $a_mon  = $matches[2];
        $a_day  = $matches[3];
        $a_time = $matches[4];
        $ret_mon = $a_mon;
        if ($a_mon == 1) {$ret_mon = "Jan";}
        elseif ($a_mon == 2) {$ret_mon = "Feb";}
        elseif ($a_mon == 3) {$ret_mon = "Mar";}
        elseif ($a_mon == 4) {$ret_mon = "Apr";}
        elseif ($a_mon == 5) {$ret_mon = "May";}
        elseif ($a_mon == 6) {$ret_mon = "Jun";}
        elseif ($a_mon == 7) {$ret_mon = "Jul";}
        elseif ($a_mon == 8) {$ret_mon = "Aug";}
        elseif ($a_mon == 9) {$ret_mon = "Sep";}
        elseif ($a_mon == 10) {$ret_mon = "Oct";}
        elseif ($a_mon == 11) {$ret_mon = "Nov";}
        elseif ($a_mon == 12) {$ret_mon = "Dec";}
        $ret_date = "$a_day-$ret_mon-$a_yr";

        $ret_time = $a_time;
        $ret_time = str_replace ('.000', '', $ret_time);
        $ret_time = str_replace ('00:00:00', '', $ret_time);

    }

    return $ret_date.'&nbsp;'.$ret_time;
}

//-------------------------------------------------------------
// Redirect the user to the home page

function http_redirect ($nextURL="index.php") {
    header ("REFRESH: 0; URL=$nextURL");
    echo "<html>\n";
    echo "<head>\n";
    echo "<title>Rings</title>\n";
    echo "</head>\n";
    echo "<body>\n";
    echo "<h1><a href=\"$nextURL\">Rings</a></h1>\n";
    echo "</body>\n";
    echo "</html>\n";
    exit;
}

//-------------------------------------------------------------
// -- Increment the time part of a datetime.  Don't do anything if we
//    need to goto the next day.
function increment_time ($a_datetime) {

    global $DATE_FORMAT;
    global $DATE_PATTERN;

    if (preg_match($DATE_PATTERN, $a_datetime, $matches)) {
        $a_year   = $matches[1];
        $a_month  = $matches[2];
        $a_day    = $matches[3];
        $a_hour   = $matches[5];
        $a_minute = $matches[6];
        $a_second = $matches[7];
        $a_second += 10;
        if ($a_second > 59) {
            $a_second = 0;
            $a_minute++;
        }
        if ($a_minute > 59) {
            $a_minute = 0;
            $a_hour++;
        }
        if ($a_hour < 24) {
            $return_datetime = sprintf($DATE_FORMAT,
                                       $a_year,
                                       $a_month,
                                       $a_day,
                                       $a_hour,
                                       $a_minute,
                                       $a_second);
        }
        return $return_datetime;
    }
    return;
}

//-------------------------------------------------------------
// Read an attribute=value configuation file, store the results
// in an array and return the array.

function read_conf ($conf_file = '/etc/rings/rings.conf') {

    # Bail out if we can find the file
    if (! file_exists($conf_file)) {
        return;
    }

    # Open the file and read it line by line
    $this_conf = array();
    $fh = fopen($conf_file, 'r');
    if (!$fh) {
        syslog(LOG_ERR, "ERROR: reading $conf_file");
        exit("Problem opening $conf_file");
    }
    while (($line = fgets($fh)) != false) {
        if (substr($line, 0, 1) == '#') {
            continue;
        }
        if (preg_match('/^(\S+)\s*=\s*(.*)/', $line, $part)) {
            $this_conf[trim($part[1])] = trim($part[2]);
        }
    }
    fclose($fh);
    return $this_conf;
}

// ------------------------------------------------------------------------
// Message helper routines

function msg_okay ($txt) {
    global $sys_msg_ok;
    global $sys_msg_end;
    return "${sys_msg_ok}${txt}${sys_msg_end}";
}

function msg_err ($txt) {
    global $sys_msg_warn;
    global $sys_msg_end;
    return "${sys_msg_warn}ERROR: ${txt}${sys_msg_end}";
}

function sys_msg ($txt) {
    global $sys_msg_ok;
    global $sys_msg_end;
    $_SESSION['msg'] .= "${sys_msg_ok}${txt}${sys_msg_end}";
    syslog(LOG_INFO, $txt);
    return;
}

function sys_err ($txt) {
    global $sys_msg_warn;
    global $sys_msg_end;
    $_SESSION['msg'] .= "${sys_msg_warn}ERROR: ${txt}${sys_msg_end}";
    syslog(LOG_ERR, $txt);
    return;
}

function sys_display_msg () {
    if (!empty($_SESSION['msg'])) {
        echo $_SESSION['msg'];
    }
    $_SESSION['msg'] = '';
    return;
}

// ------------------------------------------------------------------------
// Assemble the path to a picture

function picture_path ($lot, $size_id, $pid, $file_type) {

    global $CONF;

    if (empty($lot)) {
        sys_err("picture_path missing picture_lot ($lot)");
        return $m;
    }
    list ($a_size_id, $a_size_desc) = validate_size($size_id);
    if (empty($a_size_id)) {
        sys_err("picture_path invalid size_id ($size_id)");
        return $m;
    }
    if ($pid < 1) {
        sys_err('picture_path invalid pid');
        return $m;
    }
    list ($a_file_type, $a_mime_type) = validate_type($file_type);
    if (empty($a_file_type)) {
        sys_err("picture_path invalid file_type ($file_type)");
        return $m;
    }

    $pic_dir = $CONF['picture_root'];
    $pic_dir .= '/' . $lot;
    $pic_dir .= '/' . $a_size_id;

    $pic_file = $pic_dir;
    $pic_file .= '/' . $pid;
    $pic_file .= '.' . $a_file_type;

    return array($pic_dir, $pic_file);
}

// ------------------------------------------------------------------------
// Function to exit without displaying anything and return to the main
// index page.

function back_to_index ($msg) {

    if (!empty($msg)) {
        sys_msg($msg);
    }
    echo "<html>\n";
    echo "<head>\n";
    echo "<meta http-equiv=\"refresh\" ";
    echo '    content="0; URL=http://'.$_SERVER['SERVER_NAME'].'/rings">'."\n";
    echo "<title>Rings of Pictures</title>\n";
    echo "</head>\n";
    echo "<body>\n";
    echo '<a href="rings">Rings of Pictures</a>'."\n";
    echo "</body>\n";
    echo "</html>\n";

    exit;
}

?>
