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

Revision 7704, 117.4 KB checked in by cristiano, 11 years ago (diff)

Ticket #3263 - Problema ao tentar aceitar um convite em conta compartilhada

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