#!/usr/bin/env php
# -*- Mode: php -*-

<?php
/*
 * Copyright 2005 - 2014  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 with the following additional 
 * term according to sec. 7:
 *  
 * According to sec. 7 of the GNU Affero General Public License, version
 * 3, the terms of the AGPL are supplemented with the following terms:
 * 
 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
 * the Program under the AGPL does not imply a trademark license.
 * Therefore any rights, title and interest in our trademarks remain
 * entirely with us.
 * 
 * However, if you propagate an unmodified version of the Program you are
 * allowed to use the term "Zarafa" to indicate that you distribute the
 * Program. Furthermore you may use our trademarks where it is necessary
 * to indicate the intended purpose of a product or service provided you
 * use it in accordance with honest practices in industrial or commercial
 * matters.  If you want to propagate modified versions of the Program
 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
 * have a written permission by Zarafa B.V. (to acquire a permission
 * please contact Zarafa at trademark@zarafa.com).
 * 
 * The interactive user interface of the software displays an attribution
 * notice containing the term "Zarafa" and/or the logo of Zarafa.
 * Interactive user interfaces of unmodified and modified versions must
 * display Appropriate Legal Notices according to sec. 5 of the GNU
 * Affero General Public License, version 3, when you propagate
 * unmodified or modified versions of the Program. In accordance with
 * sec. 7 b) of the GNU Affero General Public License, version 3, these
 * Appropriate Legal Notices must retain the logo of Zarafa or display
 * the words "Initial Development by Zarafa" if the display of the logo
 * is not reasonably feasible for technical reasons. The use of the logo
 * of Zarafa in Legal Notices is allowed for unmodified and modified
 * versions of the software.
 * 
 * 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('/usr/share/php/mapi/mapi.util.php');
include('/usr/share/php/mapi/mapidefs.php');
include('/usr/share/php/mapi/mapicode.php');
include('/usr/share/php/mapi/mapitags.php');
include('/usr/share/php/mapi/mapiguid.php');

include('/usr/share/php/mapi/class.meetingrequest.php');
include('/usr/share/php/mapi/class.recurrence.php');
include('/usr/share/php/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);
    }
}

/**
* Get the default store for this session
*/
function getDefaultStore($session)
{
    $msgstorestable = mapi_getmsgstorestable($session);

    $msgstores = mapi_table_queryallrows($msgstorestable, array(PR_DEFAULT_STORE, PR_ENTRYID));

    foreach ($msgstores as $row) {
        if($row[PR_DEFAULT_STORE]) {
            $storeentryid = $row[PR_ENTRYID];
        }
    }

    if(!$storeentryid) {
        print "Can't find default store\n";
        return false;
    }

    $store = mapi_openmsgstore($session, $storeentryid);
    
    return $store;
}

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

/**
* Auto-process a meeting request, response or cancellation
*/
function autoProcess($session, $store, $entryid, $capacity, $policy)
{
    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;
    }
}

function forceUTF8($category)
{
    $old_locale = setlocale($category, "");
    if(!isset($old_locale) || !$old_locale) {
        print "Unable to initialize locale\n";
        exit(1);
    }
    $dot = strpos($old_locale, ".");
    if($dot) {
        if(strrchr($old_locale, ".") == ".UTF-8" || strrchr($old_locale, ".") == ".utf8")
            return true;
        $old_locale = substr($old_locale, 0, $dot);
    }
    $new_locale = $old_locale . ".UTF-8";
    $old_locale = setlocale($category, $new_locale);
    if(!$old_locale) {
        $new_locale = "en_US.UTF-8";
        $old_locale = setlocale($category, $new_locale);
    }
    if(!$old_locale) {
        print "Unable to set locale $new_locale\n";
        exit(1);
    }
    
    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("zarafa");

if(count($argv) != 4) {
    print "Usage: " . $argv[0] . " <username> <path/to/dagent.cfg> <entryid>\n";
    print
    print "If <entryid> is not specified, all unresponded MR's 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"] = "file:///var/run/zarafa";
}

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), $capacity, $policy);

$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);

?>
