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

Revision 7959, 118.0 KB checked in by cristiano, 11 years ago (diff)

Ticket #3374 - Inconsistências ao criar eventos em nome de uma agenda assinada

Line 
1<?php
2
3//require_once ROOTPATH . '/plugins/icalcreator/iCalUtilityFunctions.class.php';
4require_once ROOTPATH . '/plugins/icalcreator/iCalcreator.class.php';
5require_once ROOTPATH . '/modules/calendar/constants.php';
6
7use prototype\api\Config as Config;
8
9//TODO:Timeout request
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');
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'); 
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');
17
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);
28
29    }
30
31    protected function createIcal($data, $params = false )
32    {
33        $ical = new icalCreatorVcalendar();
34                $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
35
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']);
42
43                foreach ($data as $i => $v) {
44
45                    switch ($v['type']) {
46                        case EVENT_ID:
47                            $vevent = $ical->newComponent('vevent');
48
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' );
53
54                            $timezone = new DateTimeZone('UTC');
55                            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
56                            $apTimezoneOBJ = new DateTimeZone($apTimezone);
57
58                            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
59                            $sTime->setTimezone($apTimezoneOBJ);
60
61                $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
62                $eTime->setTimezone($apTimezoneOBJ);
63
64                            if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' ))
65                                    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
66
67                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
68
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');
73                    $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
74                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
75                            } else
76                {
77                    $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
78                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
79                    $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
80                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
81                            }
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);
110
111                            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
112                                        $this->createAttachment($v['attachments'], $vevent);
113
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
139                    $timezone = $ical->newComponent('vtimezone');
140                    $timezone->setProperty('tzid',$apTimezone );
141
142                    $standard  = $timezone->newComponent( "standard" );
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
157                    $daylight  = $timezone->newComponent( "daylight" );
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
183                            break;
184            case TODO_ID:
185
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
203                $todo->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
204
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
215                if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
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));
220                    $todo->setProperty('dueTime', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
221                }               
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;
257                        default:
258                            break;
259                    }
260                }
261                return $ical->createCalendar();
262    }
263
264    protected function createCompatibleIcal($data, $params = false )
265    {
266        $ical = new icalCreatorVcalendar();
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
287                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
288
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                                       
329                                        }
330                           
331
332                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
333                                        $this->createAttendee($v['participants'], $vevent);
334
335                            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
336                                        $this->createAttachment($v['attachments'], $vevent);
337
338                            $vevent->setProperty('uid', $v['uid']); 
339                           
340                            break;
341
342                        default:
343                            break;
344                       
345        case TODO_ID:
346
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
355            $todo->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
356
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
372            if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
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
419       
420        return $ical->createCalendar();
421    }
422
423    protected function formatIcalRepeat($pRepeat)
424    {
425        $repeat = array();
426
427                foreach ($pRepeat as $ir => $rv) {
428                    if ($rv) {
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);
441                    }
442                }
443                return $repeat;
444    }
445
446   
447    public function createAlarms($alarms, &$vevent)
448    {   
449            foreach ($alarms as $va)
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    }
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);
482        }
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;
496            if ((isset($pv['delegatedFrom']) && $pv['delegatedFrom'] == 0) || !isset($pv['delegatedFrom']))  {
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);
526
527                }
528            }
529           
530           
531        }
532    }
533
534    public function parse($data, $params = false) {
535        Config::regSet('noAlarm', TRUE); //Evita o envio de notificação
536        $vcalendar = new icalCreatorVcalendar( );
537
538        $vcalendar->parse(trim($data));
539        $vcalendar->sort();
540
541        $return = array();
542        $method = $vcalendar->getProperty('method', FALSE, FALSE);
543        $params['prodid'] = $vcalendar->getProperty('prodid', false, false);
544        $params['X-WR-TIMEZONE'] = ( $xrTimezone = $vcalendar->getProperty('X-WR-TIMEZONE', false, false)) ? self::nomalizeTZID($xrTimezone[1]) : false ;
545
546        while ($component = $vcalendar->getComponent()) {
547            $interation = array();
548            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
549
550            switch (strtoupper($component->objName)) {
551                case 'VEVENT':
552
553
554                    switch ($method) {
555                        case 'PUBLISH':
556                            //Caso o evento não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
557                if (!$schedulable = self::_getSchedulable($uid))
558                                    $interation = self::_makeVEVENT($schedulable, $component, $params);
559                else{
560                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
561                                        array('AND',
562                                            array('=', 'calendar', $params['calendar']),
563                                            array('=', 'schedulable', $schedulable['id'])
564                                        )));
565
566                    if(!$links &&  !isset($links[0]))
567                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
568
569                    }
570                            break;
571
572                        case 'REQUEST':
573                            $schedulable = self::_getSchedulable($uid);
574                $calendar = false;
575                $accpeted = true;
576                            if ($schedulable) {
577                    ///Verifica se o usuario e um participante e se este aceitou o pedido.
578                    foreach ($schedulable['participants'] as $value){
579                        if ($value['user']['id'] == $params['owner'] &&  ($value['status'] == STATUS_UNANSWERED || $value['status'] == STATUS_DECLINED)){
580                            $accpeted  = false;
581                        }
582                    }
583                             //Caso o evento exista
584                    if (!($calendar = self::_existInMyCalendars($schedulable['id'], $params['owner'])) || !$accpeted ) {
585                        $calendarToSchedulable = array();
586                        $calendarToSchedulable['calendar'] = $params['calendar'];
587                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
588                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
589
590                        if (isset($params['status']))
591                        {
592                            if($params['owner'] != Config::me("uidNumber"))
593                            {
594                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );
595                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
596                            }
597                            else
598                            {
599                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
600                            }
601                            //caso nõa seja participante adiciona a lista de participantes
602                            if(!$pID){
603                                $pID =  mt_rand() . '2(Formatter)';
604                                $interation['participant://' . $pID]['status'] = $params['status'];
605                                $interation['participant://' . $pID]['user'] = $params['owner'];
606                                $interation['participant://' . $pID]['isOrganizer'] = '0';
607                                $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
608                            }
609                            else
610                            {
611                                $interation['participant://' . $pID]['status'] = $params['status'];
612                            }
613                        }
614
615                        Config::regSet('noAlarm', FALSE); //reativa notificação
616                    } else {
617
618                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']){ //Organizador esta requisitando que você atualize o evento
619
620                            $params['calendar'] = $params['calendar'] == 'true' ? $calendar : $params['calendar'];
621                            $interation = self::_makeVEVENT($schedulable, $component, $params);
622                        }else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
623                            //Ler melhor rfc sobre isto 3.2.2.2
624                            //Aparentemente é para retornar um ical com o evento atualizado para o attende
625                        }
626
627                        if (isset($params['status'])) {
628                            if($params['owner'] != Config::me("uidNumber")){
629                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );
630                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
631                            }else
632                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
633                            //Verifica a importação de eventos em que não participo
634                            if ($pID) {
635
636                                $interation['participant://' . $pID]['status'] = $params['status'];
637
638                            }
639                        }
640                    }
641                } else { // Importar evento
642                    $interation = self::_makeVEVENT(array(), $component, $params);
643
644                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
645
646                        /* Data de Inicio */
647                        $startTime = $component->getProperty('dtstart', false, true);
648
649                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
650
651                        /* Tiem zone do evento */
652                        if ($tzid)
653                        $sc['timezone'] = self::nomalizeTZID($tzid);
654                        else
655                        $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
656
657                        $objTimezone = new DateTimeZone($sc['timezone']);
658
659                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
660                        $sc['allDay'] = 1;
661                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
662                        } 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 */
663                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
664                        else {
665                        $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
666                        if (strpos($params['prodid'], 'Outlook') !== false) {
667                            //Se o ics veio em utc não aplicar horario de verão
668                            $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
669                            $sTime->setTimezone($objTimezone);
670                            if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
671                            $sc['startTime'] = $sc['startTime'] - 3600000;
672                        }
673                        }
674
675
676                        /* Data de Termino */
677                        $endTime = $component->getProperty('dtend', false, true);
678
679                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
680                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
681                        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 */
682                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
683                        else {
684                        $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
685                        if (strpos($params['prodid'], 'Outlook') !== false) {
686                            //Se o ics veio em utc não aplicar horario de verão
687                            $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
688                            $eTime->setTimezone($objTimezone);
689                            if ($eTime->format('I'))
690                            $sc['endTime'] = $sc['endTime'] - 3600000;
691                        }
692                        }
693
694
695                        if ($uid = $component->getProperty('uid', false, false))
696                        ;
697                        $sc['uid'] = $uid;
698
699
700                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
701
702                        /* Definindo Description */
703                        if ($desc = $component->getProperty('description', false, false))
704                        $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
705
706                        /* Definindo location */
707                        if ($location = $component->getProperty('location', false, false))
708                        $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
709
710
711
712                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
713                        $participant = array();
714                        $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
715
716                        $participantID = mt_rand() . '2(Formatter)';
717
718                        $participant['isOrganizer'] = '1';
719
720                        $user = null;
721
722                        $participant['isExternal'] = 1;
723                        /* Gera um randon id para o contexto formater */
724                        $userID = mt_rand() . '4(Formatter)';
725
726                        $user['mail'] = $mailUser;
727                        $organizerMail = $mailUser;
728
729                        $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
730                        $user['isExternal'] = '1';
731                        $participant['user'] = $user;
732
733                        $sc['participants'][] = $participant;
734                        }
735
736
737                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
738                        $participant['isOrganizer'] = '0';
739                        $participant['isExternal'] = 0;
740
741                        $user = false;
742                        if($params['owner'] != Config::me("uidNumber"))
743                        {
744                            $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );
745                        }
746
747                        $participant['user'] = $user ?  array('mail' => $user['mail'], 'name' => $user['name']) : array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
748
749                        $sc['participants'][] = $participant;
750                        $sc['type'] = EVENT_ID;
751
752
753                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
754                        $ical['type'] = 'application/ics';
755                        $ical['name'] = 'outlook.ics';
756
757                        $ical2['source'] = $ical['source'];
758                        $ical2['type'] = 'text/calendar; method=REPLY';
759                        $ical2['name'] = 'thunderbird.ics';
760
761                        $timezone = new DateTimeZone('UTC');
762                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
763                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
764
765                        if (isset($sc['timezone'])) {
766                        $sTime->setTimezone(new DateTimeZone($sc['timezone']));
767                        $eTime->setTimezone(new DateTimeZone($sc['timezone']));
768                        }
769
770                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
771                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
772                        'endDate' => date_format($eTime, 'd/m/Y'),
773                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
774                        'eventTitle' => $sc['summary'],
775                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
776                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
777                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
778
779                        $subject['notificationType'] = 'Convite Aceito';
780                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
781                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
782                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
783                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
784                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
785                        $subject['participant'] = Config::me('uid');
786
787                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
788
789                        switch ($params['status']) {
790                        case STATUS_ACCEPTED:
791                            $tpl = 'notify_accept_body';
792                            $subject['notificationType'] = 'Convite Aceito';
793                            break;
794                        case STATUS_TENTATIVE:
795                            $tpl = 'notify_attempt_body';
796                            $subject['notificationType'] = 'Convite  aceito provisoriamente';
797                            break;
798                        case STATUS_CANCELLED:
799                            $tpl = 'notify_reject_body';
800                            $subject['notificationType'] = 'Convite rejeitado';
801                            break;
802                        }
803                        require_once ROOTPATH . '/api/parseTPL.php';
804
805                        $mail = array();
806                        $mail['attachments'][] = $ical;
807                        $mail['attachments'][] = $ical2;
808
809                        $mail['isHtml'] = true;
810                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
811                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
812                        ;
813                        $mail['from'] = $user ? '"' . $user['name'] . '" <' . $user['mail'] . '>' : '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
814                        $mail['to'] = $organizerMail;
815
816                        Controller::create(array('service' => 'SMTP'), $mail);
817                    }
818                            }
819                            break;
820
821                        case 'REFRESH':
822                            break;
823
824                        case 'CANCEL':
825                            if ($schedulable = self::_getSchedulable($uid))
826                                $interation['schedulable://' . $schedulable['id']] = false;
827                            break;
828                               
829                        case 'ADD':
830                            break;
831
832                        case 'REPLY':
833                            if ($schedulable = self::_getSchedulable($uid)) {
834                                while ($property = $component->getProperty('attendee', FALSE, TRUE))
835                                    if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
836                                        $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
837
838                                $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
839                            }
840                            break;
841
842                        case 'COUNTER':
843                            if ($params['acceptedSuggestion'] !== 'false') {
844
845                                $schedulable = self::_getSchedulable($uid);
846                                $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
847
848                                $interation = self::_makeCOUNTER($schedulable, $component, $params);
849                                Config::regSet('noAlarm', FALSE);
850                            } else {
851                                $response = array();
852                                $response['from'] = $params['from'];
853                                $response['type'] = 'suggestionResponse';
854                                $response['status'] = 'DECLINECOUNTER';
855                                $response['schedulable'] = self::_getSchedulable($uid);
856
857                                Controller::create(array('concept' => 'notification'), $response);
858                            }
859                            break;
860
861                        case 'DECLINECOUNTER':
862                            break;
863
864                        default:
865
866                            $schedulable = self::_getSchedulable($uid);
867
868                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
869                                $interation = self::_makeVEVENT($schedulable, $component, $params);
870
871                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
872                                    $calendarToSchedulable = array();
873                                    $calendarToSchedulable['calendar'] = $params['calendar'];
874                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
875                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
876                                }
877                            }
878                            else // Importar evento
879                                $interation = self::_makeVEVENT(array(), $component, $params);
880                            break;
881                    }
882
883                    $return[] = $interation;
884                    break;
885        /***********************************************************************TODO*******************************************************************************/
886        case 'VTODO':
887        switch ($method) {
888            case 'PUBLISH':
889                //Caso a tarefa não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
890                if (!$schedulable = self::_getSchedulable($uid))
891                    $interation = self::_makeVTODO($schedulable, $component, $params);
892                else{
893                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
894                    array('AND',
895                        array('=', 'calendar', $params['calendar']),
896                        array('=', 'schedulable', $schedulable['id'])
897                    )));
898
899                    if(!$links &&  !isset($links[0]))
900                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
901                }
902                break;
903
904            case 'REQUEST':
905                $schedulable = self::_getSchedulable($uid);
906
907                if ($schedulable) { //Caso tarefa exista
908                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
909                       
910                        $calendarToSchedulable = array();
911                        $calendarToSchedulable['calendar'] = $params['calendar'];
912                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
913                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
914       
915                        if (isset($params['status'])) {
916                            if($params['owner'] != Config::me("uidNumber")){                       
917                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                       
918                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
919                            }else
920                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
921                                $interation['participant://' . $pID]['status'] = $params['status'];
922                        }
923                        Config::regSet('noAlarm', FALSE); //reativa notificação
924                    } else {
925
926                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
927                            $interation = self::_makeVEVENT($schedulable, $component, $params);
928                        else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
929                        //Ler melhor rfc sobre isto 3.2.2.2
930                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
931                        }
932
933                        if (isset($params['status'])) {
934                            if($params['owner'] != Config::me("uidNumber")){                       
935                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                     
936                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
937                            }else{
938                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
939                                //Verifica a importação de tarefas em que não participo
940                                if ($pID) {
941                                    $pID =  mt_rand() . '2(Formatter)';
942                                    $interation['participant://' . $pID]['status'] = $params['status'];
943                                    $interation['participant://' . $pID]['user'] = $params['owner'];
944                                    $interation['participant://' . $pID]['isOrganizer'] = '0';
945                                    $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
946                                }else
947                                    $interation['participant://' . $pID]['status'] = $params['status'];
948                            }
949                        }
950                    }
951                } else { // Importar tarefa
952                    $interation = self::_makeVTODO(array(), $component, $params);
953
954                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
955
956                        /* Data de Inicio */
957                        $startTime = $component->getProperty('dtstart', false, true);
958                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
959
960                        /* Tiem zone do evento */   
961                        if ($tzid)
962                            $sc['timezone'] = self::nomalizeTZID($tzid);
963                        else
964                            $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
965
966                        $objTimezone = new DateTimeZone($sc['timezone']);
967
968                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
969                            $sc['allDay'] = 1;
970                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
971                        } 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 */
972                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
973                        else {
974                            $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
975                            if (strpos($params['prodid'], 'Outlook') !== false) {
976                                //Se o ics veio em utc não aplicar horario de verão
977                                $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
978                                $sTime->setTimezone($objTimezone);
979                                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
980                                $sc['startTime'] = $sc['startTime'] - 3600000;
981                            }
982                        }
983
984                        /* Data de Termino */
985                        $endTime = $component->getProperty('dtend', false, true);
986
987                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
988                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
989                        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 */
990                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
991                        else {
992                            $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
993                            if (strpos($params['prodid'], 'Outlook') !== false) {
994                                //Se o ics veio em utc não aplicar horario de verão
995                                $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
996                                $eTime->setTimezone($objTimezone);
997                                if ($eTime->format('I'))
998                                    $sc['endTime'] = $sc['endTime'] - 3600000;
999                            }
1000                        }
1001
1002
1003                        if ($uid = $component->getProperty('uid', false, false))                   
1004                            $sc['uid'] = $uid;
1005
1006                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
1007
1008                        /* Definindo Description */
1009                        if ($desc = $component->getProperty('description', false, false))
1010                            $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
1011
1012            if ($priority = $component->getProperty('priority', false, false))
1013                $sc['priority'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $priority), 'UTF-8', 'UTF-8,ISO-8859-1');
1014
1015            if ($status = $component->getProperty('status', false, false))
1016                $sc['status'] = $this->decodeStatusTodo(mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $status), 'UTF-8', 'UTF-8,ISO-8859-1'));
1017
1018            if ($percentage = $component->getProperty('percent-complete', false, false))
1019                $sc['percentage'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $percentage), 'UTF-8', 'UTF-8,ISO-8859-1');
1020
1021                        /* Definindo location */
1022                        if ($location = $component->getProperty('location', false, false))
1023                            $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
1024
1025
1026
1027                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1028                            $participant = array();
1029                            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1030
1031                            $participantID = mt_rand() . '2(Formatter)';
1032
1033                            $participant['isOrganizer'] = '1';
1034
1035                            $user = null;
1036
1037                            $participant['isExternal'] = 1;
1038                            /* Gera um randon id para o contexto formater */
1039                            $userID = mt_rand() . '4(Formatter)';
1040
1041                            $user['mail'] = $mailUser;
1042                            $organizerMail = $mailUser;
1043
1044                            $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1045                            $user['isExternal'] = '1';
1046                            $participant['user'] = $user;
1047
1048                            $sc['participants'][] = $participant;
1049                        }
1050
1051
1052                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1053                        $participant['isOrganizer'] = '0';
1054                        $participant['isExternal'] = 0;
1055                        $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
1056                        $sc['participants'][] = $participant;
1057                        $sc['type'] = TODO_ID;
1058
1059
1060                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
1061                        $ical['type'] = 'application/ics';
1062                        $ical['name'] = 'outlook.ics';
1063
1064                        $ical2['source'] = $ical['source'];
1065                        $ical2['type'] = 'text/calendar; method=REPLY';
1066                        $ical2['name'] = 'thunderbird.ics';
1067
1068                        $timezone = new DateTimeZone('UTC');
1069                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
1070                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
1071
1072                        if (isset($sc['timezone'])) {
1073                            $sTime->setTimezone(new DateTimeZone($sc['timezone']));
1074                            $eTime->setTimezone(new DateTimeZone($sc['timezone']));
1075                        }
1076
1077                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
1078                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
1079                        'endDate' => date_format($eTime, 'd/m/Y'),
1080                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
1081                        'eventTitle' => $sc['summary'],
1082                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
1083                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
1084                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
1085
1086                        $subject['notificationType'] = 'Convite Aceito';
1087                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
1088                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
1089                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
1090                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
1091                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
1092                        $subject['participant'] = Config::me('uid');
1093
1094                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1095
1096                        switch ($params['status']) {
1097                            case STATUS_ACCEPTED:
1098                                $tpl = 'notify_accept_body';
1099                                $subject['notificationType'] = 'Convite Aceito';
1100                                break;
1101                            case STATUS_TENTATIVE:
1102                                $tpl = 'notify_attempt_body';
1103                                $subject['notificationType'] = 'Convite  aceito provisoriamente';
1104                                break;
1105                            case STATUS_CANCELLED:
1106                                $tpl = 'notify_reject_body';
1107                                $subject['notificationType'] = 'Convite rejeitado';
1108                                break;
1109                        }
1110
1111                        require_once ROOTPATH . '/api/parseTPL.php';
1112
1113                        $mail = array();
1114                        $mail['attachments'][] = $ical;
1115                        $mail['attachments'][] = $ical2;
1116
1117                        $mail['isHtml'] = true;
1118                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
1119                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
1120
1121                        $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
1122                        $mail['to'] = $organizerMail;
1123
1124
1125                        Controller::create(array('service' => 'SMTP'), $mail);
1126                    }
1127                }
1128                break;
1129
1130            case 'REFRESH':
1131                break;
1132
1133            case 'CANCEL':
1134                if ($schedulable = self::_getSchedulable($uid))
1135                    $interation['schedulable://' . $schedulable['id']] = false;
1136                break;
1137
1138            case 'ADD':
1139                break;
1140
1141            case 'REPLY':
1142                if ($schedulable = self::_getSchedulable($uid)) {
1143                    while ($property = $component->getProperty('attendee', FALSE, TRUE))
1144                        if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
1145                            $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
1146
1147                    $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
1148                }
1149                break;
1150
1151            case 'COUNTER':
1152                if ($params['acceptedSuggestion'] !== 'false') {
1153
1154                    $schedulable = self::_getSchedulable($uid);
1155                    $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
1156
1157                    $interation = self::_makeCOUNTER($schedulable, $component, $params);
1158                    Config::regSet('noAlarm', FALSE);
1159                } else {
1160                    $response = array();
1161                    $response['from'] = $params['from'];
1162                    $response['type'] = 'suggestionResponse';
1163                    $response['status'] = 'DECLINECOUNTER';
1164                    $response['schedulable'] = self::_getSchedulable($uid);
1165
1166                    Controller::create(array('concept' => 'notification'), $response);
1167                }
1168                break;
1169
1170            case 'DECLINECOUNTER':
1171                break;
1172
1173            default:
1174
1175                $schedulable = self::_getSchedulable($uid);
1176
1177                if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
1178                    $interation = self::_makeVEVENT($schedulable, $component, $params);
1179
1180                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
1181                        $calendarToSchedulable = array();
1182                        $calendarToSchedulable['calendar'] = $params['calendar'];
1183                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
1184                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
1185                    }
1186                }
1187                else // Importar evento
1188                $interation = self::_makeVEVENT(array(), $component, $params);
1189
1190                break;
1191            }
1192   
1193            $return[] = $interation;
1194        break;
1195        /***********************************************************************TODO*******************************************************************************/
1196        case 'VTIMEZONE':
1197                break;
1198            }
1199        }
1200        return $return;
1201    }
1202
1203    public function analize($data, $params = false) {
1204        $vcalendar = new icalCreatorVcalendar( );
1205        $vcalendar->parse(trim($data));
1206        $vcalendar->sort();
1207
1208        $return = array();
1209        $method = $vcalendar->getProperty('method', FALSE, FALSE);
1210
1211        while ($component = $vcalendar->getComponent()) {
1212            $interation = array();
1213            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
1214            switch (strtoupper($component->objName)) {
1215                case 'VEVENT':
1216
1217                    switch ($method) {
1218                        case 'PUBLISH':
1219                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1220                            break;
1221
1222                        case 'REQUEST':
1223                            $schedulable = self::_getSchedulable($uid);
1224                            if ($schedulable) { //Caso o evento exista
1225                    $isOrganizer = false;
1226                    $isParticipant = false;
1227
1228                    foreach ($schedulable['participants'] as $value){
1229
1230                        if ($value['user']['id'] == $params['owner']) {
1231                            $isParticipant = true;
1232                            if ($value['isOrganizer'])
1233                                $isOrganizer = true;
1234
1235                            if (!self::_existInMyCalendars($schedulable['id'], $params['owner']) || $value['status'] == STATUS_UNANSWERED || $value['status'] == STATUS_DECLINED) {
1236                                $interation = ICAL_ACTION_UPDATE;
1237                                $interation = ( strrpos($value['acl'], ATTENDEE_ACL_PARTICIPATION_REQUIRED) ) ? ICAL_ACTION_IMPORT_REQUIRED : array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1238                                break;
1239                            }
1240                            else
1241                            {
1242                                if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1243                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1244                                else
1245                                    $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1246
1247                            }
1248                        }
1249                      }
1250                    if (!$isParticipant){
1251                        if( self::_existInMyCalendars($schedulable['id'], $params['owner']) ){
1252                            $interation = (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] ? ICAL_ACTION_UPDATE  :  ICAL_ACTION_NONE);
1253
1254                        }else{
1255
1256                            $interation =  self::_checkParticipantByPermissions($schedulable);
1257
1258                        }
1259
1260                    }
1261                }else
1262                    $interation = array('action' => ICAL_ACTION_IMPORT_REQUIRED, 'type' => 'calendarIds');
1263
1264                    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 ) )) {
1265                        if($params['owner'] != Config::me("uidNumber")){
1266                            $sig = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=', 'user', $params['owner']), array('=', 'isOwner', '1'))));
1267                            $calendars = array();
1268                            foreach ($sig as $val)
1269                            $calendars[] = $val['calendar'];
1270
1271                            $calendarsPermission = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('=', 'user', Config::me("uidNumber")), array('IN', 'calendar', $calendars))));
1272
1273                            foreach ($calendarsPermission as $val)
1274                            $ids[] = $val['calendar'];
1275
1276                            $interation = array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION ,'calendar' => $ids);
1277                        }
1278                    }
1279
1280                            break;
1281
1282                        case 'REFRESH':
1283                            break;
1284
1285                        case 'CANCEL':
1286                            $interation = ICAL_ACTION_DELETE;
1287                            break;
1288
1289                        case 'ADD':
1290                            break;
1291
1292                        case 'REPLY':
1293                                if ($schedulable = self::_getSchedulable($uid)) {
1294                                        while ($property = $component->getProperty('attendee', FALSE, TRUE))
1295                                            if ($attendee = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants'], true))
1296                                                        $interation = (constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])) == $attendee['status']) ?  ICAL_ACTION_NONE : ICAL_ACTION_REPLY;
1297                            }else
1298                                $interation = ICAL_NOT_FOUND;
1299                            break;
1300
1301                        case 'COUNTER':
1302                            $interation = ICAL_ACTION_SUGGESTION;
1303                            break;
1304
1305                        case 'DECLINECOUNTER':
1306                            $interation = ICAL_ACTION_NONE;
1307                            break;
1308
1309                        default:
1310                            $schedulable = self::_getSchedulable($uid);
1311
1312                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1313                                $interation = ICAL_ACTION_UPDATE;
1314                            else if ($schedulable)
1315                                $interation = ICAL_ACTION_NONE;
1316                            else // Importar evento
1317                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1318
1319                            break;
1320                    }
1321
1322                    $return[$uid] = $interation;
1323                    break;
1324                case 'VTODO':
1325                    switch ($method) {
1326                        case 'PUBLISH':
1327                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1328                            break;
1329
1330                        case 'REQUEST':
1331                            $schedulable = self::_getSchedulable($uid);
1332                           
1333                            if ($schedulable) { //Caso o evento exista
1334                                $isOrganizer = false;
1335                                $isParticipant = false;
1336
1337                                foreach ($schedulable['participants'] as $value)
1338                                    if ($value['user']['id'] == $params['owner']) {
1339                                        $isParticipant = true;
1340                                        if ($value['isOrganizer'])
1341                                            $isOrganizer = true;
1342
1343                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {   
1344                                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1345                                            break;
1346                                        }
1347                                    } else {
1348
1349                        ///Atualiza o Caldadav mesmo que o expresso não prescisse de atualização, pois os calendarios do caldav são independentes um de cada usuario diferente do expresso que so tem 1 evento e é compartilhado entre os usuarios
1350                        if (Config::module('useCaldav', 'expressoCalendar')) { //Ignorar Put dos eventos ja vindos do caldav
1351                            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
1352                            $calendars = self::schedulable2calendarToObject($schedulable['id'] , isset($params['owner']) ? $params['owner']: false ); //Busca os calendarios do usuario logado que contenham o evento
1353                            if (is_array($calendars))
1354                                foreach ($calendars as $calendar)
1355                                    DAViCalAdapter::putIcal($data, array('uid' => $schedulable['uid'], 'location' => $calendar['calendar_location']));
1356                        }
1357
1358                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1359                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1360                                        else
1361                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1362                                    }
1363                                if (!$isParticipant){
1364                                      $interation = self::_checkParticipantByPermissions($schedulable);
1365                                    }
1366                            }else
1367                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1368                            break;
1369
1370                        case 'REFRESH':
1371                            break;
1372
1373                        case 'CANCEL':
1374                            $interation = ICAL_ACTION_DELETE;
1375                            break;
1376
1377                        case 'ADD':
1378                            break;
1379
1380                        case 'REPLY':
1381                            $interation = ICAL_ACTION_REPLY;
1382                            break;
1383
1384                        case 'COUNTER':
1385                            $interation = ICAL_ACTION_SUGGESTION;
1386                            break;
1387
1388                        case 'DECLINECOUNTER':
1389                            $interation = ICAL_ACTION_NONE;
1390                            break;
1391
1392                        default:
1393                            $schedulable = self::_getSchedulable($uid);
1394
1395                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1396                                $interation = ICAL_ACTION_UPDATE;
1397                            else if ($schedulable)
1398                                $interation = ICAL_ACTION_NONE;
1399                            else // Importar evento
1400                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1401
1402                            break;
1403                    }
1404
1405                    $return[$uid] = $interation;
1406                    break;
1407                case 'VTIMEZONE':
1408                break;
1409            }
1410        }
1411
1412        return $return;
1413    }
1414
1415    /* Helpers */
1416
1417    private static function _getTzOffset($rTz, $oTz = null, $time = 'now') {
1418        if ($oTz === null) {
1419            if (!is_string($oTz = date_default_timezone_get())) {
1420                return false; // A UTC timestamp was returned -- bail out!
1421            }
1422        }
1423        $origin_dtz = new DateTimeZone(self::nomalizeTZID($oTz));
1424        $remote_dtz = new DateTimeZone(self::nomalizeTZID($rTz));
1425        $origin_dt = new DateTime($time, $origin_dtz);
1426        $remote_dt = new DateTime("now", $remote_dtz);
1427
1428        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
1429
1430
1431        return $offset;
1432    }
1433
1434    private function _getStatus($id) {
1435        $a = array(
1436            STATUS_CONFIRMED => 'ACCEPTED',
1437            STATUS_CANCELLED => 'CANCELLED',
1438            STATUS_TENTATIVE => 'TENTATIVE',
1439            STATUS_UNANSWERED => 'NEEDS-ACTION',
1440            STATUS_DELEGATED => 'DELEGATED'
1441        );
1442
1443        return isset($a[$id]) ? $a[$id] : 'NEEDS-ACTION';
1444    }
1445
1446    public function decodeStatusTodo( $action )
1447    {
1448     $a = array(
1449        'NEED_ACTION' => STATUS_TODO_NEED_ACTION,
1450        'IN_PROGRESS' => STATUS_TODO_IN_PROGRESS  ,
1451        'COMPLETED' =>  STATUS_TODO_COMPLETED ,
1452        'CANCELLED'  => STATUS_TODO_CANCELLED
1453    );
1454
1455    return isset($a[$action]) ? $a[$action] : 'STATUS_TODO_NEED_ACTION';
1456   
1457    }
1458
1459    private function _getStatusTodo($id) {
1460        $a = array(
1461            STATUS_TODO_NEED_ACTION => 'NEED_ACTION',
1462            STATUS_TODO_IN_PROGRESS => 'IN_PROGRESS',
1463            STATUS_TODO_COMPLETED => 'COMPLETED',
1464            STATUS_TODO_CANCELLED => 'CANCELLED'
1465        );
1466
1467    return isset($a[$id]) ? $a[$id] : 'NEED_ACTION';
1468    }
1469
1470    private static function _checkParticipantByPermissions($schedulable) {
1471
1472        $calendarIds = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=','isOwner','0'), array('=', 'user', Config::me("uidNumber")))));
1473
1474        if($calendarIds && isset($calendarIds[0])){
1475            $ids = array();
1476            foreach($calendarIds as $value)
1477                    array_push($ids, $value['calendar']);
1478
1479            $signaturesOfOwners = Controller::find(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('IN', 'calendar', $ids) , array('=','isOwner','1')), 'deepness' => 2 ));
1480           
1481            foreach($signaturesOfOwners as $value){
1482                        if(self::_getParticipantByMail($value['user']['mail'], $schedulable['participants'])){
1483                            $eventoFromCalendar = Controller::read( array( 'concept' => 'calendarToSchedulable') , false, array('filter' => array('AND', array('=','schedulable',$schedulable['id']), array('=','calendar', $value['calendar']['id']))));
1484
1485                            return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => array($value['calendar']['id']) );
1486                        }
1487            }   
1488        }
1489        return array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1490    }
1491
1492    private static function _getParticipantByMail($mail, &$participants, $isFull = false) {
1493        if ($participants && $participants != '')
1494            foreach ($participants as $i => $v)
1495                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
1496                      return !!$isFull ? $v : $v['id'];
1497        return false;
1498    }
1499
1500    static private function nomalizeTZID($TZID) {
1501        if (isset(self::$timezonesMap[$TZID]))
1502            return self::$timezonesMap[$TZID];
1503        else if (in_array($TZID, self::$suportedTimzones))
1504            return $TZID;
1505        else
1506            return date_default_timezone_get();
1507    }
1508
1509    static private function date2timestamp($datetime, $tz = null) {
1510        if (!isset($datetime['hour']))
1511            $datetime['hour'] = '0';
1512        if (!isset($datetime['min']))
1513            $datetime['min'] = '0';
1514        if (!isset($datetime['sec']))
1515            $datetime['sec'] = '0';
1516
1517        foreach ($datetime as $dkey => $dvalue)
1518            if ('tz' != $dkey)
1519                $datetime[$dkey] = (integer) $dvalue;
1520
1521        if ($tz)
1522            $datetime['tz'] = $tz;
1523
1524        $offset = ( isset($datetime['tz']) && ( '' < trim($datetime['tz']))) ? iCalUtilityFunctions::_tz2offset($datetime['tz']) : 0;
1525
1526        return gmmktime($datetime['hour'], $datetime['min'], ($datetime['sec'] + $offset), $datetime['month'], $datetime['day'], $datetime['year']);
1527    }
1528
1529    static private function _makeCOUNTER($schedulable, $component, $params) {
1530        $interation = array();
1531        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1532
1533        /* Data de Inicio */
1534        $startTime = $component->getProperty('dtstart', false, true);
1535
1536        /* Tiem zone do evento */
1537        if (isset($startTime['params']['TZID']))
1538            $schedulable['timezone'] = self::nomalizeTZID($startTime['params']['TZID']);
1539        else
1540            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1541
1542        $objTimezone = new DateTimeZone($schedulable['timezone']);
1543
1544        if ($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1545            $schedulable['allDay'] = 1;
1546            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1547        } 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 */
1548            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID'], '@' . self::date2timestamp($startTime['value'])) . '000';
1549            $schedulable['allDay'] = 0;
1550        } else {
1551            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1552            if (strpos($params['prodid'], 'Outlook') !== false) {
1553                //Se o ics veio em utc não aplicar horario de verão
1554                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1555                $sTime->setTimezone($objTimezone);
1556                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1557                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1558            }
1559        }
1560
1561        /* Data de Termino */
1562        $endTime = $component->getProperty('dtend', false, true);
1563
1564        if ($endTime['params']['VALUE'] === 'DATE')
1565            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1566        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 */
1567            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID'], '@' . self::date2timestamp($endTime['value'])) . '000';
1568        else {
1569            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1570            if (strpos($params['prodid'], 'Outlook') !== false) {
1571                //Se o ics veio em utc não aplicar horario de verão
1572                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1573                $eTime->setTimezone($objTimezone);
1574                if ($eTime->format('I'))
1575                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1576            }
1577        }
1578        unset($schedulable['participants']);
1579        $interation['schedulable://' . $eventID] = $schedulable;
1580
1581        return $interation;
1582    }
1583
1584    static private function _makeVEVENT($schedulable, $component, $params) {
1585        $interation = array();
1586        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1587
1588        /* Data de Inicio */
1589        $startTime = $component->getProperty('dtstart', false, true);
1590
1591        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1592
1593        /* Tiem zone do evento */
1594        if ($tzid){
1595            $tzid = self::nomalizeTZID($tzid);
1596            $schedulable['timezone'] = $tzid;
1597        }else
1598            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1599
1600        $objTimezone = new DateTimeZone($schedulable['timezone']);
1601
1602        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' ) {
1603            $schedulable['allDay'] = 1;
1604            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1605        } 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 */
1606            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1607            $schedulable['allDay'] = 0;
1608        } else {
1609            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1610            if (strpos($params['prodid'], 'Outlook') !== false) {
1611                //Se o ics veio em utc não aplicar horario de verão
1612                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1613                $sTime->setTimezone($objTimezone);
1614                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1615                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1616            }
1617        }
1618
1619        /* Data de Termino */
1620        $endTime = $component->getProperty('dtend', false, true);
1621
1622        $tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
1623       
1624        if($tzid)
1625            $tzid = self::nomalizeTZID($tzid);
1626
1627        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
1628            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1629        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 */
1630            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($endTime['value'])) . '000';
1631        else {
1632            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1633            if (strpos($params['prodid'], 'Outlook') !== false) {
1634                //Se o ics veio em utc não aplicar horario de verão
1635                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1636                $eTime->setTimezone($objTimezone);
1637                if ($eTime->format('I'))
1638                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1639            }
1640        }
1641
1642
1643        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1644
1645        /* Definindo Description */
1646        if ($desc = $component->getProperty('description', false, false))
1647            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1648
1649        /* Definindo location */
1650        if ($location = $component->getProperty('location', false, false))
1651            $schedulable['location'] = mb_convert_encoding($location, 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1652
1653
1654        /* Definindo Class */
1655        $class = $component->getProperty('class', false, false);
1656        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1657            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1658        else if (!isset($schedulable['class']))
1659            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1660
1661        /* Definindo RRULE */
1662        if ($rrule = $component->getProperty('rrule', false, false)) {
1663            /* Gera um randon id para o contexto formater */
1664            $repeatID = mt_rand() . '3(Formatter)';
1665
1666            $repeat = array();
1667            $repeat['schedulable'] = $eventID;
1668            $repeat['startTime'] = $schedulable['startTime'];
1669            foreach ($rrule as $i => $v) {
1670                if (strtolower($i) == 'freq')
1671                    $repeat['frequency'] = $v;
1672                else if (strtolower($i) == 'until')
1673            {
1674                $repeat['endTime'] = strtotime($v['year'].'-'.$v['month'].'-'.$v['day'].' '.$v['hour'].':'.$v['min'].':'.$v['sec'].' '.$v['tz']) .'000' ;
1675            }
1676                else
1677                    $repeat[strtolower($i)] = $v;
1678            }
1679
1680            $interation['repeat://' . $repeatID] = $repeat;
1681        }
1682
1683        $schedulable['calendar'] = $params['calendar'];
1684
1685        $participantsInEvent = array();
1686
1687        //TODO: Participants com delegated nao estao sendo levados em conta
1688        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1689            $participant = array();
1690
1691            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1692
1693            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
1694            $participant['schedulable'] = $eventID;
1695
1696            if (isset($params['status']) && $mailUser == Config::me('mail'))
1697                $participant['status'] = $params['status'];
1698            else
1699                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1700
1701
1702            $participant['isOrganizer'] = '0';
1703
1704            /* Verifica se este usuario é um usuario interno do ldap */
1705            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1706
1707            $user = null;
1708            if ($intUser && count($intUser) > 0) {
1709                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1710                $participant['user'] = $intUser[0]['id'];
1711            } else {
1712                $participant['isExternal'] = 1;
1713                /* Gera um randon id para o contexto formater */
1714                $userID = mt_rand() . '4(Formatter)';
1715
1716                $user['mail'] = $mailUser;
1717                $user['isExternal'] = '1';
1718                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1719                $user['participants'] = array($participantID);
1720                $participant['user'] = $userID;
1721                $interation['user://' . $userID] = $user;
1722            }
1723
1724            $interation['participant://' . $participantID] = $participant;
1725            $schedulable['participants'][] = $participantID;
1726        };
1727
1728        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1729
1730            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1731
1732
1733            if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
1734
1735                $participantID = $participant['id'];
1736
1737            }else{
1738
1739                $participant = array();
1740
1741                $participantID = mt_rand() . '2(Formatter)';
1742                $participant['schedulable'] = $eventID;
1743                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1744                $participant['isOrganizer'] = '1';
1745                $participant['acl'] = 'rowi';
1746            }
1747
1748            /* Verifica se este usuario é um usuario interno do ldap */
1749            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1750            $user = null;
1751            if ($intUser && count($intUser) > 0) {
1752                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1753                $participant['user'] = $intUser[0]['id'];
1754            } else {
1755                $participant['isExternal'] = 1;
1756                /* Gera um randon id para o contexto formater */
1757                $userID = mt_rand() . '4(Formatter)';
1758
1759                $user['mail'] = $mailUser;
1760                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1761                $user['participants'] = array($participantID);
1762                $user['isExternal'] = '1';
1763                $participant['user'] = $userID;
1764                $interation['user://' . $userID] = $user;
1765            }
1766
1767            $interation['participant://' . $participantID] = $participant;
1768            $schedulable['participants'][] = $participantID;
1769        } else if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
1770            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
1771
1772            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
1773                        $participantID = mt_rand() . '2(Formatter)';
1774
1775                        $participant['schedulable'] = $eventID;
1776                        $participant['status'] = STATUS_CONFIRMED;
1777                        $participant['isOrganizer'] = '1';
1778                        $participant['acl'] = 'rowi';
1779                        $participant['isExternal'] = 0;
1780                        $participant['user'] = $params['owner'];
1781                        $interation['participant://' . $participantID] = $participant;
1782                        $schedulable['participants'][] = $participantID;
1783            }
1784        }
1785       
1786        $alarms = array();
1787       
1788        /* Definindo ALARMES */
1789        while ($alarmComp = $component->getComponent('valarm'))
1790        {
1791                $alarm = array();
1792                $alarmID = mt_rand() . '6(Formatter)';
1793                $action =  $alarmComp->getProperty('action', false, true);
1794                $trygger = $alarmComp->getProperty('trigger', false, true);
1795                $alarm['type'] = self::decodeAlarmAction($action['value']);
1796
1797                 if(isset($trygger['value']['day']))
1798                {
1799                        $alarm['time'] = $trygger['value']['day'];
1800                        $alarm['unit'] = 'd';
1801                }
1802                else if(isset($trygger['value']['hour']))
1803                {
1804                        $alarm['time'] = $trygger['value']['hour'];
1805                        $alarm['unit'] = 'h';
1806                }
1807                else if(isset($trygger['value']['min']))
1808                {
1809                        $alarm['time'] = $trygger['value']['min'];
1810                        $alarm['unit'] = 'm';
1811                }
1812               
1813                foreach ($interation as $iint => &$vint)
1814                {
1815                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
1816                        {
1817                                $alarm['participant'] = str_replace('participant://', '', $iint);       
1818                                $vint['alarms'][] = $alarmID;
1819                        }
1820                }
1821                $alarm['schedulable'] = $eventID;
1822                               
1823                $interation['alarm://' . $alarmID ] = $alarm;
1824               
1825        }
1826       
1827       
1828        /* Definindo DTSTAMP */
1829        if ($dtstamp = self::_getTime($component, 'dtstamp'))
1830            $schedulable['dtstamp'] = $dtstamp;
1831
1832        /* Definindo TRANSP */
1833        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
1834            $schedulable['transparent'] = 1;
1835
1836        /* Definindo last_update */
1837        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
1838            $schedulable['lastUpdate'] = $lastUpdate;
1839
1840
1841        if ($sequence = $component->getProperty('SEQUENCE', false, false))
1842            $schedulable['sequence'] = $sequence;
1843
1844        if ($uid = $component->getProperty('uid', false, false))
1845            ;
1846        $schedulable['uid'] = $uid;
1847
1848        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
1849
1850            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
1851                'size' => strlen($attach['value']),
1852                'type' => self::_getContentType($attach['params']['X-FILENAME'])
1853            );
1854
1855            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
1856
1857            if (!is_array($ids)) {
1858                $attachCurrent['source'] = $attach['value'];
1859                //insere o anexo no banco e pega id para colcar no relacionamento                               
1860                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
1861            }else
1862                $idAttachment = array('id' => $ids[0]['id']);
1863
1864            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
1865            $calendarToAttachment['attachment'] = $idAttachment['id'];
1866            $calendarToAttachment['schedulable'] = $eventID;
1867            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
1868
1869            $schedulable['attachments'][] = $calendarToAttachmentId;
1870        }
1871
1872        $schedulable['type'] = '1';
1873
1874        $interation['schedulable://' . $eventID] = $schedulable;
1875
1876        return $interation;
1877    }
1878   
1879    static private function _makeVTODO($schedulable, $component, $params) {
1880        $interation = array();
1881        $todoID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1882
1883        /* Data de Inicio */
1884        $startTime = $component->getProperty('dtstart', false, true);
1885
1886        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1887
1888        /* Tiem zone do evento */
1889        if ($tzid){
1890            $tzid = self::nomalizeTZID($tzid);
1891            $schedulable['timezone'] = $tzid;
1892        }else
1893            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1894
1895        $objTimezone = new DateTimeZone($schedulable['timezone']);
1896
1897        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1898            $schedulable['allDay'] = 1;
1899            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1900        } 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 */
1901            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1902            $schedulable['allDay'] = 0;
1903        } else {
1904            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1905            if (strpos($params['prodid'], 'Outlook') !== false) {
1906                //Se o ics veio em utc não aplicar horario de verão
1907                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1908                $sTime->setTimezone($objTimezone);
1909                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1910                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1911            }
1912        }
1913
1914        /* Data de Termino */
1915        if($due = $component->getProperty('due', false, true)){
1916
1917        $tzid = isset($due['params']['TZID']) ? $due['params']['TZID'] : $params['X-WR-TIMEZONE'];
1918
1919        if($tzid)
1920            $tzid = self::nomalizeTZID($tzid);
1921
1922        if (isset($due['params']['VALUE']) && $due['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']))
1923            $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($due['value'])) . '000';
1924        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 */
1925            $schedulable['due'] = self::date2timestamp($due['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($due['value'])) . '000';
1926        else {
1927            $schedulable['due'] = self::date2timestamp($due['value']) . '000';
1928            if (strpos($params['prodid'], 'Outlook') !== false) {
1929            //Se o ics veio em utc não aplicar horario de verão
1930            $dueTime = new DateTime('@' . (int) ($schedulable['due'] / 1000), new DateTimeZone('UTC'));
1931            $dueTime->setTimezone($objTimezone);
1932
1933            if ($dueTime->format('I'))
1934                $schedulable['due'] = $schedulable['due'] - 3600000;
1935            }
1936        }
1937        $schedulable['endTime'] = $schedulable['due'];
1938    }else
1939        $schedulable['endTime'] = $schedulable['startTime'];
1940
1941        $schedulable['type'] = '2'; //type schedulable
1942        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1943
1944        /* Definindo Description */
1945        if ($desc = $component->getProperty('description', false, false))
1946            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1947
1948        /* Definindo Class */
1949        $class = $component->getProperty('class', false, false);
1950        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1951            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1952        else if (!isset($schedulable['class']))
1953            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1954
1955        $schedulable['calendar'] = $params['calendar'];
1956
1957        $participantsInTodo = array();
1958
1959        //TODO: Participants com delegated nao estao sendo levados em conta
1960        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1961            $participant = array();
1962
1963            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1964
1965            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
1966            $participant['schedulable'] = $todoID;
1967
1968            if (isset($params['status']) && $mailUser == Config::me('mail'))
1969                $participant['status'] = $params['status'];
1970            else
1971                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1972
1973
1974            $participant['isOrganizer'] = '0';
1975
1976            /* Verifica se este usuario é um usuario interno do ldap */
1977            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1978
1979            $user = null;
1980            if ($intUser && count($intUser) > 0) {
1981                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1982                $participant['user'] = $intUser[0]['id'];
1983            } else {
1984                $participant['isExternal'] = 1;
1985                /* Gera um randon id para o contexto formater */
1986                $userID = mt_rand() . '4(Formatter)';
1987
1988                $user['mail'] = $mailUser;
1989                $user['isExternal'] = '1';
1990                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1991                $user['participants'] = array($participantID);
1992                $participant['user'] = $userID;
1993                $interation['user://' . $userID] = $user;
1994            }
1995
1996            $interation['participant://' . $participantID] = $participant;
1997            $schedulable['participants'][] = $participantID;
1998        };
1999
2000        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
2001            $participant = array();
2002            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
2003
2004        if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
2005
2006            $participantID = $participant['id'];
2007
2008        }else{
2009
2010            $participant = array();
2011
2012            $participantID = mt_rand() . '2(Formatter)';
2013            $participant['schedulable'] = $todoID;
2014            $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
2015            $participant['isOrganizer'] = '1';
2016            $participant['acl'] = 'rowi';
2017        }
2018
2019            /* Verifica se este usuario é um usuario interno do ldap */
2020            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
2021
2022            $user = null;
2023            if ($intUser && count($intUser) > 0) {
2024                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
2025                $participant['user'] = $intUser[0]['id'];
2026            } else {
2027                $participant['isExternal'] = 1;
2028                /* Gera um randon id para o contexto formater */
2029                $userID = mt_rand() . '4(Formatter)';
2030
2031                $user['mail'] = $mailUser;
2032                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
2033                $user['participants'] = array($participantID);
2034                $user['isExternal'] = '1';
2035                $participant['user'] = $userID;
2036                $interation['user://' . $userID] = $user;
2037            }
2038
2039            $interation['participant://' . $participantID] = $participant;
2040            $schedulable['participants'][] = $participantID;
2041            } else if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
2042            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
2043
2044            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
2045                $participantID = mt_rand() . '2(Formatter)';
2046
2047                $participant['schedulable'] = $todoID;
2048                $participant['status'] = STATUS_CONFIRMED;
2049                $participant['isOrganizer'] = '1';
2050                $participant['acl'] = 'rowi';
2051                $participant['isExternal'] = 0;
2052                $participant['user'] = $params['owner'];
2053                $interation['participant://' . $participantID] = $participant;
2054                $schedulable['participants'][] = $participantID;
2055            }
2056        }
2057       
2058        $alarms = array();
2059       
2060        /* Definindo ALARMES */
2061        while ($alarmComp = $component->getComponent('valarm'))
2062        {
2063                $alarm = array();
2064                $alarmID = mt_rand() . '6(Formatter)';
2065                $action =  $alarmComp->getProperty('action', false, true);
2066                $trygger = $alarmComp->getProperty('trigger', false, true);
2067                $alarm['type'] = self::decodeAlarmAction($action['value']);
2068
2069                 if(isset($trygger['value']['day']))
2070                {
2071                        $alarm['time'] = $trygger['value']['day'];
2072                        $alarm['unit'] = 'd';
2073                }
2074                else if(isset($trygger['value']['hour']))
2075                {
2076                        $alarm['time'] = $trygger['value']['hour'];
2077                        $alarm['unit'] = 'h';
2078                }
2079                else if(isset($trygger['value']['min']))
2080                {
2081                        $alarm['time'] = $trygger['value']['min'];
2082                        $alarm['unit'] = 'm';
2083                }
2084               
2085                foreach ($interation as $iint => &$vint)
2086                {
2087                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
2088                        {
2089                                $alarm['participant'] = str_replace('participant://', '', $iint);       
2090                                $vint['alarms'][] = $alarmID;
2091                        }
2092                }
2093                $alarm['schedulable'] = $eventID;
2094                               
2095                $interation['alarm://' . $alarmID ] = $alarm;
2096               
2097        }
2098       
2099       
2100        /* Definindo DTSTAMP */
2101        if ($dtstamp = self::_getTime($component, 'dtstamp'))
2102            $schedulable['dtstamp'] = $dtstamp;
2103
2104        /* Definindo TRANSP */
2105        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
2106            $schedulable['transparent'] = 1;
2107
2108        /* Definindo last_update */
2109        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
2110            $schedulable['lastUpdate'] = $lastUpdate;
2111
2112
2113        if ($sequence = $component->getProperty('SEQUENCE', false, false))
2114            $schedulable['sequence'] = $sequence;
2115
2116        if ($uid = $component->getProperty('uid', false, false))
2117            ;
2118        $schedulable['uid'] = $uid;
2119
2120        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
2121
2122            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
2123                'size' => strlen($attach['value']),
2124                'type' => self::_getContentType($attach['params']['X-FILENAME'])
2125            );
2126
2127            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
2128
2129            if (!is_array($ids)) {
2130                $attachCurrent['source'] = $attach['value'];
2131                //insere o anexo no banco e pega id para colcar no relacionamento                               
2132                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
2133            }else
2134                $idAttachment = array('id' => $ids[0]['id']);
2135
2136            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
2137            $calendarToAttachment['attachment'] = $idAttachment['id'];
2138            $calendarToAttachment['schedulable'] = $eventID;
2139            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
2140
2141            $schedulable['attachments'][] = $calendarToAttachmentId;
2142        }
2143
2144        $interation['schedulable://' . $todoID] = $schedulable;
2145
2146    return $interation;
2147    }
2148
2149    static private function _getSchedulable($uid) {
2150        $schedulable = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'uid', $uid), 'deepness' => 2));
2151        return (isset($schedulable[0])) ? $schedulable[0] : false;
2152    }
2153
2154    static private function _existInMyCalendars($id, $owner) {
2155        $sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'isOwner', '1'), array('=', 'user', $owner))));
2156        $sig2 = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('*', 'acl', 'w'), array('=', 'user', $owner))));
2157
2158        $calendars = array();
2159        if(is_array($sig))
2160                foreach ($sig as $val)
2161                    $calendars[] = $val['calendar'];
2162        if(is_array($sig2))
2163                foreach ($sig2 as $val)
2164                    $calendars[] = $val['calendar'];
2165
2166
2167        $return = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('AND', array('IN', 'calendar', $calendars), array('=', 'schedulable', $id))));
2168
2169        return (isset($return[0])) ? $return[0]['calendar'] : false;
2170    }
2171
2172    static private function _getTime(&$component, $property) {
2173        if ($date = $component->getProperty($property, false, true))
2174            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';
2175
2176        return false;
2177    }
2178
2179    static private function _getContentType($fileName) {
2180        $strFileType = strtolower(substr($fileName, strrpos($fileName, '.')));
2181
2182        switch ($strFileType) {
2183            case ".asf": return "video/x-ms-asf";
2184            case ".avi": return "video/avi";
2185            case ".doc": return "application/msword";
2186            case ".zip": return "application/zip";
2187            case ".xls": return "application/vnd.ms-excel";
2188            case ".gif": return "image/gif";
2189            case ".bmp": return "image/bmp";
2190            case ".jpeg":
2191            case ".jpg": return "image/jpeg";
2192            case ".wav": return "audio/wav";
2193            case ".mp3": return "audio/mpeg3";
2194            case ".mpeg":
2195            case ".mpg": return "video/mpeg";
2196            case ".rtf": return "application/rtf";
2197            case ".html":
2198            case ".htm": return "text/html";
2199            case ".xml": return "text/xml";
2200            case ".xsl": return "text/xsl";
2201            case ".css": return "text/css";
2202            case ".php": return "text/php";
2203            case ".asp": return "text/asp";
2204            case ".pdf": return "application/pdf";
2205            case ".png": return "image/png";
2206            case ".txt": return "text/plain";
2207            case ".log": return "text/plain";
2208            case ".wmv": return "video/x-ms-wmv";
2209            case ".sxc": return "application/vnd.sun.xml.calc";
2210            case ".odt": return "application/vnd.oasis.opendocument.text";
2211            case ".stc": return "application/vnd.sun.xml.calc.template";
2212            case ".sxd": return "application/vnd.sun.xml.draw";
2213            case ".std": return "application/vnd.sun.xml.draw.template";
2214            case ".sxi": return "application/vnd.sun.xml.impress";
2215            case ".sti": return "application/vnd.sun.xml.impress.template";
2216            case ".sxm": return "application/vnd.sun.xml.math";
2217            case ".sxw": return "application/vnd.sun.xml.writer";
2218            case ".sxq": return "application/vnd.sun.xml.writer.global";
2219            case ".stw": return "application/vnd.sun.xml.writer.template";
2220            case ".pps": return "application/vnd.ms-powerpoint";
2221            case ".odt": return "application/vnd.oasis.opendocument.text";
2222            case ".ott": return "application/vnd.oasis.opendocument.text-template";
2223            case ".oth": return "application/vnd.oasis.opendocument.text-web";
2224            case ".odm": return "application/vnd.oasis.opendocument.text-master";
2225            case ".odg": return "application/vnd.oasis.opendocument.graphics";
2226            case ".otg": return "application/vnd.oasis.opendocument.graphics-template";
2227            case ".odp": return "application/vnd.oasis.opendocument.presentation";
2228            case ".otp": return "application/vnd.oasis.opendocument.presentation-template";
2229            case ".ods": return "application/vnd.oasis.opendocument.spreadsheet";
2230            case ".ots": return "application/vnd.oasis.opendocument.spreadsheet-template";
2231            case ".odc": return "application/vnd.oasis.opendocument.chart";
2232            case ".odf": return "application/vnd.oasis.opendocument.formula";
2233            case ".odi": return "application/vnd.oasis.opendocument.image";
2234            case ".ndl": return "application/vnd.lotus-notes";
2235            case ".eml": return "text/plain";
2236            case ".ps" : return "application/postscript";
2237            default : return "application/octet-stream";
2238        }
2239    }
2240   
2241    public function codeAlarmAction( $action )
2242    {
2243        switch ($action)
2244        {
2245                case ALARM_MAIL :
2246                                return  'EMAIL';
2247                                break;
2248                case ALARM_ALERT :
2249                                return  'DISPLAY';
2250                                break;
2251                case 'mail' :
2252                                        return  'EMAIL';
2253                                        break;
2254                case 'alert'  :
2255                                        return  'DISPLAY';
2256                                        break;
2257        }
2258       
2259    }
2260   
2261    public function decodeAlarmAction( $action )
2262    {
2263        switch ( $action )
2264        {
2265                case 'EMAIL'  :
2266                        return  'mail';
2267                        break;
2268                case 'DISPLAY' :
2269                        return  'alert';
2270                        break;
2271
2272        }
2273   
2274    }
2275
2276    private static function schedulable2calendarToObject($Schedulable, $user = false) {
2277        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature'
2278            . ' WHERE calendar_signature.user_uidnumber = ' . $user ? $user : Config::me('uidNumber')
2279            //      .' AND calendar_signature.is_owner = 1'
2280            . ' AND calendar_signature.calendar_id = calendar.id'
2281            . ' AND calendar_to_calendar_object.calendar_id = calendar.id'
2282            . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($Schedulable));
2283    }
2284}
2285
2286?>
Note: See TracBrowser for help on using the repository browser.