This file is indexed.

/usr/sbin/kopano-mr-accept is in kopano-dagent 8.5.5-0ubuntu1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#!/usr/bin/php
<?php
# -*- Mode: 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.
 * 
 * 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('POLICY_PROCESS_MEETING_REQUESTS',				0x0001);
define('POLICY_DECLINE_RECURRING_MEETING_REQUESTS',		0x0002);
define('POLICY_DECLINE_CONFLICTING_MEETING_REQUESTS', 	0x0004);

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

/**
* Sorts by timestamp, if equal, then end before start. Used by getOverlapDepth()
*/
function cmp($a, $b)
{
    if ($a["time"] == $b["time"]) {
        if($a["type"] < $b["type"])
            return 1;
        if($a["type"] > $b["type"])
            return -1;
        return 0;
    }
    return ($a["time"] > $b["time"] ? 1 : -1);
} 

/**
* Get the overlap depth of the passed items.
*
* This function calculates the maximum number of overlapping appointments at any one time
* for all the passed appointments, disregarding 'free' appointments. 
*/
function getOverlapDepth($items, $proptags, $goid2)
{
    $timestamps = Array();
    $cbusy = Array();
    $level = 0;
    $maxlevel = 0;

    foreach($items as $item)
    {
        // Disregard 'free' items and the item that we are updating
        if($item[$proptags['busystatus']] > 0 && $item[$proptags['goid2']] != $goid2) {
            $ts["type"] = 0;
            $ts["time"] = $item[$proptags["startdate"]];
            $timestamps[] = $ts;

            $ts["type"] = 1;
            $ts["time"] = $item[$proptags["duedate"]];
            $timestamps[] = $ts;
        }
    } 

    usort($timestamps, "cmp");

    foreach($timestamps as $ts)
    {
        switch ($ts["type"])
        {
            case 0: // Start
                $level++;
                $maxlevel = max($level, $maxlevel);
                break;
            case 1: // End
                $level--;
                break;
        } 
    } 

    return $maxlevel;
} 

/**
* Get unresponded items from the specified folder
*
* Looks for messages which have PR_RESPONSE_REQUESTED = TRUE, but no PR_PROCESSED = TRUE and have
* class IPM.Meeting.Req.*
*/
function getUnresponded($folder)
{
    $contents = mapi_folder_getcontentstable($folder);
    
    $restriction = Array(RES_OR, 
                            Array(
                                Array(RES_AND,
                                        Array(
                                            Array(RES_PROPERTY, Array(RELOP => RELOP_EQ, ULPROPTAG => PR_MESSAGE_CLASS, VALUE => 'IPM.Schedule.Meeting.Request') ),
                                            Array(RES_PROPERTY, Array(RELOP => RELOP_EQ, ULPROPTAG => PR_RESPONSE_REQUESTED, VALUE => true ) ),
                                            Array(RES_PROPERTY, Array(RELOP => RELOP_NE, ULPROPTAG => PR_PROCESSED, VALUE => true ) )
                                        )
                                ),
                                Array(RES_AND,
                                        Array(
                                            Array(RES_PROPERTY, Array(RELOP => RELOP_EQ, ULPROPTAG => PR_MESSAGE_CLASS, VALUE => 'IPM.Schedule.Meeting.Canceled') ),
                                            Array(RES_PROPERTY, Array(RELOP => RELOP_NE, ULPROPTAG => PR_PROCESSED, VALUE => true ) )
                                        )
                                )
                            )
                    );
                        
    $rows = mapi_table_queryallrows($contents, Array(PR_ENTRYID), $restriction);
    
    $entryids = array();
    
    foreach ($rows as $row) {
        $entryids[] = $row[PR_ENTRYID];
    }
    
    return $entryids;
}

/**
* Get the capacity of the resource store
*
* For rooms, the capacity is always 1. For equipment the capacity is 1 if
* PR_EMS_AB_ROOM_CAPACITY does not exist, otherwise it is equal to
* PR_EMS_AB_ROOM_CAPACITY. Other objects always have a capacity of 1.
*/
function getCapacity($session, $store)
{
    $storeprops = mapi_getprops($store, array(PR_MAILBOX_OWNER_ENTRYID));
    $ab = mapi_openaddressbook($session);
    
    $mailuser = mapi_ab_openentry($ab, $storeprops[PR_MAILBOX_OWNER_ENTRYID]);
    
    $props = mapi_getprops($mailuser, array(PR_EMS_AB_ROOM_CAPACITY, PR_DISPLAY_TYPE_EX));
    
    if(!isset($props[PR_EMS_AB_ROOM_CAPACITY]) || $props[PR_EMS_AB_ROOM_CAPACITY] <= 0 || !isset($props[PR_DISPLAY_TYPE_EX]) || $props[PR_DISPLAY_TYPE_EX] != DT_EQUIPMENT) {
        $capacity = 1;
    } else {
        $capacity = $props[PR_EMS_AB_ROOM_CAPACITY];
    }
    
    return $capacity;
}

/**
* Get local freebusy message for this store
*/
function getLocalFBMessage($store)
{
    $root = mapi_msgstore_openentry($store);
    
    $rootprops = mapi_getprops($root, array(PR_FREEBUSY_ENTRYIDS));
    
    if(!isset($rootprops[PR_FREEBUSY_ENTRYIDS]) || count($rootprops[PR_FREEBUSY_ENTRYIDS]) < 2)
        return false;
        
    $message = mapi_msgstore_openentry($store, $rootprops[PR_FREEBUSY_ENTRYIDS][1]);
    
    return $message;
}

/**
* Get auto-respond policy for a store
*
* Can return POLICY_PROCESS_MEETING_REQUESTS, POLICY_DECLINE_RECURRING_MEETING_REQUESTS and POLICY_DECLINE_CONFLICTING_MEETING_REQUESTS
* in any combination
*
*/
function getPolicy($store)
{
    $localfbmessage = getLocalFBMessage($store);
    
    if(!$localfbmessage) {
        return 0;
    }
    
    $props = mapi_getprops($localfbmessage, array(PR_PROCESS_MEETING_REQUESTS, PR_DECLINE_CONFLICTING_MEETING_REQUESTS, PR_DECLINE_RECURRING_MEETING_REQUESTS));
    
    $flags = 0;
    
    if(isset($props[PR_PROCESS_MEETING_REQUESTS]) && $props[PR_PROCESS_MEETING_REQUESTS])
        $flags |= POLICY_PROCESS_MEETING_REQUESTS;
    if(isset($props[PR_DECLINE_CONFLICTING_MEETING_REQUESTS]) && $props[PR_DECLINE_CONFLICTING_MEETING_REQUESTS])
        $flags |= POLICY_DECLINE_CONFLICTING_MEETING_REQUESTS;
    if(isset($props[PR_DECLINE_RECURRING_MEETING_REQUESTS]) && $props[PR_DECLINE_RECURRING_MEETING_REQUESTS])
        $flags |= POLICY_DECLINE_RECURRING_MEETING_REQUESTS;
        
    return $flags;
}

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

/**
 * Return TRUE if two appointments overlap
 *
 */
function apptOverlap($appt1, $appt2, $proptags)
{
    // If appt1 starts after appt2 has ended, no overlap
    if($appt1[$proptags['startdate']] >= $appt2[$proptags['duedate']]) {
        return false;
    }
    
    // If appt2 starts after appt1 has ended, no overlap
    if($appt2[$proptags['startdate']] >= $appt1[$proptags['duedate']]) {
        return false;
    }

    return true;
}

/**
 * Return the intersection of a list of appointments with one appointment
 *
 * This means that only the appointments in $list that overlap with $appointment
 * are returned in a list
 */
function intersectAppointmentWithList($appointment, $list, $proptags)
{
    $intersect = array();
    
    foreach($list as $item) {
        if(apptOverlap($item, $appointment, $proptags))
            $intersect[] = $item;
    }
    
    return $intersect;
}

/**
* Auto-respond to a meeting request
*
* Looks at the incoming meeting request, checks availability for the resource, and responds accordingly
*/
function autoRespond($session, $store, $entryid, $capacity, $policy)
{
    debugLog("Processing item with entryid " . bin2hex($entryid) . "\n");
    $calendar = getCalendar($store);
    
    if(!$calendar) {
        debugLog("Unable to open calendar.\n");
        return false;
    }
    
    $proptags = getPropIdsFromStrings($store, array(
        'startdate' => "PT_SYSTIME:PSETID_Appointment:0x820d",
        'duedate' => "PT_SYSTIME:PSETID_Appointment:0x820e",
        'busystatus' => "PT_LONG:PSETID_Appointment:0x8205",
        'recurring' => "PT_BOOLEAN:PSETID_Appointment:0x8223",
        'goid2' => "PT_BINARY:PSETID_Meeting:0x23",
        'subject' => PR_SUBJECT
    ));
    
    $request = mapi_msgstore_openentry($store, $entryid);
    
    if(!$request) {
        debugLog("Unable to open item with entryid " . bin2hex($entryid) . "\n");
        return false;
    }
    
    $mr = new Meetingrequest($store, $request, $session);
    
    if($mr->isMeetingRequest()) {
        $props = mapi_getprops($request, $proptags);
        
        // Check general policy settings
        
        if(isset($props[$proptags['recurring']]) && $props[$proptags['recurring']] && ($policy & POLICY_DECLINE_RECURRING_MEETING_REQUESTS)) {
            $mr->doDecline(true, false, false, _("Recurring meetings are not allowed"));
            debugLog("Declined due to recurrence against non-recurring policy.\n");
            return true;
        }
        
        if($policy & POLICY_DECLINE_CONFLICTING_MEETING_REQUESTS) {
            if(isset($props[$proptags['recurring']]) && $props[$proptags['recurring']]) {
                $rec = new Recurrence($store, $request);
                
                // Only check for conflicts in the first X months, otherwise processing would become too
                // complicated.
                $reqitems = $rec->GetItems($props[$proptags['startdate']], $props[$proptags['startdate']] + RECURRENCE_AVAILABILITY_RANGE);
                
                // Get all the possible conflicts in the coming X months
                debugLog('Getting conflicts from ' . strftime('%x %X', $props[$proptags['startdate']]) . '\n');
                debugLog('Getting conflicts to ' . strftime('%x %X', $props[$proptags['startdate']] + RECURRENCE_AVAILABILITY_RANGE) . '\n');
                
                $possibleconflicts = getCalendarItems($store, $calendar, $props[$proptags['startdate']], $props[$proptags['startdate']] + RECURRENCE_AVAILABILITY_RANGE, $proptags);
            } else {
                $reqitems = array($props);
                
                // Only look at possible conflicts during the duration of the item
                $possibleconflicts = getCalendarItems($store, $calendar, $props[$proptags['startdate']], $props[$proptags['duedate']], $proptags);
            }
            
            $conflicts = array();
            
            foreach($reqitems as $reqitem) {
                // Check for conflicting appointments        
                $start = $reqitem[$proptags['startdate']];
                $end = $reqitem[$proptags['duedate']];
                
                debugLog("Checking availability from " . strftime("%x %X", $start) . " to " . strftime("%x %X", $end) . "\n");
                
                $items = intersectAppointmentWithList($reqitem, $possibleconflicts, $proptags);
                
                debugLog("Found " . count($items) . " overlapping records\n");
                
                $currentdepth = getOverlapDepth($items, $proptags, $props[$proptags['goid2']]);
                
                debugLog("Overlap depth is " . $currentdepth . "\n");
                
                if($currentdepth >= $capacity) {
                    $conflicts[] = $reqitem;
                }
            }
            
            if(count($conflicts) > 0) {
                // At least one conflict
                if(count($conflicts) == count($reqitems)) {
                    $body = _("The requested time slot is unavailable");
                } else {
                    $body = _("The requested time slots are unavailble on the following dates:") . "\n\n";
                    
                    foreach($conflicts as $conflict) {
                        $body .= strftime(_("%x %X"), $conflict[$proptags["startdate"]]) . " - " . strftime(_("%x %X"), $conflict[$proptags["duedate"]]) . "\n";
                    }
                }
                
                $mr->doDecline(true, false, false, $body);
                debugLog("Declined due to capacity reached.\n");
                return true;
            }
        }
        
        // Checks passed, book the meeting
        $ceid = $mr->doAccept(false, true, true);
		if ($ceid === false) {
			debugLog("Failed to accept: " . sprintf("0x%X", mapi_last_hresult()) . "\n");
			return false;
		}
		debugLog("Accepted.\n");
		// reopen entry to add self as BCC recipient for ZCP-9901
		$calitem = mapi_msgstore_openentry($store, $ceid);
		if ($calitem) {
			$storeprops = mapi_getprops($store, array(PR_MAILBOX_OWNER_ENTRYID));
			$ab = mapi_openaddressbook($session);
			$mailuser = mapi_ab_openentry($ab, $storeprops[PR_MAILBOX_OWNER_ENTRYID]);
			$recip = mapi_getprops($mailuser, array(PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_DISPLAY_TYPE, PR_DISPLAY_TYPE_EX,
													PR_EMAIL_ADDRESS, PR_ENTRYID, PR_OBJECT_TYPE, PR_SEARCH_KEY, PR_SMTP_ADDRESS));
			$recip[PR_RECIPIENT_ENTRYID] = $recip[PR_ENTRYID];
			$recip[PR_RECIPIENT_FLAGS] = 256 | 1;
			$recip[PR_RECIPIENT_TRACKSTATUS] = 0;
			$recip[PR_RECIPIENT_TYPE] = MAPI_BCC;
			// not setting PidLidAllAttendees, not important
			mapi_message_modifyrecipients($calitem, MODRECIP_ADD, array($recip));
			mapi_savechanges($calitem);
			debugLog("Accept updated.\n");
		} else {
			debugLog("Unable to update accepted item.\n");
		}
        return true;
    } else if($mr->isMeetingCancellation()) {
        $mr->processMeetingCancellation();
        $mr->doRemoveFromCalendar();
        debugLog("Removed canceled meeting\n");
        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);
forceUTF8(LC_TIME);
textdomain("kopano");

if(count($argv) != 3 && 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];
if(isset($argv[3]))
    $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);

$capacity = getCapacity($session, $store);
$policy = getPolicy($store);

debugLog("Policy is " . $policy . "\n");

if(($policy & POLICY_PROCESS_MEETING_REQUESTS) == 0) {
    debugLog("Policy auto-respond not set.\n");
}

debugLog("Resource capacity is $capacity\n");

$inbox = mapi_msgstore_getreceivefolder($store);

if(isset($entryid)) {
    $items = array (hex2bin($entryid));
} else {
    $items = getUnresponded($inbox);
}

debugLog("Found " . count($items) . " items to process\n");

foreach ($items as $item) {
    autoRespond($session, $store, $item, $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);

?>