source: trunk/prototype/services/iCal.php @ 7702

Revision 7702, 115.1 KB checked in by acoutinho, 11 years ago (diff)

Ticket #3259 - Otimizar carregamento de eventos no modulo ExpressoCalendar?

RevLine 
[5341]1<?php
2
[7660]3//require_once ROOTPATH . '/plugins/icalcreator/iCalUtilityFunctions.class.php';
[6066]4require_once ROOTPATH . '/plugins/icalcreator/iCalcreator.class.php';
5require_once ROOTPATH . '/modules/calendar/constants.php';
6
[6528]7use prototype\api\Config as Config;
8
[5341]9//TODO:Timeout request
[6066]10set_time_limit(600);
11
12class iCal implements Formatter {
13
14    static $timezonesMap = array('(GMT-12.00) International Date Line West' => 'Etc/GMT+12', '(GMT-11.00) Midway Island / Samoa' => 'Pacific/Midway', '(GMT-10.00) Hawaii' => 'Pacific/Honolulu', '(GMT-09.00) Alaska' => 'America/Anchorage', '(GMT-08.00) Pacific Time (US & Canada) / Tijuana' => 'America/Los_Angeles', '(GMT-08.00) Tijuana / Baja California' => 'America/Tijuana', '(GMT-07.00) Arizona' => 'America/Phoenix', '(GMT-07.00) Chihuahua / La Paz / Mazatlan - Old' => 'America/Chihuahua', '(GMT-07.00) Mountain Time (US & Canada)' => 'America/Denver', '(GMT-06.00) Central America' => 'America/Guatemala', '(GMT-06.00) Central Time (US & Canada)' => 'America/Chicago', '(GMT-06.00) Guadalajara / Mexico City / Monterrey - Old' => 'America/Mexico_City', '(GMT-06.00) Saskatchewan' => 'America/Regina', '(GMT-05.00) Bogota / Lima / Quito' => 'America/Bogota', '(GMT-05.00) Eastern Time (US & Canada)' => 'America/New_York', '(GMT-05.00) Indiana (East)' => 'America/Indiana/Indianapolis', '(GMT-04.30) Caracas' => 'America/Caracas', '(GMT-04.00) Atlantic Time (Canada)' => 'America/Halifax', '(GMT-04.00) Georgetown' => 'America/Guyana', '(GMT-04.00) Caracas / La Paz' => 'America/La_Paz', '(GMT-04.00) Manaus' => 'America/Manaus', '(GMT-04.00) Santiago' => 'America/Santiago', '(GMT-03.30) Newfoundland' => 'America/St_Johns', '(GMT-03.00) Brasilia' => 'America/Sao_Paulo', 'GMT -0300 (Standard) / GMT -0200 (Daylight)' => 'America/Sao_Paulo', '(GMT-03.00) Buenos Aires / Georgetown' => 'America/Argentina/Buenos_Aires', '(GMT-03.00) Greenland' => 'America/Godthab', '(GMT-03.00) Montevideo' => 'America/Montevideo', '(GMT-02.00) Mid-Atlantic' => 'Atlantic/South_Georgia', '(GMT-01.00) Azores' => 'Atlantic/Azores', '(GMT-01.00) Cape Verde Is.' => 'Atlantic/Cape_Verde', '(GMT) Casablanca' => 'Africa/Casablanca', '(GMT) Greenwich Mean Time - Dublin / Edinburgh / Lisbon / London' => 'Europe/London', '(GMT) Casablanca / Monrovia' => 'Africa/Monrovia', '(GMT+01.00) Amsterdam / Berlin / Bern / Rome / Stockholm / Vienna' => 'Europe/Berlin', '(GMT+01.00) Belgrade / Bratislava / Budapest / Ljubljana / Prague' => 'Europe/Belgrade', '(GMT+01.00) Brussels / Copenhagen / Madrid / Paris' => 'Europe/Brussels', '(GMT+01.00) Sarajevo / Skopje / Warsaw / Zagreb' => 'Europe/Warsaw', '(GMT+01.00) West Central Africa' => 'Africa/Algiers', '(GMT+02.00) Windhoek' => 'Africa/Windhoek', '(GMT+02.00) Amman' => 'Asia/Amman', '(GMT+02.00) Bucharest' => 'Europe/Athens', '(GMT+02.00) Beirut' => 'Asia/Beirut', '(GMT+02.00) Cairo' => 'Africa/Cairo', '(GMT+02.00) Harare / Pretoria' => 'Africa/Harare', '(GMT+02.00) Helsinki / Kyiv / Riga / Sofia / Tallinn / Vilnius' => 'Europe/Helsinki', '(GMT+02.00) Jerusalem' => 'Asia/Jerusalem', '(GMT+02.00) Minsk' => 'Europe/Minsk', '(GMT+03.00) Baghdad' => 'Asia/Baghdad', '(GMT+03.00) Kuwait / Riyadh' => 'Asia/Kuwait', '(GMT+03.00) Moscow / St. Petersburg / Volgograd' => 'Europe/Moscow', '(GMT+03.00) Nairobi' => 'Africa/Nairobi', '(GMT+04.00) Caucasus Standard Time' => 'Asia/Tbilisi', '(GMT+03.30) Tehran' => 'Asia/Tehran', '(GMT+04.00) Abu Dhabi / Muscat' => 'Asia/Muscat', '(GMT+04.00) Baku / Tbilisi / Yerevan' => 'Asia/Baku', '(GMT+04.00) Yerevan' => 'Asia/Yerevan', '(GMT+04.30) Kabul' => 'Asia/Kabul', '(GMT+05.00) Ekaterinburg' => 'Asia/Yekaterinburg', '(GMT+05.00) Islamabad / Karachi / Tashkent' => 'Asia/Karachi', '(GMT+05.00) Tashkent' => 'Asia/Tashkent', '(GMT+05.30) Chennai / Kolkata / Mumbai / New Delhi' => 'Asia/Kolkata', '(GMT+06.00) Sri Jayawardenepura' => 'Asia/Colombo', '(GMT+05.45) Kathmandu' => 'Asia/Katmandu', '(GMT+06.00) Almaty / Novosibirsk' => 'Asia/Novosibirsk', '(GMT+06.00) Astana / Dhaka' => 'Asia/Dhaka', '(GMT+06.30) Rangoon' => 'Asia/Rangoon', '(GMT+07.00) Bangkok / Hanoi / Jakarta' => 'Asia/Bangkok', '(GMT+07.00) Krasnoyarsk' => 'Asia/Krasnoyarsk', '(GMT+08.00) Beijing / Chongqing / Hong Kong / Urumqi' => 'Asia/Hong_Kong', '(GMT+08.00) Irkutsk / Ulaan Bataar' => 'Asia/Irkutsk', '(GMT+08.00) Kuala Lumpur / Singapore' => 'Asia/Kuala_Lumpur', '(GMT+08.00) Perth' => 'Australia/Perth', '(GMT+08.00) Taipei' => 'Asia/Taipei', '(GMT+09.00) Osaka / Sapporo / Tokyo' => 'Asia/Tokyo', '(GMT+09.00) Seoul' => 'Asia/Seoul', '(GMT+09.00) Yakutsk' => 'Asia/Yakutsk', '(GMT+09.30) Adelaide' => 'Australia/Adelaide', '(GMT+09.30) Darwin' => 'Australia/Darwin', '(GMT+10.00) Brisbane' => 'Australia/Brisbane', '(GMT+10.00) Canberra / Melbourne / Sydney' => 'Australia/Sydney', '(GMT+10.00) Guam / Port Moresby' => 'Pacific/Guam', '(GMT+10.00) Hobart' => 'Australia/Hobart', '(GMT+10.00) Vladivostok' => 'Asia/Vladivostok', '(GMT+11.00) Magadan / Solomon Is. / New Caledonia' => 'Asia/Magadan', '(GMT+12.00) Auckland / Wellington' => 'Pacific/Auckland', '(GMT+12.00) Fiji / Kamchatka / Marshall Is.' => 'Pacific/Fiji', '(GMT+13.00) Nuku\'alofa' => 'Pacific/Tongatapu', 'E. South America Standard Time' => 'America/Sao_Paulo', 'E. South America' => 'America/Sao_Paulo');
[5341]15//    static $timezonesOutlookID = array('Europe/London' => '1' ,'Europe/Brussels' => '3' ,'Europe/Berlin' => '4' ,'America/New_York' => '5' ,'Europe/Belgrade' => '6' ,'Europe/Minsk' => '7' ,'America/Sao_Paulo' => '8' ,'America/Halifax' => '9' ,'America/New_York' => '10' ,'America/Chicago' => '11' ,'America/Denver' => '12' ,'America/Los_Angeles' => '13' ,'America/Anchorage' => '14' ,'Pacific/Honolulu' => '15' ,'Pacific/Midway' => '16' ,'Pacific/Auckland' => '17' ,'Australia/Brisbane' => '18' ,'Australia/Adelaide' => '19' ,'Asia/Tokyo' => '20' ,'Asia/Hong_Kong' => '21' ,'Asia/Bangkok' => '22' ,'Asia/Kolkata' => '23' ,'Asia/Muscat' => '24' ,'Asia/Tehran' => '25' ,'Asia/Baghdad' => '26' ,'Asia/Jerusalem' => '27' ,'America/St_Johns' => '28' ,'Atlantic/Azores' => '29' ,'Atlantic/South_Georgia' => '30' ,'Africa/Casablanca' => '31' ,'America/La_Paz' => '33' ,'America/Indiana/Indianapolis' => '34' ,'America/Bogota' => '35' ,'America/Regina' => '36' ,'America/Mexico_City' => '37' ,'America/Phoenix' => '38' ,'Etc/GMT+12' => '39' ,'Pacific/Fiji' => '40' ,'Asia/Magadan' => '41' ,'Australia/Hobart' => '42' ,'Pacific/Guam' => '43' ,'Australia/Darwin' => '44' ,'Asia/Hong_Kong' => '45' ,'Asia/Novosibirsk' => '46' ,'Asia/Kabul' => '48' ,'Africa/Cairo' => '49' ,'Africa/Harare' => '50' ,'Europe/Moscow' => '51' ,'Australia/Sydney' => '52' ,'Australia/Sydney' => '53' ,'Australia/Adelaide' => '54' ,'Australia/Hobart' => '55' ,'America/Santiago' => '56' ,'Australia/Pert' => '57' ,'America/Tijuana' => '59' ,'Asia/Tbilisi' => '60' ,'Australia/Sydney' => '61' ,'America/Caracas' => '62' ,'Asia/Amman' => '63' ,'Asia/Baku' => '64' ,'Asia/Yerevan' => '65' ,'Europe/Moscow' => '66' ,'America/Argentina/Buenos_Aires' => '67' ,'America/Montevideo' => '72'); 
[6066]16    static $suportedTimzones = array('Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville', 'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Lome', 'Africa/Luanda', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Malabo', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Africa/Mogadishu', 'Africa/Monrovia', 'Africa/Nairobi', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Porto-Novo', 'Africa/Sao_Tome', 'Africa/Timbuktu', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Anguilla', 'America/Antigua', 'America/Araguaina', 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca', 'America/Argentina/ComodRivadavia', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/La_Rioja', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Aruba', 'America/Asuncion', 'America/Atikokan', 'America/Atka', 'America/Bahia', 'America/Barbados', 'America/Belem', 'America/Belize', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Bogota', 'America/Boise', 'America/Buenos_Aires', 'America/Cambridge_Bay', 'America/Campo_Grande', 'America/Cancun', 'America/Caracas', 'America/Catamarca', 'America/Cayenne', 'America/Cayman', 'America/Chicago', 'America/Chihuahua', 'America/Coral_Harbour', 'America/Cordoba', 'America/Costa_Rica', 'America/Cuiaba', 'America/Curacao', 'America/Danmarkshavn', 'America/Dawson_Creek', 'America/Dawson', 'America/Denver', 'America/Detroit', 'America/Dominica', 'America/Edmonton', 'America/Eirunepe', 'America/El_Salvador', 'America/Ensenada', 'America/Fort_Wayne', 'America/Fortaleza', 'America/Glace_Bay', 'America/Godthab', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Indiana/Indianapolis', 'America/Indiana/Knox', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indianapolis', 'America/Inuvik', 'America/Iqaluit', 'America/Jamaica', 'America/Jujuy', 'America/Juneau', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Knox_IN', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Louisville', 'America/Maceio', 'America/Managua', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Matamoros', 'America/Mazatlan', 'America/Mendoza', 'America/Menominee', 'America/Merida', 'America/Mexico_City', 'America/Miquelon', 'America/Moncton', 'America/Monterrey', 'America/Montevideo', 'America/Montreal', 'America/Montserrat', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Nome', 'America/Noronha', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Ojinaga', 'America/Panama', 'America/Pangnirtung', 'America/Paramaribo', 'America/Phoenix', 'America/Port_of_Spain', 'America/Port-au-Prince', 'America/Porto_Acre', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Recife', 'America/Regina', 'America/Resolute', 'America/Rio_Branco', 'America/Rosario', 'America/Santa_Isabel', 'America/Santarem', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/Shiprock', 'America/St_Barthelemy', 'America/St_Johns', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Swift_Current', 'America/Tegucigalpa', 'America/Thule', 'America/Thunder_Bay', 'America/Tijuana', 'America/Toronto', 'America/Tortola', 'America/Vancouver', 'America/Virgin', 'America/Whitehorse', 'America/Winnipeg', 'America/Yakutat', 'America/Yellowknife', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Antarctica/McMurdo', 'Antarctica/Palmer', 'Antarctica/Rothera', 'Antarctica/South_Pole', 'Antarctica/Syowa', 'Antarctica/Vostok', 'Arctic/Longyearbyen', 'Asia/Aden', 'Asia/Almaty', 'Asia/Amman', 'Asia/Anadyr', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Ashkhabad', 'Asia/Baghdad', 'Asia/Bahrain', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Calcutta', 'Asia/Choibalsan', 'Asia/Chongqing', 'Asia/Chungking', 'Asia/Colombo', 'Asia/Dacca', 'Asia/Damascus', 'Asia/Dhaka', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Gaza', 'Asia/Harbin', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Asia/Istanbul', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Kashgar', 'Asia/Kathmandu', 'Asia/Katmandu', 'Asia/Kolkata', 'Asia/Krasnoyarsk', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Kuwait', 'Asia/Macao', 'Asia/Macau', 'Asia/Magadan', 'Asia/Makassar', 'Asia/Manila', 'Asia/Muscat', 'Asia/Nicosia', 'Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Oral', 'Asia/Phnom_Penh', 'Asia/Pontianak', 'Asia/Pyongyang', 'Asia/Qatar', 'Asia/Qyzylorda', 'Asia/Rangoon', 'Asia/Riyadh', 'Asia/Saigon', 'Asia/Sakhalin', 'Asia/Samarkand', 'Asia/Seoul', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Tel_Aviv', 'Asia/Thimbu', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Ujung_Pandang', 'Asia/Ulaanbaatar', 'Asia/Ulan_Bator', 'Asia/Urumqi', 'Asia/Vientiane', 'Asia/Vladivostok', 'Asia/Yakutsk', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faeroe', 'Atlantic/Faroe', 'Atlantic/Jan_Mayen', 'Atlantic/Madeira', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/St_Helena', 'Atlantic/Stanley', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Canberra', 'Australia/Currie', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/LHI', 'Australia/Lindeman', 'Australia/Lord_Howe', 'Australia/Melbourne', 'Australia/NSW', 'Australia/North', 'Australia/Perth', 'Australia/Queensland', 'Australia/South', 'Australia/Sydney', 'Australia/Tasmania', 'Australia/Victoria', 'Australia/West', 'Australia/Yancowinna', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Athens', 'Europe/Belfast', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Bratislava', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Dublin', 'Europe/Gibraltar', 'Europe/Guernsey', 'Europe/Helsinki', 'Europe/Isle_of_Man', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Lisbon', 'Europe/Ljubljana', 'Europe/London', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Mariehamn', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Nicosia', 'Europe/Oslo', 'Europe/Paris', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/San_Marino', 'Europe/Sarajevo', 'Europe/Simferopol', 'Europe/Skopje', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Tiraspol', 'Europe/Uzhgorod', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zagreb', 'Europe/Zaporozhye', 'Europe/Zurich', 'Indian/Antananarivo', 'Indian/Chagos', 'Indian/Christmas', 'Indian/Cocos', 'Indian/Comoro', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Mayotte', 'Indian/Reunion', 'Pacific/Apia', 'Pacific/Auckland', 'Pacific/Chatham', 'Pacific/Easter', 'Pacific/Efate', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Funafuti', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Johnston', 'Pacific/Kiritimati', 'Pacific/Kosrae', 'Pacific/Kwajalein', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Midway', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pago_Pago', 'Pacific/Palau', 'Pacific/Pitcairn', 'Pacific/Ponape', 'Pacific/Port_Moresby', 'Pacific/Rarotonga', 'Pacific/Saipan', 'Pacific/Samoa', 'Pacific/Tahiti', 'Pacific/Tarawa', 'Pacific/Tongatapu', 'Pacific/Truk', 'Pacific/Wake', 'Pacific/Wallis', 'Pacific/Yap', 'UTC');
[5341]17
[6791]18    public function format($data, $params = false)
19    {
20                $timezones = array_flip(self::$timezonesMap);
21                $sytemTimezone = (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo';
22                $params['defaultTZI'] = self::nomalizeTZID((isset($params['defaultTZI']) && $params['defaultTZI'] != 'null') ? $params['defaultTZI'] : $sytemTimezone );
23                $params['X-WR-TIMEZONE'] = isset($timezones[$params['defaultTZI']]) ? $timezones[$params['defaultTZI']] : $params['defaultTZI'];
24               
25                return (isset($params['compatible']) && $params['compatible']) ?
26                                        array('ical' => $this->createIcal($data, $params) , 'compatible' => $this->createCompatibleIcal($data, $params)) :
27                                        $this->createIcal($data, $params);
[6011]28
[6791]29    }
[5341]30
[6791]31    protected function createIcal($data, $params = false )
32    {
[7660]33        $ical = new vcalendar();
[6791]34                $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
[5341]35
[6791]36                /*
37                 * Seta propiedades obrigatorias para alguns softwares (Outlook)
38                 */
39                $ical->setProperty('x-wr-calname', 'Calendar Expresso');
40                $ical->setProperty('X-WR-CALDESC', 'Calendar Expresso');
41                $ical->setProperty('X-WR-TIMEZONE', $params['X-WR-TIMEZONE']);
[5341]42
[6791]43                foreach ($data as $i => $v) {
[5341]44
[6791]45                    switch ($v['type']) {
46                        case EVENT_ID:
47                            $vevent = $ical->newComponent('vevent');
[6066]48
[6791]49                            $vevent->setProperty('summary', $v['summary']);
50                            $vevent->setProperty('description', isset($v['description']) ? $v['description'] : '');
51                            $vevent->setProperty('location', $v['location']);
52                            $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
[6066]53
[6791]54                            $timezone = new DateTimeZone('UTC');
55                            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
56                            $apTimezoneOBJ = new DateTimeZone($apTimezone);
[6066]57
[6791]58                            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
59                            $sTime->setTimezone($apTimezoneOBJ);
[6066]60
[7243]61                $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
62                $eTime->setTimezone($apTimezoneOBJ);
63
[6791]64                            if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' ))
65                                    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
[6066]66
[7702]67                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
68
[7068]69                            if (isset($v['allDay']) && $v['allDay'] == 1)
70                {
71                    $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
72                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
[7243]73                    $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
74                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
[7068]75                            } else
76                {
77                    $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
78                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
[7243]79                    $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
80                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
[6066]81                            }
[6791]82                                           
83                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
84                                $participants = $v['participants'];
85                            else
86                                        $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
87                           
88                                if (is_array($participants) && count($participants) > 0)
89                                        foreach ($participants as $ii => $vv) {
90                                       
91                                                if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
92                                                {
93                                                        if ($vv['isExternal'] == 1)
94                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
95                                                        else
96                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
97                                                }
98                                       
99                                                if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
100                                                {
101                                                        $alarms = (isset($participants[$ii]['alarms'])) ? $participants[$ii]['alarms'] : Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id']))));
102                                                        if(is_array($alarms))
103                                                                self::createAlarms($alarms, $vevent);
104                                                }
105                                       
106                                        }
107                           
108                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
109                                        $this->createAttendee($v['participants'], $vevent);
[6066]110
[6791]111                            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
112                                        $this->createAttachment($v['attachments'], $vevent);
113
[7579]114                            $vevent->setProperty('uid', $v['uid']);
115
116                $timezoneDayligth = Controller::read(array('concept' => 'timezones'), null, array('filter' => array('=', 'tzid', $apTimezone)));
117
118                if(!empty( $timezoneDayligth ) && count( $timezoneDayligth ) > 0){
119
120                    if(array_key_exists(0, $timezoneDayligth))
121                        $timezoneDayligth = $timezoneDayligth[0];
122
123                    date_default_timezone_set('UTC');
124
125                    require_once ROOTPATH . '/plugins/when/When.php';
126
127                    $r = new When();
128
129                    $start = new DateTime('1970-01-01 '.$timezoneDayligth['standardDtstart']);
130
131                    $r = new When();
132                    $r->recur($start, $timezoneDayligth['standardFrequency'])
133                        ->until($start->modify('+1 years'))
134                        ->bymonth(array( $timezoneDayligth['standardBymonth'] ))
135                        ->byday(array(  $timezoneDayligth['daylightByday'] ));
136
137                   $date = $r->next();
138
[7660]139                    $timezone = $ical->newComponent('vtimezone');
[7579]140                    $timezone->setProperty('tzid',$apTimezone );
141
[7660]142                    $standard  = $timezone->newComponent( "standard" );
[7579]143                    $standard->setProperty( "tzoffsetfrom", $timezoneDayligth['standardFrom'] );
144                    $standard->setProperty( "tzoffsetto", $timezoneDayligth['standardTo'] );
145
146
147                    $standard->setProperty( "dtstart", $date->format(DATE_RFC822), array("VALUE" => "DATE") );
148
149                    $rrule = array(
150                        'FREQ' => $timezoneDayligth['standardFrequency'],
151                        'BYMONTH' =>  $timezoneDayligth['standardBymonth'],
152                        'BYday' => array(preg_replace("/[^0-9]/", "", $timezoneDayligth['standardByday']),  "DAY" => preg_replace("/[^a-zA-Z\s]/", "", $timezoneDayligth['standardByday']))
153                    );
154
155                    $standard->setProperty('rrule', $rrule);
156
[7660]157                    $daylight  = $timezone->newComponent( "daylight" );
[7579]158
159                    $daylight->setProperty( "tzoffsetfrom", $timezoneDayligth['daylightFrom'] );
160                    $daylight->setProperty( "tzoffsetto", $timezoneDayligth['daylightTo'] );
161
162
163                    $start = new DateTime('1970-01-01 '.$timezoneDayligth['daylightDtstart']);
164
165                    $r->recur($start, $timezoneDayligth['daylightFrequency'])
166                        ->until($start->modify('+1 years'))
167                        ->bymonth(array( $timezoneDayligth['daylightBymonth'] ))
168                        ->byday(array(  $timezoneDayligth['daylightByday'] ));
169
170                    $date = $r->next();
171
172                    $daylight->setProperty( "dtstart", $date->format(DATE_RFC822), array("VALUE" => "DATE") );
173
174                    $rrule = array(
175                        'FREQ' => $timezoneDayligth['daylightFrequency'],
176                        'BYMONTH' =>  $timezoneDayligth['daylightBymonth'],
177                        'BYday' => array(preg_replace("/[^0-9]/", "", $timezoneDayligth['daylightByday']),  "DAY" => preg_replace("/[^a-zA-Z\s]/", "", $timezoneDayligth['daylightByday']))
178                    );
179
180                    $daylight->setProperty('rrule', $rrule);
181                }
182
[6791]183                            break;
[7028]184            case TODO_ID:
[6791]185
[7006]186                $todo = $ical->newComponent('todo');
187
188                $todo->setProperty('summary', $v['summary']);
189                $todo->setProperty('description', isset($v['description']) ? $v['description'] : '');
190                $todo->setProperty('priority', $v['priority']);
191                $todo->setProperty('percent-complete', $v['percentage']);
192                $todo->setProperty('status', $this->_getStatusTodo($v['status']));
193
194                $timezone = new DateTimeZone('UTC');
195                $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
196                $apTimezoneOBJ = new DateTimeZone($apTimezone);
197
198                $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
199                $sTime->setTimezone($apTimezoneOBJ);
200                $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
201                $eTime->setTimezone($apTimezoneOBJ);
202
[7702]203                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
204
[7006]205                if (isset($v['allDay']) && $v['allDay'] == 1) {
206                    $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
207                    $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
208                    //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
209                } else {
210                    $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
211                    $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
212                    //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
213                }
214
[7028]215                if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
[7006]216                    $dueTime = new DateTime('@' . (int) ($v['due'] / 1000), $timezone);
217                    $dueTime->setTimezone($apTimezoneOBJ);
218
219                    $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
[7028]220                    $todo->setProperty('dueTime', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
221                }               
[7006]222                       
223                if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
224                    $participants = $v['participants'];
225                else
226                    $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
227               
228                if (is_array($participants) && count($participants) > 0)
229                    foreach ($participants as $ii => $vv) {
230                   
231                        if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
232                        {
233                            if ($vv['isExternal'] == 1)
234                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
235                            else
236                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
237                        }
238                   
239                        if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
240                        {
241                            $alarms = (isset($participants[$ii]['alarms'])) ? $participants[$ii]['alarms'] : Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id']))));
242                            if(is_array($alarms))
243                                self::createAlarms($alarms, $todo);
244                        }
245                   
246                    }
247
248                if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
249                    $this->createAttendee($v['participants'], $todo);
250
251                if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
252                    $this->createAttachment($v['attachments'], $todo);
253
254                $todo->setProperty('uid', $v['uid']); 
255               
256                break;
[6791]257                        default:
258                            break;
[6066]259                    }
[7068]260                }
[6791]261                return $ical->createCalendar();
262    }
263
264    protected function createCompatibleIcal($data, $params = false )
265    {
[7660]266        $ical = new vcalendar();
[6791]267                $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
268
269                /*
270                 * Seta propiedades obrigatorias para alguns softwares (Outlook)
271                 */
272                $ical->setProperty('x-wr-calname', 'Calendar Expresso');
273                $ical->setProperty('X-WR-CALDESC', 'Calendar Expresso');
274                $ical->setProperty('X-WR-TIMEZONE', $params['X-WR-TIMEZONE']);
275
276                foreach ($data as $i => $v) {
277
278                    switch ($v['type']) {
279                        case EVENT_ID:
280                            $vevent = $ical->newComponent('vevent');
281
282                            $vevent->setProperty('summary', $v['summary']);
283                            $vevent->setProperty('description', isset($v['description']) ? $v['description'] : '');
284                            $vevent->setProperty('location', $v['location']);
285                            $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
286
[7702]287                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
288
[6791]289                            $timezone = new DateTimeZone('UTC');
290                            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
291                            $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
292
293                            if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' ))
294                                    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
295
296                            if (isset($v['allDay']) && $v['allDay'] == 1) {
297                                $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
298                                $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
299                                $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
300                            } else {
301                                $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822));
302                                $vevent->setProperty('dtend', $eTime->format(DATE_RFC822));
303                                $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
304                            }
305                                           
306                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
307                                $participants = $v['participants'];
308                            else
309                                        $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
310                           
311                                if (is_array($participants) && count($participants) > 0)
312                                        foreach ($participants as $ii => $vv) {
313                                       
314                                                if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
315                                                {
316                                                        if ($vv['isExternal'] == 1)
317                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
318                                                        else
319                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
320                                                }
321                                       
322                                                if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
323                                                {
324                                                        $alarms = (isset($participants[$ii]['alarms'])) ? $participants[$ii]['alarms'] : Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id']))));
325                                                        if(is_array($alarms))
326                                                                self::createAlarms($alarms, $vevent);
327                                                }
328                                       
[6094]329                                        }
[6791]330                           
[6066]331
[6791]332                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
333                                        $this->createAttendee($v['participants'], $vevent);
[6066]334
[6791]335                            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
336                                        $this->createAttachment($v['attachments'], $vevent);
[6066]337
[6791]338                            $vevent->setProperty('uid', $v['uid']); 
339                           
340                            break;
[6066]341
[6791]342                        default:
343                            break;
[6996]344                       
[7028]345        case TODO_ID:
[6066]346
[6996]347            $todo = $ical->newComponent('todo');
348
349            $todo->setProperty('summary', $v['summary']);
350            $todo->setProperty('description', isset($v['description']) ? $v['description'] : '');
351            $todo->setProperty('priority', $v['priority']);
352            $todo->setProperty('percent-complete', $v['percentage']);
353            $todo->setProperty('status', $this->_getStatusTodo($v['status']));
354
[7702]355            $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
356
[6996]357            $timezone = new DateTimeZone('UTC');
358            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
359            $apTimezoneOBJ = new DateTimeZone($apTimezone);
360
361            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
362            $sTime->setTimezone($apTimezoneOBJ);
363
364            if (isset($v['allDay']) && $v['allDay'] == 1) {
365                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
366                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
367            } else {
368                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
369                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
370            }
371
[7028]372            if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
[6996]373                $dueTime = new DateTime('@' . (int) ($v['due'] / 1000), $timezone);
374                $dueTime->setTimezone($apTimezoneOBJ);
375
376                $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
377            }
378                   
379            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
380                $participants = $v['participants'];
381            else
382                $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
383           
384            if (is_array($participants) && count($participants) > 0)
385                foreach ($participants as $ii => $vv) {
386               
387                    if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
388                    {
389                        if ($vv['isExternal'] == 1)
390                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
391                        else
392                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
393                    }
394               
395                    if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
396                    {
397                        $alarms = (isset($participants[$ii]['alarms'])) ? $participants[$ii]['alarms'] : Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id']))));
398                        if(is_array($alarms))
399                            self::createAlarms($alarms, $todo);
400                    }
401               
402                }
403
404            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
405                $this->createAttendee($v['participants'], $todo);
406
407            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
408                $this->createAttachment($v['attachments'], $todo);
409
410            $todo->setProperty('uid', $v['uid']); 
411           
412            break;
413
414                default:
415                    break;
416            }
417        }
418
[6171]419       
[6996]420        return $ical->createCalendar();
[5341]421    }
[6791]422
423    protected function formatIcalRepeat($pRepeat)
424    {
425        $repeat = array();
426
427                foreach ($pRepeat as $ir => $rv) {
428                    if ($rv) {
[7579]429                if ($ir == 'frequency' && $rv !== 'none')
430                    $repeat['FREQ'] = $rv;
431                else if ($ir == 'endTime') {
432                    $time = new DateTime('@' . (int) ($rv / 1000), new DateTimeZone('UTC'));
433                    $time->setTimezone($apTimezoneOBJ);
434                    $repeat['until'] = $time->format(DATE_RFC822);
435                }else if ($ir == 'count')
436                    $repeat[$ir] = $rv;
437                else if ($ir == 'interval')
438                    $repeat[$ir] = $rv;
439                else if ($ir !== 'schedulable' && $ir !== 'id' && $ir !== 'startTime')
440                    $repeat[$ir] = explode(',', $rv);
[6791]441                    }
442                }
443                return $repeat;
444    }
445
[6094]446   
447    public function createAlarms($alarms, &$vevent)
448    {   
[7068]449            foreach ($alarms as $va)
[6094]450            {
451                $valarm = new valarm();
452                $valarm->setProperty('ACTION' , self::codeAlarmAction($va['type']));
453               
454                $duration = array();
455               
456                switch ($va['unit'])
457                {
458                        case 'h':
459                                $duration['hour'] = $va['time'];
460                        break;
461                        case 'm':
462                                $duration['min'] = $va['time'];
463                        break;
464                        case 's':
465                                $duration['sec'] = $va['time'];
466                                break;
467                }
468               
469                $valarm->setProperty('trigger' ,$duration);
470                $vevent->setComponent($valarm);
471            }   
472       
473    }
[6066]474
475    //Trata a criacao de anexos do ics
476    public function createAttachment($attachments, &$vevent) {
477        foreach ($attachments as $key => $attachment) {
478            $pParams = array("ENCODING" => "BASE64", "VALUE" => "BINARY",
479                "X-FILENAME" => $attachment['name']);
480
481            $vevent->setProperty("attach", $attachment['source'], $pParams);
[5514]482        }
[6066]483    }
484
485    //Trata a criacao de attendees com tratamento de delegate
486    public function createAttendee($attendees, &$vevent) {
487        $delegate = array();
488        foreach ($attendees as $di => $dv) {
489            if (isset($dv['delegatedFrom']) && $dv['delegatedFrom'] != 0) {
490                $delegate[$dv['delegatedFrom']] = $dv;
491            }
492        }
493
494        foreach ($attendees as $pi => $pv) {
495            $isResponseDelegated = false;
[6321]496            if ((isset($pv['delegatedFrom']) && $pv['delegatedFrom'] == 0) || !isset($pv['delegatedFrom']))  {
[6066]497                if ($pv['isOrganizer'] == 1)
498                    $vevent->setProperty('organizer', $pv['user']['mail'], array('CN' => $pv['user']['name']));
499                else {
500                    $pParams = array();
501                    $pParams['CN'] = $pv['user']['name'];
502                    $pParams['PARTSTAT'] = self::_getStatus($pv['status']);
503
504                    if (isset($pv['id']) && isset($delegate[$pv['id']])) {
505                        $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
506                        $pParams['DELEGATED-TO'] = $delegate[$pv['id']]['user']['mail'];
507                        $pParams['CN'] = $pv['user']['name'];
508
509                        $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
510
511                        if ($delegate[$pv['id']]['status'] == STATUS_UNANSWERED) {
512                            $pParams['RSVP'] = $pv['receiveNotification'] == 1 ? 'TRUE' : 'FALSE';
513                            unset($pParams['PARTSTAT']);
514                        }else
515                            $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
516
517                        unset($pParams['DELEGATED-TO']);
518                        $pParams['DELEGATED-FROM'] = $pv['user']['mail'];
519
520                        $vevent->setProperty('attendee', $delegate[$pv['id']]['user']['mail'], $pParams);
521                        continue;
522                    }
523                    $pParams['RSVP'] = 'TRUE';
524
525                    $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
[6094]526
[5514]527                }
[6066]528            }
[6094]529           
530           
[6066]531        }
532    }
[5514]533
[6066]534    public function parse($data, $params = false) {
535        Config::regSet('noAlarm', TRUE); //Evita o envio de notificação
[7660]536        $vcalendar = new vcalendar( );
[6066]537        $vcalendar->parse(trim($data));
538        $vcalendar->sort();
539
540        $return = array();
541        $method = $vcalendar->getProperty('method', FALSE, FALSE);
542        $params['prodid'] = $vcalendar->getProperty('prodid', false, false);
[6215]543        $params['X-WR-TIMEZONE'] = ( $xrTimezone = $vcalendar->getProperty('X-WR-TIMEZONE', false, false)) ? self::nomalizeTZID($xrTimezone[1]) : false ;
[6066]544
545        while ($component = $vcalendar->getComponent()) {
546            $interation = array();
547            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
548
549            switch (strtoupper($component->objName)) {
550                case 'VEVENT':
551
[7702]552
[6066]553                    switch ($method) {
554                        case 'PUBLISH':
[6344]555                            //Caso o evento não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
[7006]556                if (!$schedulable = self::_getSchedulable($uid))
557                                    $interation = self::_makeVEVENT($schedulable, $component, $params);
558                else{
559                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
560                                        array('AND',
561                                            array('=', 'calendar', $params['calendar']),
562                                            array('=', 'schedulable', $schedulable['id'])
563                                        )));
[6344]564
[7006]565                    if(!$links &&  !isset($links[0]))
566                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
[6344]567
[7006]568                    }
[6066]569                            break;
570
571                        case 'REQUEST':
572                            $schedulable = self::_getSchedulable($uid);
[7695]573                $calendar = false;
[6066]574
575                            if ($schedulable) { //Caso o evento exista
[7695]576                    if (!($calendar = self::_existInMyCalendars($schedulable['id'], $params['owner']) )) {
577                        $calendarToSchedulable = array();
578                        $calendarToSchedulable['calendar'] = $params['calendar'];
579                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
580                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
581
582                        if (isset($params['status'])) {
583                            if($params['owner'] != Config::me("uidNumber")){
584                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );
585                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
586                            }else{
587                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
588                                //caso nõa seja participante adiciona a lista de participantes
589                                if(!$pID){
590                                    $pID =  mt_rand() . '2(Formatter)';
591                                    $interation['participant://' . $pID]['status'] = $params['status'];
592                                    $interation['participant://' . $pID]['user'] = $params['owner'];
593                                    $interation['participant://' . $pID]['isOrganizer'] = '0';
594                                    $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
595                                }else
596                                    $interation['participant://' . $pID]['status'] = $params['status'];
597                            }
[7006]598                        }
[6066]599
[7695]600                        Config::regSet('noAlarm', FALSE); //reativa notificação
601                    } else {
[6066]602
[7695]603                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']){ //Organizador esta requisitando que você atualize o evento
[6066]604
[7695]605                            $params['calendar'] = $params['calendar'] == 'true' ? $calendar : $params['calendar'];
606                            $interation = self::_makeVEVENT($schedulable, $component, $params);
607                        }else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
608                            //Ler melhor rfc sobre isto 3.2.2.2
609                            //Aparentemente é para retornar um ical com o evento atualizado para o attende
610                        }
[5341]611
[7695]612                        if (isset($params['status'])) {
613                            if($params['owner'] != Config::me("uidNumber")){
614                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );
615                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
616                            }else
617                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
618                            //Verifica a importação de eventos em que não participo
619                            if ($pID) {
[7702]620
[7695]621                                $interation['participant://' . $pID]['status'] = $params['status'];
[7702]622
[7695]623                            }
624                        }
625                    }
626                } else { // Importar evento
627                    $interation = self::_makeVEVENT(array(), $component, $params);
[5916]628
[7695]629                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
[5682]630
[7695]631                        /* Data de Inicio */
632                        $startTime = $component->getProperty('dtstart', false, true);
[6215]633
[7695]634                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
[5682]635
[7695]636                        /* Tiem zone do evento */
637                        if ($tzid)
638                        $sc['timezone'] = self::nomalizeTZID($tzid);
639                        else
640                        $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
[5682]641
[7695]642                        $objTimezone = new DateTimeZone($sc['timezone']);
[5682]643
[7695]644                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
645                        $sc['allDay'] = 1;
646                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
647                        } elseif (isset($startTime['params']['TZID']) && !isset($startTime['value']['tz']))/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
648                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
649                        else {
650                        $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
651                        if (strpos($params['prodid'], 'Outlook') !== false) {
652                            //Se o ics veio em utc não aplicar horario de verão
653                            $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
654                            $sTime->setTimezone($objTimezone);
655                            if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
656                            $sc['startTime'] = $sc['startTime'] - 3600000;
657                        }
658                        }
[5682]659
660
[7695]661                        /* Data de Termino */
662                        $endTime = $component->getProperty('dtend', false, true);
[5682]663
[7695]664                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
665                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
666                        else if (isset($endTime['params']['TZID']) && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
667                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
668                        else {
669                        $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
670                        if (strpos($params['prodid'], 'Outlook') !== false) {
671                            //Se o ics veio em utc não aplicar horario de verão
672                            $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
673                            $eTime->setTimezone($objTimezone);
674                            if ($eTime->format('I'))
675                            $sc['endTime'] = $sc['endTime'] - 3600000;
676                        }
677                        }
[5682]678
679
[7695]680                        if ($uid = $component->getProperty('uid', false, false))
681                        ;
682                        $sc['uid'] = $uid;
[5682]683
684
[7695]685                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
[5682]686
[7695]687                        /* Definindo Description */
688                        if ($desc = $component->getProperty('description', false, false))
689                        $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
[5682]690
[7695]691                        /* Definindo location */
692                        if ($location = $component->getProperty('location', false, false))
693                        $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
[5682]694
[5736]695
[5682]696
[7695]697                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
698                        $participant = array();
699                        $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
[5682]700
[7695]701                        $participantID = mt_rand() . '2(Formatter)';
[5682]702
[7695]703                        $participant['isOrganizer'] = '1';
[5682]704
[7695]705                        $user = null;
[5341]706
[7695]707                        $participant['isExternal'] = 1;
708                        /* Gera um randon id para o contexto formater */
709                        $userID = mt_rand() . '4(Formatter)';
[5341]710
[7695]711                        $user['mail'] = $mailUser;
712                        $organizerMail = $mailUser;
[5341]713
[7695]714                        $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
715                        $user['isExternal'] = '1';
716                        $participant['user'] = $user;
[5341]717
[7695]718                        $sc['participants'][] = $participant;
719                        }
[5341]720
721
[7695]722                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
723                        $participant['isOrganizer'] = '0';
724                        $participant['isExternal'] = 0;
725                        $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
726                        $sc['participants'][] = $participant;
727                        $sc['type'] = EVENT_ID;
[5341]728
[5903]729
[7695]730                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
731                        $ical['type'] = 'application/ics';
732                        $ical['name'] = 'outlook.ics';
[5947]733
[7695]734                        $ical2['source'] = $ical['source'];
735                        $ical2['type'] = 'text/calendar; method=REPLY';
736                        $ical2['name'] = 'thunderbird.ics';
[5341]737
[7695]738                        $timezone = new DateTimeZone('UTC');
739                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
740                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
[5341]741
[7695]742                        if (isset($sc['timezone'])) {
743                        $sTime->setTimezone(new DateTimeZone($sc['timezone']));
744                        $eTime->setTimezone(new DateTimeZone($sc['timezone']));
745                        }
[5341]746
[7695]747                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
748                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
749                        'endDate' => date_format($eTime, 'd/m/Y'),
750                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
751                        'eventTitle' => $sc['summary'],
752                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
753                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
754                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
[5341]755
[7695]756                        $subject['notificationType'] = 'Convite Aceito';
757                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
758                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
759                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
760                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
761                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
762                        $subject['participant'] = Config::me('uid');
[5341]763
[7695]764                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
[5344]765
[7695]766                        switch ($params['status']) {
767                        case STATUS_ACCEPTED:
768                            $tpl = 'notify_accept_body';
769                            $subject['notificationType'] = 'Convite Aceito';
770                            break;
771                        case STATUS_TENTATIVE:
772                            $tpl = 'notify_attempt_body';
773                            $subject['notificationType'] = 'Convite  aceito provisoriamente';
774                            break;
775                        case STATUS_CANCELLED:
776                            $tpl = 'notify_reject_body';
777                            $subject['notificationType'] = 'Convite rejeitado';
778                            break;
779                        }
780                        require_once ROOTPATH . '/api/parseTPL.php';
[5344]781
[7695]782                        $mail = array();
783                        $mail['attachments'][] = $ical;
784                        $mail['attachments'][] = $ical2;
[5344]785
[7695]786                        $mail['isHtml'] = true;
787                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
788                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
789                        ;
790                        $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
791                        $mail['to'] = $organizerMail;
[5344]792
[7695]793
794                        Controller::create(array('service' => 'SMTP'), $mail);
795                    }
[6066]796                            }
797                            break;
[5344]798
[6066]799                        case 'REFRESH':
800                            break;
[5341]801
[6066]802                        case 'CANCEL':
803                            if ($schedulable = self::_getSchedulable($uid))
804                                $interation['schedulable://' . $schedulable['id']] = false;
805                            break;
[6861]806                               
[6066]807                        case 'ADD':
808                            break;
[5344]809
[6066]810                        case 'REPLY':
811                            if ($schedulable = self::_getSchedulable($uid)) {
812                                while ($property = $component->getProperty('attendee', FALSE, TRUE))
813                                    if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
814                                        $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
[5344]815
[6066]816                                $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
817                            }
818                            break;
[5341]819
[6066]820                        case 'COUNTER':
821                            if ($params['acceptedSuggestion'] !== 'false') {
[5341]822
[6066]823                                $schedulable = self::_getSchedulable($uid);
[6331]824                                $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
[6066]825
826                                $interation = self::_makeCOUNTER($schedulable, $component, $params);
827                                Config::regSet('noAlarm', FALSE);
828                            } else {
829                                $response = array();
830                                $response['from'] = $params['from'];
831                                $response['type'] = 'suggestionResponse';
832                                $response['status'] = 'DECLINECOUNTER';
833                                $response['schedulable'] = self::_getSchedulable($uid);
834
835                                Controller::create(array('concept' => 'notification'), $response);
836                            }
837                            break;
838
839                        case 'DECLINECOUNTER':
840                            break;
841
842                        default:
843
844                            $schedulable = self::_getSchedulable($uid);
845
846                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
847                                $interation = self::_makeVEVENT($schedulable, $component, $params);
848
[6331]849                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
[6066]850                                    $calendarToSchedulable = array();
851                                    $calendarToSchedulable['calendar'] = $params['calendar'];
852                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
853                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
[5514]854                                }
[6066]855                            }
856                            else // Importar evento
857                                $interation = self::_makeVEVENT(array(), $component, $params);
858                            break;
859                    }
[7702]860
[6066]861                    $return[] = $interation;
862                    break;
[6996]863        /***********************************************************************TODO*******************************************************************************/
864        case 'VTODO':
865        switch ($method) {
866            case 'PUBLISH':
867                //Caso a tarefa não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
868                if (!$schedulable = self::_getSchedulable($uid))
869                    $interation = self::_makeVTODO($schedulable, $component, $params);
870                else{
871                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
872                    array('AND',
873                        array('=', 'calendar', $params['calendar']),
874                        array('=', 'schedulable', $schedulable['id'])
875                    )));
[6066]876
[6996]877                    if(!$links &&  !isset($links[0]))
878                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
879                }
880                break;
[6066]881
[6996]882            case 'REQUEST':
883                $schedulable = self::_getSchedulable($uid);
884
885                if ($schedulable) { //Caso tarefa exista
886                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
887                       
888                        $calendarToSchedulable = array();
889                        $calendarToSchedulable['calendar'] = $params['calendar'];
890                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
891                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
892       
893                        if (isset($params['status'])) {
894                            if($params['owner'] != Config::me("uidNumber")){                       
895                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                       
896                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
897                            }else
898                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
899                                $interation['participant://' . $pID]['status'] = $params['status'];
900                        }
901                        Config::regSet('noAlarm', FALSE); //reativa notificação
902                    } else {
903
904                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
905                            $interation = self::_makeVEVENT($schedulable, $component, $params);
906                        else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
907                        //Ler melhor rfc sobre isto 3.2.2.2
908                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
909                        }
910
911                        if (isset($params['status'])) {
912                            if($params['owner'] != Config::me("uidNumber")){                       
913                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                     
914                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
[7028]915                            }else{
[6996]916                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
[7028]917                                //Verifica a importação de tarefas em que não participo
918                                if ($pID) {
919                                    $pID =  mt_rand() . '2(Formatter)';
920                                    $interation['participant://' . $pID]['status'] = $params['status'];
921                                    $interation['participant://' . $pID]['user'] = $params['owner'];
922                                    $interation['participant://' . $pID]['isOrganizer'] = '0';
923                                    $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
924                                }else
925                                    $interation['participant://' . $pID]['status'] = $params['status'];
[6996]926                            }
927                        }
928                    }
929                } else { // Importar tarefa
[7028]930                    $interation = self::_makeVTODO(array(), $component, $params);
[6996]931
932                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
933
934                        /* Data de Inicio */
935                        $startTime = $component->getProperty('dtstart', false, true);
936                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
937
938                        /* Tiem zone do evento */   
939                        if ($tzid)
940                            $sc['timezone'] = self::nomalizeTZID($tzid);
941                        else
942                            $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
943
944                        $objTimezone = new DateTimeZone($sc['timezone']);
945
946                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
947                            $sc['allDay'] = 1;
948                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
949                        } elseif (isset($startTime['params']['TZID']) && !isset($startTime['value']['tz']))/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
950                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
951                        else {
952                            $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
953                            if (strpos($params['prodid'], 'Outlook') !== false) {
954                                //Se o ics veio em utc não aplicar horario de verão
955                                $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
956                                $sTime->setTimezone($objTimezone);
957                                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
958                                $sc['startTime'] = $sc['startTime'] - 3600000;
959                            }
960                        }
961
962                        /* Data de Termino */
963                        $endTime = $component->getProperty('dtend', false, true);
964
965                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
966                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
967                        else if (isset($endTime['params']['TZID']) && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
968                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
969                        else {
970                            $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
971                            if (strpos($params['prodid'], 'Outlook') !== false) {
972                                //Se o ics veio em utc não aplicar horario de verão
973                                $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
974                                $eTime->setTimezone($objTimezone);
975                                if ($eTime->format('I'))
976                                    $sc['endTime'] = $sc['endTime'] - 3600000;
977                            }
978                        }
979
980
981                        if ($uid = $component->getProperty('uid', false, false))                   
982                            $sc['uid'] = $uid;
983
984                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
985
986                        /* Definindo Description */
987                        if ($desc = $component->getProperty('description', false, false))
988                            $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
989
990            if ($priority = $component->getProperty('priority', false, false))
991                $sc['priority'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $priority), 'UTF-8', 'UTF-8,ISO-8859-1');
992
993            if ($status = $component->getProperty('status', false, false))
994                $sc['status'] = $this->decodeStatusTodo(mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $status), 'UTF-8', 'UTF-8,ISO-8859-1'));
995
996            if ($percentage = $component->getProperty('percent-complete', false, false))
997                $sc['percentage'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $percentage), 'UTF-8', 'UTF-8,ISO-8859-1');
998
999                        /* Definindo location */
1000                        if ($location = $component->getProperty('location', false, false))
1001                            $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
1002
1003
1004
1005                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1006                            $participant = array();
1007                            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1008
1009                            $participantID = mt_rand() . '2(Formatter)';
1010
1011                            $participant['isOrganizer'] = '1';
1012
1013                            $user = null;
1014
1015                            $participant['isExternal'] = 1;
1016                            /* Gera um randon id para o contexto formater */
1017                            $userID = mt_rand() . '4(Formatter)';
1018
1019                            $user['mail'] = $mailUser;
1020                            $organizerMail = $mailUser;
1021
1022                            $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1023                            $user['isExternal'] = '1';
1024                            $participant['user'] = $user;
1025
1026                            $sc['participants'][] = $participant;
1027                        }
1028
1029
1030                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1031                        $participant['isOrganizer'] = '0';
1032                        $participant['isExternal'] = 0;
1033                        $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
1034                        $sc['participants'][] = $participant;
1035                        $sc['type'] = TODO_ID;
1036
1037
1038                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
1039                        $ical['type'] = 'application/ics';
1040                        $ical['name'] = 'outlook.ics';
1041
1042                        $ical2['source'] = $ical['source'];
1043                        $ical2['type'] = 'text/calendar; method=REPLY';
1044                        $ical2['name'] = 'thunderbird.ics';
1045
1046                        $timezone = new DateTimeZone('UTC');
1047                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
1048                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
1049
1050                        if (isset($sc['timezone'])) {
1051                            $sTime->setTimezone(new DateTimeZone($sc['timezone']));
1052                            $eTime->setTimezone(new DateTimeZone($sc['timezone']));
1053                        }
1054
1055                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
1056                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
1057                        'endDate' => date_format($eTime, 'd/m/Y'),
1058                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
1059                        'eventTitle' => $sc['summary'],
1060                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
1061                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
1062                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
1063
1064                        $subject['notificationType'] = 'Convite Aceito';
1065                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
1066                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
1067                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
1068                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
1069                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
1070                        $subject['participant'] = Config::me('uid');
1071
1072                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1073
1074                        switch ($params['status']) {
1075                            case STATUS_ACCEPTED:
1076                                $tpl = 'notify_accept_body';
1077                                $subject['notificationType'] = 'Convite Aceito';
1078                                break;
1079                            case STATUS_TENTATIVE:
1080                                $tpl = 'notify_attempt_body';
1081                                $subject['notificationType'] = 'Convite  aceito provisoriamente';
1082                                break;
1083                            case STATUS_CANCELLED:
1084                                $tpl = 'notify_reject_body';
1085                                $subject['notificationType'] = 'Convite rejeitado';
1086                                break;
1087                        }
1088
1089                        require_once ROOTPATH . '/api/parseTPL.php';
1090
1091                        $mail = array();
1092                        $mail['attachments'][] = $ical;
1093                        $mail['attachments'][] = $ical2;
1094
1095                        $mail['isHtml'] = true;
1096                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
1097                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
1098
1099                        $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
1100                        $mail['to'] = $organizerMail;
1101
1102
1103                        Controller::create(array('service' => 'SMTP'), $mail);
1104                    }
1105                }
1106                break;
1107
1108            case 'REFRESH':
1109                break;
1110
1111            case 'CANCEL':
1112                if ($schedulable = self::_getSchedulable($uid))
1113                    $interation['schedulable://' . $schedulable['id']] = false;
1114                break;
1115
1116            case 'ADD':
1117                break;
1118
1119            case 'REPLY':
1120                if ($schedulable = self::_getSchedulable($uid)) {
1121                    while ($property = $component->getProperty('attendee', FALSE, TRUE))
1122                        if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
1123                            $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
1124
1125                    $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
1126                }
1127                break;
1128
1129            case 'COUNTER':
1130                if ($params['acceptedSuggestion'] !== 'false') {
1131
1132                    $schedulable = self::_getSchedulable($uid);
1133                    $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
1134
1135                    $interation = self::_makeCOUNTER($schedulable, $component, $params);
1136                    Config::regSet('noAlarm', FALSE);
1137                } else {
1138                    $response = array();
1139                    $response['from'] = $params['from'];
1140                    $response['type'] = 'suggestionResponse';
1141                    $response['status'] = 'DECLINECOUNTER';
1142                    $response['schedulable'] = self::_getSchedulable($uid);
1143
1144                    Controller::create(array('concept' => 'notification'), $response);
1145                }
1146                break;
1147
1148            case 'DECLINECOUNTER':
1149                break;
1150
1151            default:
1152
1153                $schedulable = self::_getSchedulable($uid);
1154
1155                if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
1156                    $interation = self::_makeVEVENT($schedulable, $component, $params);
1157
1158                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
1159                        $calendarToSchedulable = array();
1160                        $calendarToSchedulable['calendar'] = $params['calendar'];
1161                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
1162                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
1163                    }
1164                }
1165                else // Importar evento
1166                $interation = self::_makeVEVENT(array(), $component, $params);
1167
1168                break;
1169            }
1170   
1171            $return[] = $interation;
1172        break;
1173        /***********************************************************************TODO*******************************************************************************/
1174        case 'VTIMEZONE':
1175                break;
[6066]1176            }
1177        }
1178        return $return;
1179    }
1180
1181    public function analize($data, $params = false) {
[7660]1182        $vcalendar = new vcalendar( );
[6066]1183        $vcalendar->parse(trim($data));
1184        $vcalendar->sort();
1185
1186        $return = array();
1187        $method = $vcalendar->getProperty('method', FALSE, FALSE);
1188
1189        while ($component = $vcalendar->getComponent()) {
1190            $interation = array();
1191            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
1192            switch (strtoupper($component->objName)) {
1193                case 'VEVENT':
1194
1195                    switch ($method) {
1196                        case 'PUBLISH':
[6996]1197                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
[6066]1198                            break;
1199
1200                        case 'REQUEST':
1201                            $schedulable = self::_getSchedulable($uid);
1202                            if ($schedulable) { //Caso o evento exista
[7695]1203                    $isOrganizer = false;
1204                    $isParticipant = false;
[6066]1205
[7695]1206                    foreach ($schedulable['participants'] as $value){
[6066]1207
[7695]1208                        if ($value['user']['id'] == $params['owner']) {
1209                            $isParticipant = true;
1210                            if ($value['isOrganizer'])
1211                                $isOrganizer = true;
[5863]1212
[7695]1213                            if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
1214                                $interation = ICAL_ACTION_UPDATE;
1215                                $interation = ( strrpos($value['acl'], ATTENDEE_ACL_PARTICIPATION_REQUIRED) ) ? ICAL_ACTION_IMPORT_REQUIRED : array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1216                                break;
1217                            }
1218                        } else {
1219                            if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1220                                $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1221                            else
1222                                $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1223                        }
[6331]1224
[7695]1225                    }
1226
1227                    if (!$isParticipant){
1228                        if( self::_existInMyCalendars($schedulable['id'], $params['owner']) ){
1229
1230                            $interation = (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] ? ICAL_ACTION_UPDATE  :  ICAL_ACTION_NONE);
1231
1232                        }else{
1233
1234                            $interation =  self::_checkParticipantByPermissions($schedulable);
1235
1236                        }
1237
1238
1239                    }
1240                }else
1241                    $interation = array('action' => ICAL_ACTION_IMPORT_REQUIRED, 'type' => 'calendarIds');
1242
1243                    if(($interation != ICAL_ACTION_NONE) && ($interation != ICAL_ACTION_ORGANIZER_NONE) && ($interation != ICAL_ACTION_ORGANIZER_UPDATE) && ($interation != ICAL_ACTION_NONE) && ($interation != ICAL_ACTION_UPDATE) && (!is_array($interation ) )) {
1244                        if($params['owner'] != Config::me("uidNumber")){
1245                            $sig = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=', 'user', $params['owner']), array('=', 'isOwner', '1'))));
1246                            $calendars = array();
1247                            foreach ($sig as $val)
1248                            $calendars[] = $val['calendar'];
1249
1250                            $calendarsPermission = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('=', 'user', Config::me("uidNumber")), array('IN', 'calendar', $calendars))));
1251
1252                            foreach ($calendarsPermission as $val)
1253                            $ids[] = $val['calendar'];
1254
1255                            $interation = array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION ,'calendar' => $ids);
1256                        }
1257                    }
1258
[6066]1259                            break;
1260
1261                        case 'REFRESH':
1262                            break;
1263
1264                        case 'CANCEL':
1265                            $interation = ICAL_ACTION_DELETE;
1266                            break;
1267
1268                        case 'ADD':
1269                            break;
1270
1271                        case 'REPLY':
[6861]1272                                if ($schedulable = self::_getSchedulable($uid)) {
1273                                        while ($property = $component->getProperty('attendee', FALSE, TRUE))
1274                                            if ($attendee = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants'], true))
1275                                                        $interation = (constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])) == $attendee['status']) ?  ICAL_ACTION_NONE : ICAL_ACTION_REPLY;
1276                            }else
1277                                $interation = ICAL_NOT_FOUND;
[6066]1278                            break;
1279
1280                        case 'COUNTER':
1281                            $interation = ICAL_ACTION_SUGGESTION;
1282                            break;
1283
1284                        case 'DECLINECOUNTER':
1285                            $interation = ICAL_ACTION_NONE;
1286                            break;
1287
1288                        default:
1289                            $schedulable = self::_getSchedulable($uid);
1290
1291                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1292                                $interation = ICAL_ACTION_UPDATE;
1293                            else if ($schedulable)
1294                                $interation = ICAL_ACTION_NONE;
1295                            else // Importar evento
[6996]1296                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
[6066]1297
1298                            break;
1299                    }
1300
1301                    $return[$uid] = $interation;
1302                    break;
[6996]1303                case 'VTODO':
1304                    switch ($method) {
1305                        case 'PUBLISH':
1306                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1307                            break;
[6066]1308
[6996]1309                        case 'REQUEST':
1310                            $schedulable = self::_getSchedulable($uid);
1311                           
1312                            if ($schedulable) { //Caso o evento exista
1313                                $isOrganizer = false;
1314                                $isParticipant = false;
[6066]1315
[6996]1316                                foreach ($schedulable['participants'] as $value)
1317                                    if ($value['user']['id'] == $params['owner']) {
1318                                        $isParticipant = true;
1319                                        if ($value['isOrganizer'])
1320                                            $isOrganizer = true;
1321
1322                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {   
1323                                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1324                                            break;
1325                                        }
1326                                    } else {
1327                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1328                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1329                                        else
1330                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1331                                    }
1332                                if (!$isParticipant){
1333                                      $interation = self::_checkParticipantByPermissions($schedulable);
1334                                    }
1335                            }else
1336                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1337                            break;
1338
1339                        case 'REFRESH':
1340                            break;
1341
1342                        case 'CANCEL':
1343                            $interation = ICAL_ACTION_DELETE;
1344                            break;
1345
1346                        case 'ADD':
1347                            break;
1348
1349                        case 'REPLY':
1350                            $interation = ICAL_ACTION_REPLY;
1351                            break;
1352
1353                        case 'COUNTER':
1354                            $interation = ICAL_ACTION_SUGGESTION;
1355                            break;
1356
1357                        case 'DECLINECOUNTER':
1358                            $interation = ICAL_ACTION_NONE;
1359                            break;
1360
1361                        default:
1362                            $schedulable = self::_getSchedulable($uid);
1363
1364                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1365                                $interation = ICAL_ACTION_UPDATE;
1366                            else if ($schedulable)
1367                                $interation = ICAL_ACTION_NONE;
1368                            else // Importar evento
1369                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1370
1371                            break;
1372                    }
1373
1374                    $return[$uid] = $interation;
[6066]1375                    break;
[6996]1376                case 'VTIMEZONE':
1377                break;
[6066]1378            }
1379        }
1380
1381        return $return;
1382    }
1383
1384    /* Helpers */
1385
1386    private static function _getTzOffset($rTz, $oTz = null, $time = 'now') {
1387        if ($oTz === null) {
1388            if (!is_string($oTz = date_default_timezone_get())) {
1389                return false; // A UTC timestamp was returned -- bail out!
1390            }
1391        }
1392        $origin_dtz = new DateTimeZone(self::nomalizeTZID($oTz));
1393        $remote_dtz = new DateTimeZone(self::nomalizeTZID($rTz));
1394        $origin_dt = new DateTime($time, $origin_dtz);
1395        $remote_dt = new DateTime("now", $remote_dtz);
1396
1397        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
1398
1399
1400        return $offset;
1401    }
1402
1403    private function _getStatus($id) {
1404        $a = array(
1405            STATUS_CONFIRMED => 'ACCEPTED',
1406            STATUS_CANCELLED => 'CANCELLED',
1407            STATUS_TENTATIVE => 'TENTATIVE',
1408            STATUS_UNANSWERED => 'NEEDS-ACTION',
1409            STATUS_DELEGATED => 'DELEGATED'
1410        );
1411
1412        return isset($a[$id]) ? $a[$id] : 'NEEDS-ACTION';
1413    }
1414
[6996]1415    public function decodeStatusTodo( $action )
1416    {
1417     $a = array(
1418        'NEED_ACTION' => STATUS_TODO_NEED_ACTION,
1419        'IN_PROGRESS' => STATUS_TODO_IN_PROGRESS  ,
1420        'COMPLETED' =>  STATUS_TODO_COMPLETED ,
1421        'CANCELLED'  => STATUS_TODO_CANCELLED
1422    );
1423
[7028]1424    return isset($a[$action]) ? $a[$action] : 'STATUS_TODO_NEED_ACTION';
[6996]1425   
1426    }
1427
1428
1429    private function _getStatusTodo($id) {
1430        $a = array(
1431            STATUS_TODO_NEED_ACTION => 'NEED_ACTION',
1432            STATUS_TODO_IN_PROGRESS => 'IN_PROGRESS',
1433            STATUS_TODO_COMPLETED => 'COMPLETED',
1434            STATUS_TODO_CANCELLED => 'CANCELLED'
1435        );
1436
1437    return isset($a[$id]) ? $a[$id] : 'NEED_ACTION';
1438    }
1439
[6295]1440    private static function _checkParticipantByPermissions($schedulable) {
1441
[7006]1442        $calendarIds = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=','isOwner','0'), array('=', 'user', Config::me("uidNumber")))));
[6295]1443
[7006]1444        if($calendarIds && isset($calendarIds[0])){
1445            $ids = array();
1446            foreach($calendarIds as $value)
1447                    array_push($ids, $value['calendar']);
[6295]1448
[7006]1449            $signaturesOfOwners = Controller::find(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('IN', 'calendar', $ids) , array('=','isOwner','1')), 'deepness' => 2 ));
1450           
1451            foreach($signaturesOfOwners as $value){
1452                        if(self::_getParticipantByMail($value['user']['mail'], $schedulable['participants'])){
1453                            $eventoFromCalendar = Controller::read( array( 'concept' => 'calendarToSchedulable') , false, array('filter' => array('AND', array('=','schedulable',$schedulable['id']), array('=','calendar', $value['calendar']['id']))));
[6295]1454
[7006]1455                            return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => array($value['calendar']['id']) );
1456                        }
1457            }   
1458        }
1459        return array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
[6295]1460    }
1461   
1462   
[7006]1463    private static function _getParticipantByMail($mail, &$participants, $isFull = false) {
[6066]1464        if ($participants && $participants != '')
1465            foreach ($participants as $i => $v)
1466                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
[6861]1467                      return !!$isFull ? $v : $v['id'];
[6066]1468        return false;
1469    }
1470
1471    static private function nomalizeTZID($TZID) {
1472        if (isset(self::$timezonesMap[$TZID]))
1473            return self::$timezonesMap[$TZID];
1474        else if (in_array($TZID, self::$suportedTimzones))
1475            return $TZID;
1476        else
1477            return date_default_timezone_get();
1478    }
1479
1480    static private function date2timestamp($datetime, $tz = null) {
1481        if (!isset($datetime['hour']))
1482            $datetime['hour'] = '0';
1483        if (!isset($datetime['min']))
1484            $datetime['min'] = '0';
1485        if (!isset($datetime['sec']))
1486            $datetime['sec'] = '0';
1487
1488        foreach ($datetime as $dkey => $dvalue)
1489            if ('tz' != $dkey)
1490                $datetime[$dkey] = (integer) $dvalue;
1491
1492        if ($tz)
1493            $datetime['tz'] = $tz;
1494
1495        $offset = ( isset($datetime['tz']) && ( '' < trim($datetime['tz']))) ? iCalUtilityFunctions::_tz2offset($datetime['tz']) : 0;
1496
1497        return gmmktime($datetime['hour'], $datetime['min'], ($datetime['sec'] + $offset), $datetime['month'], $datetime['day'], $datetime['year']);
1498    }
1499
1500    static private function _makeCOUNTER($schedulable, $component, $params) {
1501        $interation = array();
1502        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1503
1504        /* Data de Inicio */
1505        $startTime = $component->getProperty('dtstart', false, true);
1506
1507        /* Tiem zone do evento */
1508        if (isset($startTime['params']['TZID']))
1509            $schedulable['timezone'] = self::nomalizeTZID($startTime['params']['TZID']);
1510        else
1511            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1512
1513        $objTimezone = new DateTimeZone($schedulable['timezone']);
1514
1515        if ($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1516            $schedulable['allDay'] = 1;
1517            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1518        } elseif (isset($startTime['params']['TZID']) && !isset($startTime['value']['tz'])) {/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
1519            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID'], '@' . self::date2timestamp($startTime['value'])) . '000';
1520            $schedulable['allDay'] = 0;
1521        } else {
1522            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1523            if (strpos($params['prodid'], 'Outlook') !== false) {
1524                //Se o ics veio em utc não aplicar horario de verão
1525                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1526                $sTime->setTimezone($objTimezone);
1527                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1528                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1529            }
1530        }
1531
1532        /* Data de Termino */
1533        $endTime = $component->getProperty('dtend', false, true);
1534
1535        if ($endTime['params']['VALUE'] === 'DATE')
1536            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1537        else if (isset($endTime['params']['TZID']) && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
1538            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID'], '@' . self::date2timestamp($endTime['value'])) . '000';
1539        else {
1540            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1541            if (strpos($params['prodid'], 'Outlook') !== false) {
1542                //Se o ics veio em utc não aplicar horario de verão
1543                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1544                $eTime->setTimezone($objTimezone);
1545                if ($eTime->format('I'))
1546                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1547            }
1548        }
1549        unset($schedulable['participants']);
1550        $interation['schedulable://' . $eventID] = $schedulable;
1551
1552        return $interation;
1553    }
1554
[7006]1555    static private function _makeVEVENT($schedulable, $component, $params) {
1556        $interation = array();
1557        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
[6066]1558
[7006]1559        /* Data de Inicio */
1560        $startTime = $component->getProperty('dtstart', false, true);
[6066]1561
[7006]1562        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
[6248]1563
[7006]1564        /* Tiem zone do evento */
1565        if ($tzid){
1566            $tzid = self::nomalizeTZID($tzid);
1567            $schedulable['timezone'] = $tzid;
1568        }else
1569            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
[6066]1570
[7006]1571        $objTimezone = new DateTimeZone($schedulable['timezone']);
[6066]1572
[7702]1573        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' ) {
[7006]1574            $schedulable['allDay'] = 1;
1575            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1576        } elseif ($tzid && !isset($startTime['value']['tz'])) {/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
1577            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1578            $schedulable['allDay'] = 0;
1579        } else {
1580            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1581            if (strpos($params['prodid'], 'Outlook') !== false) {
1582                //Se o ics veio em utc não aplicar horario de verão
1583                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1584                $sTime->setTimezone($objTimezone);
1585                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1586                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1587            }
1588        }
[6066]1589
[7006]1590        /* Data de Termino */
1591        $endTime = $component->getProperty('dtend', false, true);
[6066]1592
[7006]1593        $tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
1594       
1595        if($tzid)
1596            $tzid = self::nomalizeTZID($tzid);
[6215]1597
[7006]1598        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
1599            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1600        else if ($tzid && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
1601            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($endTime['value'])) . '000';
1602        else {
1603            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1604            if (strpos($params['prodid'], 'Outlook') !== false) {
1605                //Se o ics veio em utc não aplicar horario de verão
1606                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1607                $eTime->setTimezone($objTimezone);
1608                if ($eTime->format('I'))
1609                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1610            }
1611        }
[6066]1612
1613
[7006]1614        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
[6066]1615
[7006]1616        /* Definindo Description */
1617        if ($desc = $component->getProperty('description', false, false))
1618            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
[6066]1619
[7006]1620        /* Definindo location */
1621        if ($location = $component->getProperty('location', false, false))
1622            $schedulable['location'] = mb_convert_encoding($location, 'ISO-8859-1', 'UTF-8,ISO-8859-1');
[6066]1623
1624
[7006]1625        /* Definindo Class */
1626        $class = $component->getProperty('class', false, false);
1627        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1628            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1629        else if (!isset($schedulable['class']))
1630            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
[6066]1631
[7006]1632        /* Definindo RRULE */
1633        if ($rrule = $component->getProperty('rrule', false, false)) {
1634            /* Gera um randon id para o contexto formater */
1635            $repeatID = mt_rand() . '3(Formatter)';
[6066]1636
[7006]1637            $repeat = array();
1638            $repeat['schedulable'] = $eventID;
[7660]1639            $repeat['startTime'] = $schedulable['startTime'];
1640            foreach ($rrule as $i => $v) {
[7006]1641                if (strtolower($i) == 'freq')
1642                    $repeat['frequency'] = $v;
1643                else if (strtolower($i) == 'until')
[7660]1644            {
1645                $repeat['endTime'] = strtotime($v['year'].'-'.$v['month'].'-'.$v['day'].' '.$v['hour'].':'.$v['min'].':'.$v['sec'].' '.$v['tz']) .'000' ;
1646            }
[7006]1647                else
1648                    $repeat[strtolower($i)] = $v;
1649            }
[5415]1650
[7006]1651            $interation['repeat://' . $repeatID] = $repeat;
1652        }
[5415]1653
[7006]1654        $schedulable['calendar'] = $params['calendar'];
[5415]1655
[7006]1656        $participantsInEvent = array();
[5415]1657
[7006]1658        //TODO: Participants com delegated nao estao sendo levados em conta
1659        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1660            $participant = array();
[5415]1661
[7006]1662            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
[5415]1663
[7006]1664            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
1665            $participant['schedulable'] = $eventID;
[5415]1666
[7006]1667            if (isset($params['status']) && $mailUser == Config::me('mail'))
1668                $participant['status'] = $params['status'];
1669            else
1670                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
[5415]1671
1672
[7006]1673            $participant['isOrganizer'] = '0';
[5415]1674
[7006]1675            /* Verifica se este usuario é um usuario interno do ldap */
1676            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
[5415]1677
[7702]1678            $user = null;
[7006]1679            if ($intUser && count($intUser) > 0) {
1680                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1681                $participant['user'] = $intUser[0]['id'];
1682            } else {
1683                $participant['isExternal'] = 1;
1684                /* Gera um randon id para o contexto formater */
1685                $userID = mt_rand() . '4(Formatter)';
[5415]1686
[7006]1687                $user['mail'] = $mailUser;
1688                $user['isExternal'] = '1';
1689                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1690                $user['participants'] = array($participantID);
1691                $participant['user'] = $userID;
1692                $interation['user://' . $userID] = $user;
1693            }
[5415]1694
[7006]1695            $interation['participant://' . $participantID] = $participant;
1696            $schedulable['participants'][] = $participantID;
1697        };
[5415]1698
[7006]1699        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
[7702]1700
[7006]1701            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
[5415]1702
1703
[7702]1704            if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
[5415]1705
[7702]1706                $participantID = $participant['id'];
1707
1708            }else{
1709
1710                $participant = array();
1711
1712                $participantID = mt_rand() . '2(Formatter)';
1713                $participant['schedulable'] = $eventID;
1714                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1715                $participant['isOrganizer'] = '1';
1716                $participant['acl'] = 'rowi';
1717            }
1718
[7006]1719            /* Verifica se este usuario é um usuario interno do ldap */
1720            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1721            $user = null;
1722            if ($intUser && count($intUser) > 0) {
[7702]1723                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1724                $participant['user'] = $intUser[0]['id'];
[7006]1725            } else {
[7702]1726                $participant['isExternal'] = 1;
1727                /* Gera um randon id para o contexto formater */
1728                $userID = mt_rand() . '4(Formatter)';
[5415]1729
[7702]1730                $user['mail'] = $mailUser;
1731                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1732                $user['participants'] = array($participantID);
1733                $user['isExternal'] = '1';
1734                $participant['user'] = $userID;
1735                $interation['user://' . $userID] = $user;
[7006]1736            }
[5415]1737
[7006]1738            $interation['participant://' . $participantID] = $participant;
1739            $schedulable['participants'][] = $participantID;
1740        } else if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
1741            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
[5415]1742
[7006]1743            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
1744                        $participantID = mt_rand() . '2(Formatter)';
[5415]1745
[7006]1746                        $participant['schedulable'] = $eventID;
1747                        $participant['status'] = STATUS_CONFIRMED;
1748                        $participant['isOrganizer'] = '1';
1749                        $participant['acl'] = 'rowi';
1750                        $participant['isExternal'] = 0;
1751                        $participant['user'] = $params['owner'];
1752                        $interation['participant://' . $participantID] = $participant;
1753                        $schedulable['participants'][] = $participantID;
1754            }
1755        }
1756       
1757        $alarms = array();
1758       
1759        /* Definindo ALARMES */
1760        while ($alarmComp = $component->getComponent('valarm'))
1761        {
1762                $alarm = array();
1763                $alarmID = mt_rand() . '6(Formatter)';
1764                $action =  $alarmComp->getProperty('action', false, true);
1765                $trygger = $alarmComp->getProperty('trigger', false, true);
1766                $alarm['type'] = self::decodeAlarmAction($action['value']);
[5415]1767
[7006]1768                 if(isset($trygger['value']['day']))
1769                {
1770                        $alarm['time'] = $trygger['value']['day'];
1771                        $alarm['unit'] = 'd';
1772                }
1773                else if(isset($trygger['value']['hour']))
1774                {
1775                        $alarm['time'] = $trygger['value']['hour'];
1776                        $alarm['unit'] = 'h';
1777                }
1778                else if(isset($trygger['value']['min']))
1779                {
1780                        $alarm['time'] = $trygger['value']['min'];
1781                        $alarm['unit'] = 'm';
1782                }
1783               
1784                foreach ($interation as $iint => &$vint)
1785                {
1786                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
1787                        {
1788                                $alarm['participant'] = str_replace('participant://', '', $iint);       
1789                                $vint['alarms'][] = $alarmID;
1790                        }
1791                }
1792                $alarm['schedulable'] = $eventID;
1793                               
1794                $interation['alarm://' . $alarmID ] = $alarm;
1795               
1796        }
1797       
1798       
1799        /* Definindo DTSTAMP */
1800        if ($dtstamp = self::_getTime($component, 'dtstamp'))
1801            $schedulable['dtstamp'] = $dtstamp;
[5415]1802
[7006]1803        /* Definindo TRANSP */
1804        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
1805            $schedulable['transparent'] = 1;
[5415]1806
[7006]1807        /* Definindo last_update */
1808        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
1809            $schedulable['lastUpdate'] = $lastUpdate;
[5415]1810
1811
[7006]1812        if ($sequence = $component->getProperty('SEQUENCE', false, false))
1813            $schedulable['sequence'] = $sequence;
[5415]1814
[7006]1815        if ($uid = $component->getProperty('uid', false, false))
1816            ;
1817        $schedulable['uid'] = $uid;
[5415]1818
[7006]1819        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
[5415]1820
[7006]1821            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
1822                'size' => strlen($attach['value']),
1823                'type' => self::_getContentType($attach['params']['X-FILENAME'])
1824            );
[5514]1825
[7006]1826            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
[5514]1827
[7006]1828            if (!is_array($ids)) {
1829                $attachCurrent['source'] = $attach['value'];
1830                //insere o anexo no banco e pega id para colcar no relacionamento                               
1831                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
1832            }else
1833                $idAttachment = array('id' => $ids[0]['id']);
[5514]1834
[7006]1835            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
1836            $calendarToAttachment['attachment'] = $idAttachment['id'];
1837            $calendarToAttachment['schedulable'] = $eventID;
1838            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
[5514]1839
[7006]1840            $schedulable['attachments'][] = $calendarToAttachmentId;
1841        }
[5514]1842
[7006]1843        $schedulable['type'] = '1';
[5514]1844
[7006]1845        $interation['schedulable://' . $eventID] = $schedulable;
1846
[7702]1847        return $interation;
[6066]1848    }
[6996]1849   
1850    static private function _makeVTODO($schedulable, $component, $params) {
1851        $interation = array();
1852        $todoID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
[5514]1853
[6996]1854        /* Data de Inicio */
1855        $startTime = $component->getProperty('dtstart', false, true);
1856
1857        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1858
1859        /* Tiem zone do evento */
1860        if ($tzid){
1861            $tzid = self::nomalizeTZID($tzid);
1862            $schedulable['timezone'] = $tzid;
1863        }else
1864            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1865
1866        $objTimezone = new DateTimeZone($schedulable['timezone']);
1867
1868        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1869            $schedulable['allDay'] = 1;
1870            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1871        } elseif ($tzid && !isset($startTime['value']['tz'])) {/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
1872            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1873            $schedulable['allDay'] = 0;
1874        } else {
1875            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1876            if (strpos($params['prodid'], 'Outlook') !== false) {
1877                //Se o ics veio em utc não aplicar horario de verão
1878                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1879                $sTime->setTimezone($objTimezone);
1880                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1881                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1882            }
1883        }
1884
1885        /* Data de Termino */
[7068]1886        if($due = $component->getProperty('due', false, true)){
[6996]1887
[7068]1888        $tzid = isset($due['params']['TZID']) ? $due['params']['TZID'] : $params['X-WR-TIMEZONE'];
[6996]1889
[7068]1890        if($tzid)
1891            $tzid = self::nomalizeTZID($tzid);
[6996]1892
[7680]1893        if (isset($due['params']['VALUE']) && $due['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']))
[7068]1894            $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($due['value'])) . '000';
[7680]1895        else if ($tzid && !isset($due['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
[7068]1896            $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($due['value'])) . '000';
1897        else {
1898            $schedulable['due'] = self::date2timestamp($due['value']) . '000';
1899            if (strpos($params['prodid'], 'Outlook') !== false) {
1900            //Se o ics veio em utc não aplicar horario de verão
1901            $dueTime = new DateTime('@' . (int) ($schedulable['due'] / 1000), new DateTimeZone('UTC'));
1902            $dueTime->setTimezone($objTimezone);
1903
1904            if ($dueTime->format('I'))
1905                $schedulable['due'] = $schedulable['due'] - 3600000;
1906            }
1907        }
1908        $schedulable['endTime'] = $schedulable['due'];
1909    }else
1910        $schedulable['endTime'] = $schedulable['startTime'];
1911
[6996]1912        $schedulable['type'] = '2'; //type schedulable
1913        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1914
1915        /* Definindo Description */
1916        if ($desc = $component->getProperty('description', false, false))
1917            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1918
1919        /* Definindo Class */
1920        $class = $component->getProperty('class', false, false);
1921        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1922            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1923        else if (!isset($schedulable['class']))
1924            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1925
1926        $schedulable['calendar'] = $params['calendar'];
1927
1928        $participantsInTodo = array();
1929
1930        //TODO: Participants com delegated nao estao sendo levados em conta
1931        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1932            $participant = array();
1933
1934            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1935
1936            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
[7028]1937            $participant['schedulable'] = $todoID;
[6996]1938
1939            if (isset($params['status']) && $mailUser == Config::me('mail'))
1940                $participant['status'] = $params['status'];
1941            else
1942                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1943
1944
1945            $participant['isOrganizer'] = '0';
1946
1947            /* Verifica se este usuario é um usuario interno do ldap */
1948            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1949
1950            $user = null;
1951            if ($intUser && count($intUser) > 0) {
1952                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1953                $participant['user'] = $intUser[0]['id'];
1954            } else {
1955                $participant['isExternal'] = 1;
1956                /* Gera um randon id para o contexto formater */
1957                $userID = mt_rand() . '4(Formatter)';
1958
1959                $user['mail'] = $mailUser;
1960                $user['isExternal'] = '1';
1961                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1962                $user['participants'] = array($participantID);
1963                $participant['user'] = $userID;
1964                $interation['user://' . $userID] = $user;
1965            }
1966
1967            $interation['participant://' . $participantID] = $participant;
1968            $schedulable['participants'][] = $participantID;
1969        };
1970
1971        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1972            $participant = array();
1973            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1974
[7702]1975        if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
[6996]1976
[7702]1977            $participantID = $participant['id'];
[6996]1978
[7702]1979        }else{
1980
1981            $participant = array();
1982
1983            $participantID = mt_rand() . '2(Formatter)';
1984            $participant['schedulable'] = $todoID;
1985            $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1986            $participant['isOrganizer'] = '1';
1987            $participant['acl'] = 'rowi';
1988        }
1989
[6996]1990            /* Verifica se este usuario é um usuario interno do ldap */
1991            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1992
1993            $user = null;
1994            if ($intUser && count($intUser) > 0) {
1995                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1996                $participant['user'] = $intUser[0]['id'];
1997            } else {
1998                $participant['isExternal'] = 1;
1999                /* Gera um randon id para o contexto formater */
2000                $userID = mt_rand() . '4(Formatter)';
2001
2002                $user['mail'] = $mailUser;
2003                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
2004                $user['participants'] = array($participantID);
2005                $user['isExternal'] = '1';
2006                $participant['user'] = $userID;
2007                $interation['user://' . $userID] = $user;
2008            }
2009
2010            $interation['participant://' . $participantID] = $participant;
2011            $schedulable['participants'][] = $participantID;
2012            } else if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
2013            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
2014
2015            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
2016                $participantID = mt_rand() . '2(Formatter)';
2017
2018                $participant['schedulable'] = $todoID;
2019                $participant['status'] = STATUS_CONFIRMED;
2020                $participant['isOrganizer'] = '1';
2021                $participant['acl'] = 'rowi';
2022                $participant['isExternal'] = 0;
2023                $participant['user'] = $params['owner'];
2024                $interation['participant://' . $participantID] = $participant;
2025                $schedulable['participants'][] = $participantID;
2026            }
2027        }
2028       
2029        $alarms = array();
2030       
2031        /* Definindo ALARMES */
2032        while ($alarmComp = $component->getComponent('valarm'))
2033        {
2034                $alarm = array();
2035                $alarmID = mt_rand() . '6(Formatter)';
2036                $action =  $alarmComp->getProperty('action', false, true);
2037                $trygger = $alarmComp->getProperty('trigger', false, true);
2038                $alarm['type'] = self::decodeAlarmAction($action['value']);
2039
2040                 if(isset($trygger['value']['day']))
2041                {
2042                        $alarm['time'] = $trygger['value']['day'];
2043                        $alarm['unit'] = 'd';
2044                }
2045                else if(isset($trygger['value']['hour']))
2046                {
2047                        $alarm['time'] = $trygger['value']['hour'];
2048                        $alarm['unit'] = 'h';
2049                }
2050                else if(isset($trygger['value']['min']))
2051                {
2052                        $alarm['time'] = $trygger['value']['min'];
2053                        $alarm['unit'] = 'm';
2054                }
2055               
2056                foreach ($interation as $iint => &$vint)
2057                {
2058                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
2059                        {
2060                                $alarm['participant'] = str_replace('participant://', '', $iint);       
2061                                $vint['alarms'][] = $alarmID;
2062                        }
2063                }
2064                $alarm['schedulable'] = $eventID;
2065                               
2066                $interation['alarm://' . $alarmID ] = $alarm;
2067               
2068        }
2069       
2070       
2071        /* Definindo DTSTAMP */
2072        if ($dtstamp = self::_getTime($component, 'dtstamp'))
2073            $schedulable['dtstamp'] = $dtstamp;
2074
2075        /* Definindo TRANSP */
2076        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
2077            $schedulable['transparent'] = 1;
2078
2079        /* Definindo last_update */
2080        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
2081            $schedulable['lastUpdate'] = $lastUpdate;
2082
2083
2084        if ($sequence = $component->getProperty('SEQUENCE', false, false))
2085            $schedulable['sequence'] = $sequence;
2086
2087        if ($uid = $component->getProperty('uid', false, false))
2088            ;
2089        $schedulable['uid'] = $uid;
2090
2091        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
2092
2093            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
2094                'size' => strlen($attach['value']),
2095                'type' => self::_getContentType($attach['params']['X-FILENAME'])
2096            );
2097
2098            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
2099
2100            if (!is_array($ids)) {
2101                $attachCurrent['source'] = $attach['value'];
2102                //insere o anexo no banco e pega id para colcar no relacionamento                               
2103                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
2104            }else
2105                $idAttachment = array('id' => $ids[0]['id']);
2106
2107            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
2108            $calendarToAttachment['attachment'] = $idAttachment['id'];
2109            $calendarToAttachment['schedulable'] = $eventID;
2110            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
2111
2112            $schedulable['attachments'][] = $calendarToAttachmentId;
2113        }
2114
2115        $interation['schedulable://' . $todoID] = $schedulable;
2116
[7068]2117    return $interation;
[6996]2118    }
2119
[6066]2120    static private function _getSchedulable($uid) {
2121        $schedulable = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'uid', $uid), 'deepness' => 2));
2122        return (isset($schedulable[0])) ? $schedulable[0] : false;
2123    }
[5514]2124
[6331]2125    static private function _existInMyCalendars($id, $owner) {
[7219]2126        $sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'isOwner', '1'), array('=', 'user', $owner))));
2127        $sig2 = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('*', 'acl', 'w'), array('=', 'user', $owner))));
2128
[6066]2129        $calendars = array();
[7219]2130        if(is_array($sig))
2131                foreach ($sig as $val)
2132                    $calendars[] = $val['calendar'];
2133        if(is_array($sig2))
2134                foreach ($sig2 as $val)
2135                    $calendars[] = $val['calendar'];
[6066]2136
[7219]2137
[6066]2138        $return = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('AND', array('IN', 'calendar', $calendars), array('=', 'schedulable', $id))));
2139
2140        return (isset($return[0])) ? $return[0]['calendar'] : false;
2141    }
2142
2143    static private function _getTime(&$component, $property) {
2144        if ($date = $component->getProperty($property, false, true))
2145            return (isset($date['params']['TZID']) && !isset($date['value']['tz'])) ? (self::date2timestamp($date['value']) - self::_getTzOffset('UTC', $date['params']['TZID'], '@' . self::date2timestamp($date['value']))) . '000' : self::date2timestamp($date['value']) . '000';
2146
2147        return false;
2148    }
2149
2150    static private function _getContentType($fileName) {
2151        $strFileType = strtolower(substr($fileName, strrpos($fileName, '.')));
2152
2153        switch ($strFileType) {
2154            case ".asf": return "video/x-ms-asf";
2155            case ".avi": return "video/avi";
2156            case ".doc": return "application/msword";
2157            case ".zip": return "application/zip";
2158            case ".xls": return "application/vnd.ms-excel";
2159            case ".gif": return "image/gif";
2160            case ".bmp": return "image/bmp";
2161            case ".jpeg":
2162            case ".jpg": return "image/jpeg";
2163            case ".wav": return "audio/wav";
2164            case ".mp3": return "audio/mpeg3";
2165            case ".mpeg":
2166            case ".mpg": return "video/mpeg";
2167            case ".rtf": return "application/rtf";
2168            case ".html":
2169            case ".htm": return "text/html";
2170            case ".xml": return "text/xml";
2171            case ".xsl": return "text/xsl";
2172            case ".css": return "text/css";
2173            case ".php": return "text/php";
2174            case ".asp": return "text/asp";
2175            case ".pdf": return "application/pdf";
2176            case ".png": return "image/png";
2177            case ".txt": return "text/plain";
2178            case ".log": return "text/plain";
2179            case ".wmv": return "video/x-ms-wmv";
2180            case ".sxc": return "application/vnd.sun.xml.calc";
2181            case ".odt": return "application/vnd.oasis.opendocument.text";
2182            case ".stc": return "application/vnd.sun.xml.calc.template";
2183            case ".sxd": return "application/vnd.sun.xml.draw";
2184            case ".std": return "application/vnd.sun.xml.draw.template";
2185            case ".sxi": return "application/vnd.sun.xml.impress";
2186            case ".sti": return "application/vnd.sun.xml.impress.template";
2187            case ".sxm": return "application/vnd.sun.xml.math";
2188            case ".sxw": return "application/vnd.sun.xml.writer";
2189            case ".sxq": return "application/vnd.sun.xml.writer.global";
2190            case ".stw": return "application/vnd.sun.xml.writer.template";
2191            case ".pps": return "application/vnd.ms-powerpoint";
2192            case ".odt": return "application/vnd.oasis.opendocument.text";
2193            case ".ott": return "application/vnd.oasis.opendocument.text-template";
2194            case ".oth": return "application/vnd.oasis.opendocument.text-web";
2195            case ".odm": return "application/vnd.oasis.opendocument.text-master";
2196            case ".odg": return "application/vnd.oasis.opendocument.graphics";
2197            case ".otg": return "application/vnd.oasis.opendocument.graphics-template";
2198            case ".odp": return "application/vnd.oasis.opendocument.presentation";
2199            case ".otp": return "application/vnd.oasis.opendocument.presentation-template";
2200            case ".ods": return "application/vnd.oasis.opendocument.spreadsheet";
2201            case ".ots": return "application/vnd.oasis.opendocument.spreadsheet-template";
2202            case ".odc": return "application/vnd.oasis.opendocument.chart";
2203            case ".odf": return "application/vnd.oasis.opendocument.formula";
2204            case ".odi": return "application/vnd.oasis.opendocument.image";
2205            case ".ndl": return "application/vnd.lotus-notes";
2206            case ".eml": return "text/plain";
2207            case ".ps" : return "application/postscript";
2208            default : return "application/octet-stream";
2209        }
2210    }
[6094]2211   
2212    public function codeAlarmAction( $action )
2213    {
2214        switch ($action)
2215        {
2216                case ALARM_MAIL :
2217                                return  'EMAIL';
2218                                break;
2219                case ALARM_ALERT :
2220                                return  'DISPLAY';
2221                                break;
2222                case 'mail' :
2223                                        return  'EMAIL';
2224                                        break;
2225                case 'alert'  :
2226                                        return  'DISPLAY';
2227                                        break;
2228        }
2229       
2230    }
2231   
2232    public function decodeAlarmAction( $action )
2233    {
2234        switch ( $action )
2235        {
2236                case 'EMAIL'  :
2237                        return  'mail';
2238                        break;
2239                case 'DISPLAY' :
2240                        return  'alert';
2241                        break;
[6066]2242
[6094]2243        }
2244   
2245    }
2246
[5341]2247}
[6066]2248
[5341]2249?>
Note: See TracBrowser for help on using the repository browser.