#!/usr/bin/php
<?php
# -*- Mode: php -*-
/*
 * Copyright 2005 - 2015  Zarafa B.V.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3, 
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *  
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

include('mapi/mapi.util.php');
include('mapi/mapidefs.php');
include('mapi/mapicode.php');
include('mapi/mapitags.php');
include('mapi/mapiguid.php');

include('mapi/class.meetingrequest.php');
include('mapi/class.baserecurrence.php');
include('mapi/class.recurrence.php');
include('mapi/class.freebusypublish.php');

define('RECURRENCE_AVAILABILITY_RANGE', 60 * 60 * 24 * 180); // 180 days

$DEBUG = 1;

function parseConfig($configfile)
{
    $fp = fopen($configfile, "rt");
    if(!$fp)
        return false;
        
    $settings = array();
    
    while($line = fgets($fp)) {
        if($line[0] == '#')
            continue;
        
        $pos = strpos($line, "=");
        if($pos) {
            $key = trim(substr($line, 0, $pos));
            $value = trim(substr($line, $pos+1));
            
            $settings[$key] = $value;
        }
    }

    return $settings;
}

function u2w($s)
{
    return $s;
}

if(!function_exists('hex2bin')){
    function hex2bin($data)
    {
       return pack("H*", $data);
    }
}

function debugLog($message)
{
    global $DEBUG;
    
    if($DEBUG) {
        print($message);
    }
}

/**
* Auto-process a meeting request, response or cancellation
*/
function autoProcess($session, $store, $entryid)
{
    debugLog("Processing item with entryid " . bin2hex($entryid) . "\n");
    $message = mapi_msgstore_openentry($store, $entryid);
    
    if(!$message) {
        debugLog("Unable to open item with entryid " . bin2hex($entryid) . "\n");
        return false;
    }
    
    $mr = new Meetingrequest($store, $message, $session);
    
    if($mr->isMeetingRequest()) {
        // Check general policy settings
        $mr->doAccept(true, false, false);
        return true;
    } else if($mr->isMeetingRequestResponse()) {
		$mr->processMeetingRequestResponse();
		return true;
	} else if($mr->isMeetingCancellation()) {
        $mr->processMeetingCancellation();
        return true;
    }
}

// Since the username we are getting from the commandline is always in utf8, we have
// to force LC_CTYPE to an UTF-8 language. This makes sure that opening the user's store
// will always open the correct user's store.

forceUTF8(LC_CTYPE);
forceUTF8(LC_MESSAGES);
textdomain("kopano");

if(count($argv) != 4) {
    print "Usage: " . $argv[0] . " <username> <path/to/dagent.cfg> <entryid>\n";
    print
    print "If <entryid> is not specified, all unresponded MRs in the inbox are processed\n";
    exit(1);
}

$username = $argv[1];
$config = $argv[2];
$entryid = $argv[3];

$settings = parseConfig($config);

if(!$settings || !isset($settings["server_socket"])) {
    $settings["server_socket"] = "default:";
}

if(isset($settings["sslkey_file"]) && isset($settings["sslkey_pass"]))
    $session = mapi_logon_zarafa($username, "", $settings["server_socket"], $settings["sslkey_file"], $settings["sslkey_pass"]);
else
    $session = mapi_logon_zarafa($username, "", $settings["server_socket"]);
    
$store = GetDefaultStore($session);

$inbox = mapi_msgstore_getreceivefolder($store);

autoProcess($session, $store, hex2bin($entryid));

$storeprops = mapi_getprops($store, array(PR_MAILBOX_OWNER_ENTRYID));

$fb = new FreeBusyPublish($session, $store, getCalendar($store), $storeprops[PR_MAILBOX_OWNER_ENTRYID]);

$fb->PublishFB(time() - (7 * 24 * 60 * 60), 6 * 30 * 24 * 60 * 60); // publish from one week ago, 6 months ahead

exit(0);

?>
