1<?php
2
3namespace GO\Freebusypermissions;
4
5use go\core\model\User;
6use go\core\orm;
7
8class FreebusypermissionsModule extends \GO\Base\Module{
9
10	/**
11	 * Initialize the listeners for the ActiveRecords
12	 */
13	public static function initListeners(){
14		\GO\Calendar\Model\Event::model()->addListener('load', 'GO\Freebusypermissions\FreebusypermissionsModule', 'has_freebusy_access');
15	}
16
17	public function defineListeners() {
18		User::on(orm\Property::EVENT_MAPPING, static::class, 'onMap');
19	}
20
21	public function autoInstall() {
22		return false;
23	}
24
25	public static function onMap(orm\Mapping $mapping) {
26		$mapping->addHasOne('freebusySettings', model\UserSettings::class, ['id' => 'user_id'], true);
27		return true;
28	}
29
30	public static function hasFreebusyAccess($request_user_id, $target_user_id){
31
32		$fbAcl = FreebusypermissionsModule::getFreeBusyAcl($target_user_id);
33
34
35		return \GO\Base\Model\Acl::getUserPermissionLevel($fbAcl->acl_id, $request_user_id) > 0;
36	}
37
38	public static function loadSettings($settingsController, &$params, &$response, $user) {
39
40		$acl = FreebusypermissionsModule::getFreeBusyAcl($user->id);
41
42		if(!empty($acl))
43			$response['data']['freebusypermissions_acl_id']=$acl->acl_id;
44
45		return parent::loadSettings($settingsController, $params, $response, $user);
46	}
47
48	public static function getFreeBusyAcl($userId){
49
50		$fbAcl = Model\FreeBusyAcl::model()->findSingleByAttribute('user_id', $userId);
51
52		if(!$fbAcl){
53
54			$acl = new \GO\Base\Model\Acl();
55			$acl->ownedBy = $userId;
56			$acl->usedIn = Model\FreeBusyAcl::model()->tableName();
57			$acl->save();
58
59			if($acl){
60				$fbAcl = new Model\FreeBusyAcl();
61				$fbAcl->user_id = $userId;
62				$fbAcl->acl_id = $acl->id;
63				$fbAcl->save();
64			} else {
65				$fbAcl = false;
66			}
67		}
68		return $fbAcl;
69	}
70}
71