<?php
/**
 * A test script to troubleshoot time issues. Drop it in the Mahara /htdocs directory
 * and access it via the web browser.
 *
 * @package    mahara
 * @author     Aaron Wells, Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  Catalyst IT, 2015
 */

define('INTERNAL', 1);
require_once('init.php');
require_once($CFG->docroot.'/lib/ddl.php');

echo "<pre>";
// new table collection
$table = new XMLDBTable('timetest');
$table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
$table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
$table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
if (!table_exists($table)) {
    echo "Creating timetest table\n";
    create_table($table);
}
else {
    echo "Timetest table already exists\n";
}
echo "\n";

$time = time();
$epoch1 = $time;
echo "DB version: " . get_field_sql('select version()') . "\n";
if (is_postgres()) {
    echo "DB timezone: " . get_field_sql("select current_setting('timezone')") . "\n";
}
if (is_mysql()) {
    echo "DB timezone: " . get_field_sql("SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone)") . "\n";
}
echo "PHP version: " . phpversion() . "\n";
echo "PHP timezone: " . date_default_timezone_get() . "\n";
echo "\n";

echo "1. Time from time(): {$time}\n";
$time = db_format_timestamp($time);
echo "2. Passed to db_format_timestamp(): {$time}\n";
$id = insert_record('timetest', (object)array('ctime' => $time), 'id', true);
echo "Inserted into DB (id {$id})\n";
$time = get_field('timetest', 'ctime', 'id', $id);
echo "3. Date from DB (should be the time in current timezone): {$time}\n";
$time = get_field('timetest', db_format_tsfield('ctime'), 'id', $id);
$epoch2 = $time;
echo "4. Epoch from DB " . db_format_tsfield('ctime'). ": {$time}\n";
if ($epoch1 != $epoch2) {
    $diff = ($epoch2 - $epoch1)/60/60;
    echo "    This is ahead by {$diff} hours from time()!\n";
}
$time = strftime(get_string('strftimedatetime'), $time);
echo "5. Time from strftime(" . get_string('strftimedatetime') . "): {$time}\n";