Esempio n. 1
0
 public static function EditCalendarEventEntry($arFields = array(), $arUFFields = array(), $arAccessCodes = array(), $params = array())
 {
     global $DB;
     if ($arFields['SECTION']) {
         $arFields['SECTIONS'] = array($arFields['SECTION']);
     }
     $arFields["OWNER_ID"] = $params["userId"];
     $arFields["CAL_TYPE"] = $params["type"];
     // Add author for new event
     //if (!$arFields["ID"] && !empty($arAccessCodes))
     if (!$arFields["ID"]) {
         $arAccessCodes[] = 'U' . $params["userId"];
     }
     $arAccessCodes = array_unique($arAccessCodes);
     $arAttendees = CCalendar::GetDestinationUsers($arAccessCodes);
     if (trim($arFields["NAME"]) === '') {
         $arFields["NAME"] = GetMessage('EC_DEFAULT_EVENT_NAME');
     }
     $arFields['IS_MEETING'] = !empty($arAttendees) && $arAttendees != array($params["userId"]);
     if (isset($arFields['RRULE']) && !empty($arFields['RRULE'])) {
         if (is_array($arFields['RRULE']['BYDAY'])) {
             $arFields['RRULE']['BYDAY'] = implode(',', $arFields['RRULE']['BYDAY']);
         }
     }
     if ($arFields['IS_MEETING']) {
         $arFields['ATTENDEES_CODES'] = $arAccessCodes;
         $arFields['ATTENDEES'] = $arAttendees;
         $arFields['MEETING_HOST'] = $params["userId"];
         $arFields['MEETING'] = array('HOST_NAME' => CCalendar::GetUserName($params["userId"]), 'TEXT' => '', 'OPEN' => false, 'NOTIFY' => true, 'REINVITE' => false);
     } else {
         $arFields['ATTENDEES'] = false;
     }
     $eventId = CCalendar::SaveEvent(array('arFields' => $arFields, 'autoDetectSection' => true));
     if ($eventId > 0) {
         if (count($arUFFields) > 0) {
             CCalendarEvent::UpdateUserFields($eventId, $arUFFields);
         }
         foreach ($arAccessCodes as $key => $value) {
             if ($value == "UA") {
                 unset($arAccessCodes[$key]);
                 $arAccessCodes[] = "G2";
                 break;
             }
         }
         if ($arFields['IS_MEETING'] && !empty($arUFFields['UF_WEBDAV_CAL_EVENT'])) {
             $UF = $GLOBALS['USER_FIELD_MANAGER']->GetUserFields("CALENDAR_EVENT", $eventId, LANGUAGE_ID);
             CCalendar::UpdateUFRights($arUFFields['UF_WEBDAV_CAL_EVENT'], $arAccessCodes, $UF['UF_WEBDAV_CAL_EVENT']);
         }
         $arSoFields = array("ENTITY_TYPE" => SONET_SUBSCRIBE_ENTITY_USER, "ENTITY_ID" => $params["userId"], "USER_ID" => $params["userId"], "=LOG_DATE" => $DB->CurrentTimeFunction(), "TITLE_TEMPLATE" => "#TITLE#", "TITLE" => $arFields["NAME"], "MESSAGE" => '', "TEXT_MESSAGE" => '');
         $dbRes = CSocNetLog::GetList(array("ID" => "DESC"), array("EVENT_ID" => "calendar", "SOURCE_ID" => $eventId), false, false, array("ID"));
         $arCodes = array();
         foreach ($arAccessCodes as $value) {
             if (substr($value, 0, 2) === 'SG') {
                 $arCodes[] = $value . '_K';
             }
             $arCodes[] = $value;
         }
         $arCodes = array_unique($arCodes);
         if ($arRes = $dbRes->Fetch()) {
             CSocNetLog::Update($arRes["ID"], $arSoFields);
             CSocNetLogRights::DeleteByLogID($arRes["ID"]);
             CSocNetLogRights::Add($arRes["ID"], $arCodes);
         } else {
             $arSoFields = array_merge($arSoFields, array("EVENT_ID" => "calendar", "SITE_ID" => SITE_ID, "SOURCE_ID" => $eventId, "ENABLE_COMMENTS" => "Y", "CALLBACK_FUNC" => false));
             $logID = CSocNetLog::Add($arSoFields, false);
             CSocNetLogRights::Add($logID, $arCodes);
         }
     }
 }
Esempio n. 2
0
 public static function SaveEvent($Params)
 {
     $arFields = $Params['arFields'];
     if (self::$type && !isset($arFields['CAL_TYPE'])) {
         $arFields['CAL_TYPE'] = self::$type;
     }
     if (self::$bOwner && !isset($arFields['OWNER_ID'])) {
         $arFields['OWNER_ID'] = self::$ownerId;
     }
     if (!isset($arFields['SKIP_TIME']) && isset($arFields['DT_SKIP_TIME'])) {
         $arFields['SKIP_TIME'] = $arFields['DT_SKIP_TIME'] == 'Y';
     }
     $userId = isset($Params['userId']) ? $Params['userId'] : self::GetCurUserId();
     $sectionId = is_array($arFields['SECTIONS']) && count($arFields['SECTIONS']) > 0 ? $arFields['SECTIONS'][0] : 0;
     $bPersonal = self::IsPersonal($arFields['CAL_TYPE'], $arFields['OWNER_ID'], $userId);
     // Fetch current event
     // Fetch current event
     $oCurEvent = false;
     $bNew = !isset($arFields['ID']) || !$arFields['ID'];
     if (!$bNew) {
         $oCurEvent = CCalendarEvent::GetList(array('arFilter' => array("ID" => intVal($arFields['ID']), "DELETED" => "N"), 'parseRecursion' => false, 'fetchAttendees' => $Params['bSilentAccessMeeting'] === true, 'fetchMeetings' => false, 'userId' => $userId));
         if ($oCurEvent) {
             $oCurEvent = $oCurEvent[0];
         }
         $bPersonal = $bPersonal && self::IsPersonal($oCurEvent['CAL_TYPE'], $oCurEvent['OWNER_ID'], $userId);
         $arFields['CAL_TYPE'] = $oCurEvent['CAL_TYPE'];
         $arFields['OWNER_ID'] = $oCurEvent['OWNER_ID'];
         $arFields['CREATED_BY'] = $oCurEvent['CREATED_BY'];
         $arFields['ACTIVE'] = $oCurEvent['ACTIVE'];
         $bChangeMeeting = $arFields['CAL_TYPE'] != 'user' && CCalendarSect::CanDo('calendar_edit', $oCurEvent['SECT_ID'], self::$userId);
         if (!isset($arFields['DT_FROM_TS']) && !isset($arFields['DT_FROM'])) {
             $arFields['DT_FROM_TS'] = $oCurEvent['DT_FROM_TS'];
         }
         if (!isset($arFields['DT_TO_TS']) && !isset($arFields['DT_TO'])) {
             if (isset($arFields['DT_FROM_TS'])) {
                 $arFields['DT_TO_TS'] = $arFields['DT_FROM_TS'] + $oCurEvent['DT_LENGTH'];
                 if ($arFields['SKIP_TIME']) {
                     $arFields['DT_TO_TS'] -= self::GetDayLen();
                 }
             } else {
                 $arFields['DT_TO_TS'] = $oCurEvent['DT_TO_TS'];
             }
         }
         if (!isset($arFields['NAME'])) {
             $arFields['NAME'] = $oCurEvent['NAME'];
         }
         if (!isset($arFields['DESCRIPTION'])) {
             $arFields['DESCRIPTION'] = $oCurEvent['DESCRIPTION'];
         }
         if (!isset($arFields['COLOR']) && $oCurEvent['COLOR']) {
             $arFields['COLOR'] = $oCurEvent['COLOR'];
         }
         if (!isset($arFields['TEXT_COLOR']) && $oCurEvent['TEXT_COLOR']) {
             $arFields['TEXT_COLOR'] = $oCurEvent['TEXT_COLOR'];
         }
         if (!isset($arFields['SECTIONS'])) {
             $arFields['SECTIONS'] = array($oCurEvent['SECT_ID']);
             $sectionId = is_array($arFields['SECTIONS']) && count($arFields['SECTIONS']) > 0 ? $arFields['SECTIONS'][0] : 0;
         }
         if (!isset($arFields['IS_MEETING'])) {
             $arFields['IS_MEETING'] = $oCurEvent['IS_MEETING'];
         }
         if (!isset($arFields['ACTIVE'])) {
             $arFields['ACTIVE'] = $oCurEvent['ACTIVE'];
         }
         if (!isset($arFields['PRIVATE_EVENT'])) {
             $arFields['PRIVATE_EVENT'] = $oCurEvent['PRIVATE_EVENT'];
         }
         if (!isset($arFields['ACCESSIBILITY'])) {
             $arFields['ACCESSIBILITY'] = $oCurEvent['ACCESSIBILITY'];
         }
         if (!isset($arFields['IMPORTANCE'])) {
             $arFields['IMPORTANCE'] = $oCurEvent['IMPORTANCE'];
         }
         if (!isset($arFields['LOCATION']) && $oCurEvent['LOCATION'] != "") {
             $arFields['LOCATION'] = array("OLD" => $oCurEvent['LOCATION'], "NEW" => $oCurEvent['LOCATION']);
         }
         if (!$bPersonal && !$bChangeMeeting) {
             $arFields['IS_MEETING'] = $oCurEvent['IS_MEETING'];
             if ($arFields['IS_MEETING']) {
                 $arFields['SECTIONS'] = array($oCurEvent['SECT_ID']);
             }
         }
         if ($oCurEvent['IS_MEETING']) {
             $arFields['MEETING_HOST'] = $oCurEvent['MEETING_HOST'];
         }
         if (!$bPersonal && !CCalendarSect::CanDo('calendar_edit', $oCurEvent['SECT_ID'], self::$userId)) {
             // If it's attendee but modifying called from CalDav methods
             if ($Params['bSilentAccessMeeting'] && $oCurEvent['IS_MEETING']) {
                 foreach ($oCurEvent['~ATTENDEES'] as $att) {
                     if ($att['USER_ID'] == $userId) {
                         return true;
                     }
                 }
                 // CalDav will return 204
             }
             return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));
         }
         if (!isset($arFields["RRULE"]) && $oCurEvent["RRULE"] != '' && $Params['fromWebservice'] !== true) {
             $arFields["RRULE"] = CCalendarEvent::ParseRRULE($oCurEvent["RRULE"]);
         }
         if ($Params['fromWebservice'] === true) {
             if ($arFields["RRULE"] == -1 && CCalendarEvent::CheckRecurcion($oCurEvent)) {
                 $arFields["RRULE"] = CCalendarEvent::ParseRRULE($oCurEvent['RRULE']);
             }
             if ($arFields['DT_FROM'] == -1) {
                 $arFields['DT_FROM_TS'] = $oCurEvent['DT_FROM_TS'];
                 $arFields['DT_TO_TS'] = $arFields['DT_FROM_TS'] + $oCurEvent['DT_LENGTH'];
                 if ($oCurEvent['DT_SKIP_TIME'] == 'Y') {
                     $arFields['DT_TO_TS'] -= self::GetDayLen();
                 }
             }
         }
         if (self::IsCalDAVEnabled() && $oCurEvent['SECT_ID'] != $sectionId) {
             // Check if it's CalDav section for one or another section
             $calDavCon = CCalendarSect::GetCalDAVConnectionId(array($oCurEvent['SECT_ID'], $sectionId));
             if ($calDavCon[$sectionId] != $calDavCon['SECT_ID']) {
                 // create new
                 $arFieldsNew = $arFields;
                 unset($arFieldsNew['ID']);
                 $newId = self::SaveEvent(array('arFields' => $arFieldsNew));
                 if ($newId) {
                     // Delete
                     self::DeleteEvent($arFields['ID']);
                 }
                 return $newId;
             }
         }
         if ($oCurEvent) {
             $Params['currentEvent'] = $oCurEvent;
         }
         if (!$bPersonal && !CCalendarSect::CanDo('calendar_edit', $oCurEvent['SECT_ID'], self::$userId)) {
             return GetMessage('EC_ACCESS_DENIED');
         }
     } elseif ($sectionId > 0 && !$bPersonal && !CCalendarSect::CanDo('calendar_add', $sectionId, self::$userId)) {
         return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));
     }
     if ($Params['autoDetectSection'] && $sectionId <= 0) {
         $res = CCalendarSect::GetList(array('arFilter' => array('CAL_TYPE' => $arFields['CAL_TYPE'], 'OWNER_ID' => $arFields['OWNER_ID']), 'checkPermissions' => false));
         if ($res && is_array($res) && isset($res[0])) {
             $sectionId = $res[0]['ID'];
         } elseif ($Params['autoCreateSection']) {
             $defCalendar = CCalendarSect::CreateDefault(array('type' => $arFields['CAL_TYPE'], 'ownerId' => $arFields['OWNER_ID']));
             $sectionId = $defCalendar['ID'];
             $Params['bAffectToDav'] = false;
         }
         if ($sectionId > 0) {
             $arFields['SECTIONS'] = array($sectionId);
         } else {
             return false;
         }
     }
     if (isset($arFields["RRULE"])) {
         $arFields["RRULE"] = CCalendarEvent::CheckRRULE($arFields["RRULE"]);
     }
     // Set version
     if (!isset($arFields['VERSION']) || $arFields['VERSION'] <= $oCurEvent['VERSION']) {
         $arFields['VERSION'] = $oCurEvent['VERSION'] ? $oCurEvent['VERSION'] + 1 : 1;
     }
     $offset = CCalendar::GetOffset();
     if (!isset($arFields['DT_FROM_TS'])) {
         $arFields['DT_FROM_TS'] = self::Timestamp($arFields['DT_FROM']);
         $arFields['DT_TO_TS'] = self::Timestamp($arFields['DT_TO']);
     }
     if (!isset($arFields['SKIP_TIME'])) {
         $item['DT_SKIP_TIME'] = date('H:i', $arFields['DT_FROM_TS']) == '00:00' && date('H:i', $arFields['DT_TO_TS']) == '00:00';
     }
     if ($Params['bServerTime'] !== true && !$arFields['SKIP_TIME'] && $offset != 0) {
         $arFields['DT_FROM_TS'] -= $offset;
         $arFields['DT_TO_TS'] -= $offset;
     }
     $arFields['DT_FROM'] = self::Date($arFields['DT_FROM_TS']);
     $arFields['DT_TO'] = self::Date($arFields['DT_TO_TS']);
     if ($Params['autoDetectSection'] && $sectionId <= 0 && $arFields['OWNER_ID'] > 0) {
         $res = CCalendarSect::GetList(array('arFilter' => array('CAL_TYPE' => $arFields['CAL_TYPE'], 'OWNER_ID' => $arFields['OWNER_ID']), 'checkPermissions' => false));
         if ($res && is_array($res) && isset($res[0])) {
             $sectionId = $res[0]['ID'];
         } elseif ($Params['autoCreateSection']) {
             $defCalendar = CCalendarSect::CreateDefault(array('type' => $arFields['CAL_TYPE'], 'ownerId' => $arFields['OWNER_ID']));
             $sectionId = $defCalendar['ID'];
             $Params['bAffectToDav'] = false;
         }
         if ($sectionId > 0) {
             $arFields['SECTIONS'] = array($sectionId);
         } else {
             return false;
         }
     }
     $bExchange = CCalendar::IsExchangeEnabled() && $arFields['CAL_TYPE'] == 'user';
     $bCalDav = CCalendar::IsCalDAVEnabled() && $arFields['CAL_TYPE'] == 'user';
     if ($Params['bAffectToDav'] !== false && ($bExchange || $bCalDav) && $sectionId > 0) {
         $res = CCalendar::DoSaveToDav(array('bCalDav' => $bCalDav, 'bExchange' => $bExchange, 'sectionId' => $sectionId), $arFields, $oCurEvent);
         if ($res !== true) {
             return CCalendar::ThrowError($res);
         }
     }
     $Params['arFields'] = $arFields;
     $Params['userId'] = $userId;
     if (self::$ownerId != $arFields['OWNER_ID'] && self::$type != $arFields['CAL_TYPE']) {
         $Params['path'] = self::GetPath($arFields['CAL_TYPE'], $arFields['OWNER_ID'], 1);
     } else {
         $Params['path'] = self::$path;
     }
     $id = CCalendarEvent::Edit($Params);
     $UFs = $Params['UF'];
     if (isset($UFs) && count($UFs) > 0) {
         CCalendarEvent::UpdateUserFields($id, $UFs);
         if ($arFields['IS_MEETING']) {
             if (!empty($UFs['UF_WEBDAV_CAL_EVENT'])) {
                 $UF = $GLOBALS['USER_FIELD_MANAGER']->GetUserFields("CALENDAR_EVENT", $id, LANGUAGE_ID);
                 CCalendar::UpdateUFRights($UFs['UF_WEBDAV_CAL_EVENT'], $arFields['ATTENDEES_CODES'], $UF['UF_WEBDAV_CAL_EVENT']);
             }
         }
     }
     $arFields['ID'] = $id;
     foreach (GetModuleEvents("calendar", "OnAfterCalendarEventEdit", true) as $arEvent) {
         ExecuteModuleEventEx($arEvent, array('arFields' => $arFields, 'bNew' => $bNew, 'userId' => $userId));
     }
     return $id;
 }
Esempio n. 3
0
	public static function Request($action = '')
	{
		global $APPLICATION;
		if ($_REQUEST['skip_unescape'] !== 'Y')
			CUtil::JSPostUnEscape();

		// Export calendar
		if ($action == 'export')
		{
			// We don't need to check access  couse we will check security SIGN from the URL
			$sectId = intVal($_GET['sec_id']);
			if ($_GET['check'] == 'Y') // Just for access check from calendar interface
			{
				$APPLICATION->RestartBuffer();
				if (CCalendarSect::CheckSign($_GET['sign'], intVal($_GET['user']), $sectId > 0 ? $sectId : 'superposed_calendars'))
					echo 'BEGIN:VCALENDAR';
				die();
			}

			if (CCalendarSect::CheckAuthHash() && $sectId > 0)
			{
				// We don't need any warning in .ics file
				error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR|E_PARSE);
				CCalendarSect::ReturnICal(array(
					'sectId' => $sectId,
					'userId' => intVal($_GET['user']),
					'sign' => $_GET['sign'],
					'type' => $_GET['type'],
					'ownerId' => intVal($_GET['owner'])
				));
			}
		}
		else
		{
			// // First of all - CHECK ACCESS
			if (!CCalendarType::CanDo('calendar_type_view', self::$type) || !check_bitrix_sessid())
				return $APPLICATION->ThrowException(GetMessage("EC_ACCESS_DENIED"));

			$APPLICATION->ShowAjaxHead();
			$APPLICATION->RestartBuffer();
			$reqId = intVal($_REQUEST['reqId']);

			switch ($action)
			{
				// * * * * * Add and Edit event * * * * *
				case 'edit_event':
					if (self::$bReadOnly || !CCalendarType::CanDo('calendar_type_view', self::$type))
						return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));

					$id = intVal($_POST['id']);
					if (isset($_POST['section']))
					{
						$sectId = intVal($_POST['section']);
						$_POST['sections'] = array($sectId);
					}
					else
					{
						$sectId = intVal($_POST['sections'][0]);
					}

					if (self::$type != 'user' || self::$ownerId != self::$userId) // Personal user's calendar
					{
						if (!$id && !CCalendarSect::CanDo('calendar_add', $sectId, self::$userId))
							return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));

						if ($id && !CCalendarSect::CanDo('calendar_edit', $sectId, self::$userId))
							return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));
					}

					// Default name for events
					$_POST['name'] = trim($_POST['name']);
					if ($_POST['name'] == '')
						$_POST['name'] = GetMessage('EC_DEFAULT_EVENT_NAME');

					$remind = array();
					if (isset($_POST['remind']['checked']) && $_POST['remind']['checked'] == 'Y')
						$remind[] = array('type' => $_POST['remind']['type'], 'count' => intval($_POST['remind']['count']));

					$arFields = array(
						"ID" => $id,
						"DT_FROM_TS" => $_POST['from_ts'],
						"DT_TO_TS" => $_POST['to_ts'],
						'NAME' => $_POST['name'],
						'DESCRIPTION' => trim($_POST['desc']),
						'SECTIONS' => $_POST['sections'],
						'COLOR' => $_POST['color'],
						'TEXT_COLOR' => $_POST['text_color'],
						'ACCESSIBILITY' => $_POST['accessibility'],
						'IMPORTANCE' => $_POST['importance'],
						'PRIVATE_EVENT' => $_POST['private_event'],
						'RRULE' => isset($_POST['rrule_enabled']) ? $_POST['rrule'] : false,
						'LOCATION' => is_array($_POST['location']) ? $_POST['location'] : array(),
						"REMIND" => $remind,
						"IS_MEETING" => !!$_POST['is_meeting'],
						"SKIP_TIME" => isset($_POST['skip_time']) && $_POST['skip_time'] == 'Y'
					);

					$arAccessCodes = array();
					if (isset($_POST['EVENT_DESTINATION']))
					{
						foreach($_POST["EVENT_DESTINATION"] as $v => $k)
						{
							if(strlen($v) > 0 && is_array($k) && !empty($k))
							{
								foreach($k as $vv)
								{
									if(strlen($vv) > 0)
									{
										$arAccessCodes[] = $vv;
									}
								}
							}
						}
						if (!$arFields["ID"])
							$arAccessCodes[] = 'U'.self::$userId;
						$arAccessCodes = array_unique($arAccessCodes);
					}

					$arFields['IS_MEETING'] = !empty($arAccessCodes) && $arAccessCodes != array('U'.self::$userId);
					if ($arFields['IS_MEETING'])
					{
						$arFields['ATTENDEES_CODES'] = $arAccessCodes;
						$arFields['ATTENDEES'] = CCalendar::GetDestinationUsers($arAccessCodes);
						$arFields['MEETING_HOST'] = self::$userId;
						$arFields['MEETING'] = array(
							'HOST_NAME' => self::GetUserName($arFields['MEETING_HOST']),
							'TEXT' => isset($_POST['meeting_text']) ? $_POST['meeting_text'] : '',
							'OPEN' => $_POST['open_meeting'] === 'Y',
							'NOTIFY' => $_POST['meeting_notify'] === 'Y',
							'REINVITE' => $_POST['meeting_reinvite'] === 'Y'
						);
					}

					$newId = self::SaveEvent(array('arFields' => $arFields));
					if ($newId)
					{
						// Userfields for event
						$arUFFields = array();
						foreach ($_POST as $field => $value)
						{
							if (substr($field, 0, 3) == "UF_")
							{
								$arUFFields[$field] = $value;
							}
						}

						if (count($arUFFields) > 0)
							CCalendarEvent::UpdateUserFields($newId, $arUFFields);

						if ($arFields['IS_MEETING'])
						{
							if (!empty($arUFFields['UF_WEBDAV_CAL_EVENT']))
							{
								$UF = $GLOBALS['USER_FIELD_MANAGER']->GetUserFields("CALENDAR_EVENT", $newId, LANGUAGE_ID);
								CCalendar::UpdateUFRights($arUFFields['UF_WEBDAV_CAL_EVENT'], $arAccessCodes, $UF['UF_WEBDAV_CAL_EVENT']);
							}

							// Save to livefeed


						}

						$arFilter = array("ID" => $newId);
						$month = intVal($_REQUEST['month']);
						$year = intVal($_REQUEST['year']);
						$arFilter["FROM_LIMIT"] = self::Date(mktime(0, 0, 0, $month - 1, 20, $year), false);
						$arFilter["TO_LIMIT"] = self::Date(mktime(0, 0, 0, $month + 1, 10, $year), false);

						$arAttendees = array(); // List of attendees for event
						$arEvents = CCalendarEvent::GetList(
							array(
								'arFilter' => $arFilter,
								'parseRecursion' => true,
								'fetchAttendees' => true,
								'userId' => self::$userId
							)
						);
					}

					if ($arEvents && $arFields['IS_MEETING'])
						$arAttendees = CCalendarEvent::GetLastAttendees();

					CCalendar::OutputJSRes($reqId, array(
						'id' => $newId,
						'events' => $arEvents,
						'attendees' => $arAttendees,
						'deletedEventId' => ($id && $newId != $id) ? $id : 0
					));
					break;

				// * * * * * Delete event * * * * *
				case 'delete':
					if (self::$bReadOnly || !CCalendarType::CanDo('calendar_type_view', self::$type))
						return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));

					$res = self::DeleteEvent(intVal($_POST['id']));

					if ($res !== true)
						return CCalendar::ThrowError(strlen($res) > 0 ? $res : GetMessage('EC_EVENT_DEL_ERROR'));

					CCalendar::OutputJSRes($reqId, true);
					break;

				// * * * * * Load events for some time limits * * * * *
				case 'load_events':
					$arSect = array();
					$arHiddenSect = array();
					$month = intVal($_REQUEST['month']);
					$year = intVal($_REQUEST['year']);
					$fromLimit = self::Date(mktime(0, 0, 0, $month - 1, 20, $year), false);
					$toLimit = self::Date(mktime(0, 0, 0, $month + 1, 10, $year), false);

					if ($_REQUEST['cal_dav_data_sync'] == 'Y' && CCalendar::IsCalDAVEnabled())
						CDavGroupdavClientCalendar::DataSync("user", self::$ownerId);

					$bGetTask = false;
					if (is_array($_REQUEST['sa']))
					{
						foreach($_REQUEST['sa'] as $sectId)
						{
							if ($sectId == 'tasks')
								$bGetTask = true;
							elseif (intval($sectId) > 0)
								$arSect[] = intval($sectId);
						}
					}

					if (is_array($_REQUEST['sh']))
					{
						foreach($_REQUEST['sh'] as $sectId)
						{
							if ($sectId == 'tasks')
								$arHiddenSect[] = 'tasks';
							elseif(intval($sectId) > 0)
								$arHiddenSect[] = intval($sectId);
						}
					}

					$arAttendees = array(); // List of attendees for each event Array([ID] => Array(), ..,);
					$arEvents = array();

					if (count($arSect) > 0)
					{
						// NOTICE: Attendees for meetings selected inside this method and returns as array by link '$arAttendees'
						$arEvents = self::GetEventList(array(
							'type' => self::$type,
							'section' => $arSect,
							'fromLimit' => $fromLimit,
							'toLimit' => $toLimit,
							'additonalMeetingsId' => is_array($_REQUEST['ameetid']) ? $_REQUEST['ameetid'] : array()
						), $arAttendees);
					}

					//  **** GET TASKS ****
					if (self::$bTasks && $bGetTask)
					{
						$arTasks = self::GetTaskList(array(
							'fromLimit' => $fromLimit,
							'toLimit' => $toLimit
						), $arTaskIds);

						if (count($arTasks) > 0)
							$arEvents = array_merge($arEvents, $arTasks);
					}

					// Save hidden calendars
					CCalendarSect::Hidden(self::$userId, $arHiddenSect);

					CCalendar::OutputJSRes($reqId, array(
						'events' => $arEvents,
						'attendees' => $arAttendees
					));
					break;

				// * * * * * Edit calendar * * * * *
				case 'section_edit':
					$id = intVal($_POST['id']);
					$bNew = (!isset($id) || $id == 0);

					if ($bNew) // For new sections
					{
						if (self::$type == 'group')
						{
							// It's for groups
							if (!self::$perm['section_edit'])
								return CCalendar::ThrowError('[se01]'.GetMessage('EC_ACCESS_DENIED'));
						}
						else if (self::$type == 'user')
						{
							if (!self::IsPersonal()) // If it's not owner of the group.
								return CCalendar::ThrowError('[se02]'.GetMessage('EC_ACCESS_DENIED'));
						}
						else // other types
						{
							if (!CCalendarType::CanDo('calendar_type_edit_section'))
								return CCalendar::ThrowError('[se03]'.GetMessage('EC_ACCESS_DENIED'));
						}
					}
					// For existent sections
					elseif (!self::IsPersonal() && !$bNew && !CCalendarSect::CanDo('calendar_edit_section', $id, self::$userId))
					{
						return CCalendar::ThrowError(GetMessage('[se02]EC_ACCESS_DENIED'));
					}

					$arFields = Array(
						'CAL_TYPE' => self::$type,
						'ID' => $id,
						'NAME' => trim($_POST['name']),
						'DESCRIPTION' => trim($_POST['desc']),
						'COLOR' => $_POST['color'],
						'TEXT_COLOR' => $_POST['text_color'],
						'OWNER_ID' => self::$bOwner ? self::GetOwnerId() : '',
						'EXPORT' => array(
							'ALLOW' => isset($_POST['export']) && $_POST['export'] == 'Y',
							'SET' => $_POST['exp_set']
						),
						'ACCESS' => is_array($_POST['access']) ? $_POST['access'] : array()
					);

					if ($bNew)
						$arFields['IS_EXCHANGE'] = $_POST['is_exchange'] == 'Y';

					$id = intVal(self::SaveSection(
						array(
							'arFields' => $arFields
						)
					));

					if ($id > 0)
					{
						CCalendarSect::SetClearOperationCache(true);
						$oSect = CCalendarSect::GetById($id, true, true);
						if (!$oSect)
							return CCalendar::ThrowError(GetMessage('EC_CALENDAR_SAVE_ERROR'));

						if (self::$type == 'user' && isset($_POST['is_def_meet_calendar']) && $_POST['is_def_meet_calendar'] == 'Y')
						{
							$set = CCalendar::GetUserSettings(self::$ownerId);
							$set['meetSection'] = $id;
							CCalendar::SetUserSettings($set, self::$ownerId);
						}

						CCalendar::OutputJSRes($reqId, array('calendar' => $oSect, 'accessNames' => CCalendar::GetAccessNames()));
					}

					if ($id <= 0)
						return CCalendar::ThrowError(GetMessage('EC_CALENDAR_SAVE_ERROR'));
					break;

				// * * * * * Delete calendar * * * * *
				case 'section_delete':
					$sectId = intVal($_REQUEST['id']);

					if (!self::IsPersonal() && !CCalendarSect::CanDo('calendar_edit_section', $sectId, self::$userId))
						return CCalendar::ThrowError(GetMessage('EC_ACCESS_DENIED'));

					$res = self::DeleteSection($sectId);
					// if ($res !== true)
					// return CCalendar::ThrowError(strlen($res) > 0 ? $res : GetMessage('EC_CALENDAR_DEL_ERROR'));

					CCalendar::OutputJSRes($reqId, array('result' => true));
					break;

				// * * * * * Save superposed sections * * * * *
				case 'set_superposed':

					$trackedUser = intVal($_REQUEST['trackedUser']);
					if ($trackedUser > 0)
					{
						$arUserIds = self::TrackingUsers(self::$userId);
						if (!in_array($trackedUser, $arUserIds))
						{
							$arUserIds[] = $trackedUser;
							self::TrackingUsers(self::$userId, $arUserIds);
						}
					}

					if (CCalendar::SetDisplayedSuperposed(self::$userId, $_REQUEST['sect']))
						CCalendar::OutputJSRes($reqId, array('result' => true));
					else
						CCalendar::ThrowError('Error! Cant save displayed superposed calendars');
					break;

				// * * * * * Fetch all available sections for superposing * * * * *
				case 'get_superposed':
					CCalendar::OutputJSRes($reqId, array('sections' => CCalendar::GetSuperposed()));
					break;

				// * * * * * Return info about user, and user calendars * * * * *
				case 'spcal_user_cals':
					CCalendar::OutputJSRes($reqId, array('sections' => CCalendar::GetSuperposedForUsers($_REQUEST['users'])));
					break;

				// * * * * * Delete tracking user * * * * *
				case 'spcal_del_user':
					CCalendar::OutputJSRes($reqId, array('result' => CCalendar::DeleteTrackingUser(intVal($_REQUEST['userId']))));
					break;

				// * * * * * Save user settings * * * * *
				case 'save_settings':
					if (isset($_POST['clear_all']) && $_POST['clear_all'] == true)
					{
						// Clear personal settings
						CCalendar::SetUserSettings(false);
					}
					else
					{
						// Personal
						CCalendar::SetUserSettings($_REQUEST['user_settings']);

						// Save access for type
						if (CCalendarType::CanDo('calendar_type_access', self::$type))
						{
							// General
							$_REQUEST['settings']['week_holidays'] = implode('|',$_REQUEST['settings']['week_holidays']);
							CCalendar::SetSettings($_REQUEST['settings']);
							CCalendarType::Edit(array(
								'arFields' => array(
									'XML_ID' => self::$type,
									'ACCESS' => $_REQUEST['type_access']
								)
							));
						}
					}

					CCalendar::OutputJSRes($reqId, array('result' => true));
					break;

				// * * * * * Confirm user part in event * * * * *
				case 'set_meeting_status':
					CCalendarEvent::SetMeetingStatus(
						self::$userId,
						intVal($_REQUEST['event_id']),
						in_array($_REQUEST['status'], array('Q', 'Y', 'N')) ? $_REQUEST['status'] : 'Q',
						$_REQUEST['status_comment']
					);
					CCalendar::OutputJSRes($reqId, true);
					break;
				case 'set_meeting_params':
					CCalendarEvent::SetMeetingParams(
						self::$userId,
						intVal($_REQUEST['event_id']),
						array(
							'ACCESSIBILITY' => $_REQUEST['accessibility'],
							'REMIND' =>  $_REQUEST['remind']
						)
					);
					CCalendar::OutputJSRes($reqId, true);
					break;

				// * * * * * Check users accessibility * * * * *
				case 'check_guests':
					CCalendar::OutputJSRes($reqId, array(
						'data' => CCalendar::CheckUsersAccessibility(array(
								'users' => $_REQUEST['attendees'],
								'from' => self::Date($_POST['from']),
								'to' => self::Date($_POST['to']),
								'eventId' => intVal($_POST['event_id'])
							)
						)));
					break;

				// * * * * * Get list of group members * * * * *
				case 'get_group_members':
					if (self::$type == 'group')
						CCalendar::OutputJSRes($reqId, array('users' => self::GetGroupMembers(self::$ownerId)));

					break;
				// * * * * * Get Guests Accessibility * * * * *
				case 'get_accessibility':

					$res = CCalendar::GetAccessibilityForUsers(array(
						'users' => $_POST['users'],
						'from' => self::Date(self::Timestamp($_POST['from'])),
						'to' => self::Date(self::Timestamp($_POST['to'])),
						'curEventId' => intVal($_POST['cur_event_id']),
						'getFromHR' => true
					));

					CCalendar::OutputJSRes($reqId, array('data' => $res));
					break;

				// * * * * * Get meeting room accessibility * * * * *
				case 'get_mr_accessibility':
					$res = CCalendar::GetAccessibilityForMeetingRoom(array(
						'id' => intVal($_POST['id']),
						'from' => self::Date(self::Timestamp($_POST['from'])),
						'to' => self::Date(self::Timestamp($_POST['to'])),
						'curEventId' => intVal($_POST['cur_event_id'])
					));
					CCalendar::OutputJSRes($reqId, array('data' => $res));
					break;

				// * * * * * Get meeting room accessibility * * * * *
				case 'check_meeting_room':
					$check = false;
					if (self::$allowReserveMeeting || self::$allowVideoMeeting)
					{
						$from = self::Date($_POST['from']);
						$to = self::Date($_POST['to']);

						$loc_old = $_POST['location_old'] ? CCalendar::ParseLocation(trim($_POST['location_old'])) : false;
						$loc_new = CCalendar::ParseLocation(trim($_POST['location_new']));

						$Params = array(
							'dateFrom' => self::CutZeroTime($from),
							'dateTo' => self::CutZeroTime($to),
							'regularity' => 'NONE',
							'members' => isset($_POST['guest']) ? $_POST['guest'] : false,
						);
						$tst = MakeTimeStamp($Params['dateTo']);
						if (date("H:i", $tst) == '00:00')
							$Params['dateTo'] = CIBlockFormatProperties::DateFormat(self::DFormat(true), $tst + (23 * 60 + 59) * 60);
						if (intVal($_POST['id']) > 0)
							$Params['ID'] = intVal($_POST['id']);

						if (self::$allowVideoMeeting && $loc_new['mrid'] == self::$settings['vr_iblock_id'])
						{
							$Params['VMiblockId'] = self::$settings['vr_iblock_id'];
							if ($loc_old['mrevid'] > 0)
								$Params['ID'] = $loc_old['mrevid'];
							$check = CCalendar::CheckVideoRoom($Params);
						}
						elseif(self::$allowReserveMeeting)
						{
							$Params['RMiblockId'] = self::$settings['rm_iblock_id'];
							$Params['mrid'] = $loc_new['mrid'];
							$Params['mrevid_old'] = $loc_old ? $loc_old['mrevid'] : 0;
							$check = CCalendar::CheckMeetingRoom($Params);
						}
					}

					CCalendar::OutputJSRes($reqId, array('check' => $check));
					break;

				case 'connections_edit':
					if (self::$type == 'user' && CCalendar::IsCalDAVEnabled())
					{
						$res = CCalendar::ManageConnections($_POST['connections']);
						if ($res !== true)
							CCalendar::ThrowError($res == '' ? 'Edit connections error' : $res);
						else
							CCalendar::OutputJSRes($reqId, array('result' => true));
					}
					break;
				case 'exchange_sync':
					if (self::$type == 'user' && CCalendar::IsExchangeEnabled(self::$ownerId))
					{
						$error = "";
						$res = CDavExchangeCalendar::DoDataSync(self::$ownerId, $error);
						if ($res === true || $res === false)
							CCalendar::OutputJSRes($reqId, array('result' => true));
						else
							CCalendar::ThrowError($error);
					}
					break;
				case 'userfield_view':
					CCalendarSceleton::GetUserfieldsViewHtml(intVal($_REQUEST['event_id']));
					CCalendar::OutputJSRes($reqId, array('result' => true));
					break;
				case 'userfield_edit':
					CCalendarSceleton::GetUserfieldsEditHtml(intVal($_REQUEST['event_id']), self::$actionUrl);
					CCalendar::OutputJSRes($reqId, array('result' => true));
					break;
				case 'userfield_save':
					$arFields = array();
					$bRefresh = false;
					foreach ($_POST as $field => $value)
						if (substr($field, 0, 3) == "UF_")
						{
							$arFields[$field] = $value;
							if ($field == 'UF_CRM_CAL_EVENT')
								$bRefresh = true;
						}

					if (count($arFields) > 0)
						CCalendarEvent::UpdateUserFields($_REQUEST['event_id'], $arFields);

					CCalendar::OutputJSRes($reqId, array('result' => true, 'refresh' => $bRefresh));
					break;

				case 'get_view_event_dialog':
					$APPLICATION->ShowAjaxHead();

					$jsId = $color = preg_replace('/[^\d|\w]/', '', $_REQUEST['js_id']);
					$event_id = intval($_REQUEST['event_id']);

					$Event = CCalendarEvent::GetList(
						array(
							'arFilter' => array(
								"ID" => $event_id
							),
							'parseRecursion' => false,
							'fetchAttendees' => true,
							'checkPermissions' => true,
							'setDefaultLimit' => false
						)
					);

					if ($Event && is_array($Event[0]))
					{
						CCalendarSceleton::DialogViewEvent(array(
							'id' => $jsId,
							'event' => $Event[0],
							'sectionName' => $_REQUEST['section_name'],
							'fromTs' => $_REQUEST['from_ts'],
							'bIntranet' => self::IsIntranetEnabled(),
							'bSocNet' => self::IsSocNet(),
							'AVATAR_SIZE' => 21
						));
					}

					break;

				case 'get_edit_event_dialog':
					$APPLICATION->ShowAjaxHead();

					$jsId = $color = preg_replace('/[^\d|\w]/', '', $_REQUEST['js_id']);
					$event_id = intval($_REQUEST['event_id']);

					if ($event_id > 0)
					{
						$Event = CCalendarEvent::GetList(
							array(
								'arFilter' => array(
									"ID" => $event_id
								),
								'parseRecursion' => false,
								'fetchAttendees' => true,
								'checkPermissions' => true,
								'setDefaultLimit' => false
							)
						);

						$Event = $Event && is_array($Event[0]) ? $Event[0] : false;
					}
					else
					{
						$Event = array();
					}

					CCalendarSceleton::DialogEditEvent(array(
						'id' => $jsId,
						'event' => $Event,
						'type' => self::$type,
						'bIntranet' => self::IsIntranetEnabled(),
						'bSocNet' => self::IsSocNet(),
						'AVATAR_SIZE' => 21
					));
					break;

				case 'get_attendees_by_codes_planner':
				case 'get_attendees_by_codes':
					$bPlanner = $action == 'get_attendees_by_codes_planner';
					$users = CCalendar::GetDestinationUsers($_REQUEST['codes'], true);

					$userIds = array();
					$result = array();
					foreach($users as $user)
					{
						$userIds[] = $user['USER_ID'];
						$result[] = array(
							'USER_ID' => $user['USER_ID'],
							'DISPLAY_NAME' => CCalendar::GetUserName($user),
							'AVATAR' => CCalendar::GetUserAvatar($user),
							'ACC' => '',
							'URL' => CCalendar::GetUserUrl($user['USER_ID'], self::$pathToUser)
						);
					}

					if ($_REQUEST['event_from_ts'] && $_REQUEST['event_to_ts'])
					{
						$acc = CCalendar::CheckUsersAccessibility(array(
							'users' => $userIds,
							'from' => self::Date($_REQUEST['event_from_ts']),
							'to' => self::Date($_REQUEST['event_to_ts']),
							'eventId' => intVal($_REQUEST['cur_event_id'])
						));
						foreach($result as $i => $user)
							$result[$i]['ACC'] = $acc[$user['USER_ID']];
					}

					if ($bPlanner)
					{
						$accessibility = CCalendar::GetAccessibilityForUsers(array(
							'users' => $userIds,
							'from' => self::Date($_REQUEST['from_ts']),
							'to' => self::Date($_REQUEST['to_ts']),
							'curEventId' => intVal($_REQUEST['cur_event_id']),
							'getFromHR' => true
						));
					}
					else
					{
						$accessibility = array();
					}

					CCalendar::OutputJSRes($reqId, array(
						'users' => $result,
						'accessibility' => $accessibility
					));
					break;
			}
		}

		if($ex = $APPLICATION->GetException())
			return ShowError($ex->GetString());

		die();
	}