source: sandbox/2.4.2-expresso1/prototype/services/iCal.php @ 6985

Revision 6985, 95.4 KB checked in by acoutinho, 12 years ago (diff)

Ticket #2966 - Correcao de bugs e refactoring das novas funcionalidades

Line 
1<?php
2
3require_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        $timezones = array_flip(self::$timezonesMap);
20
21        $ical = new icalCreator();
22
23        $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
24        $sytemTimezone = (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo';
25        $params['defaultTZI'] = self::nomalizeTZID((isset($params['defaultTZI']) && $params['defaultTZI'] != 'null') ? $params['defaultTZI'] : $sytemTimezone );
26
27        /*
28         * Seta propiedades obrigatorias para alguns softwares (Outlook)
29         */
30        $ical->setProperty('x-wr-calname', 'Calendar Expresso');
31        $ical->setProperty('X-WR-CALDESC', 'Calendar Expresso');
32        $ical->setProperty('X-WR-TIMEZONE', isset($timezones[$params['defaultTZI']]) ? $timezones[$params['defaultTZI']] : $params['defaultTZI']);
33
34        foreach ($data as $i => $v) {
35
36            switch ($v['type']) {
37                case EVENT_ID:
38                    $vevent = $ical->newComponent('vevent');
39
40                    $vevent->setProperty('summary', $v['summary']);
41                    $vevent->setProperty('description', isset($v['description']) ? $v['description'] : '');
42                    $vevent->setProperty('location', $v['location']);
43                    $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
44
45                    $timezone = new DateTimeZone('UTC');
46                    $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
47                    $apTimezoneOBJ = new DateTimeZone($apTimezone);
48
49                    $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
50                    $sTime->setTimezone($apTimezoneOBJ);
51                    $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
52                    $eTime->setTimezone($apTimezoneOBJ);
53
54                    if (( isset($v['repeat']) ) && ( $v['repeat']['frequency'] != 'none' )) {
55                        $repeat = array();
56
57                        foreach ($v['repeat'] as $ir => $rv) {
58                            if ($rv) {
59                                if ($ir == 'frequency' && $rv !== 'none')
60                                    $repeat['FREQ'] = $rv;
61                                else if ($ir == 'endTime') {
62                                    $time = new DateTime('@' . (int) ($rv / 1000), $timezone);
63                                    $time->setTimezone($apTimezoneOBJ);
64                                    $repeat['until'] = $time->format(DATE_RFC822);
65                                } else if ($ir == 'count')
66                                    $repeat[$ir] = $rv;
67                                else if ($ir == 'interval')
68                                    $repeat[$ir] = $rv;
69                                else if ($ir !== 'schedulable' && $ir !== 'id' && $ir !== 'startTime')
70                                    $repeat[$ir] = explode(',', $rv);
71                            }
72                        }
73
74                        if (isset($repeat['FREQ']))
75                            $vevent->setProperty('rrule', $repeat);
76                    }
77
78                    if (isset($v['allDay']) && $v['allDay'] == 1) {
79                        $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
80                        $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
81                        $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
82                    } else {
83                        $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
84                        $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
85                        $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
86                    }
87                                   
88                    if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
89                        $participants = $v['participants'];
90                    else
91                                $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
92                   
93                        if (is_array($participants) && count($participants) > 0)
94                                foreach ($participants as $ii => $vv) {
95                               
96                                        if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
97                                        {
98                                                if ($vv['isExternal'] == 1)
99                                                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
100                                                else
101                                                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
102                                        }
103                               
104                                        if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
105                                        {
106                                                $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']))));
107                                                if(is_array($alarms))
108                                                        self::createAlarms($alarms, $vevent);
109                                        }
110                               
111                                }
112                   
113
114                    if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
115                                $this->createAttendee($v['participants'], $vevent);
116
117                    if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
118                                $this->createAttachment($v['attachments'], $vevent);
119
120                    $vevent->setProperty('uid', $v['uid']); 
121                   
122                    break;
123
124        case TASK_ID:
125
126            $todo = $ical->newComponent('todo');
127
128            $todo->setProperty('summary', $v['summary']);
129            $todo->setProperty('description', isset($v['description']) ? $v['description'] : '');
130            $todo->setProperty('priority', $v['priority']);
131            $todo->setProperty('percent-complete', $v['percentage']);
132            $todo->setProperty('status', $this->_getStatusTodo($v['status']));
133
134            $timezone = new DateTimeZone('UTC');
135            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
136            $apTimezoneOBJ = new DateTimeZone($apTimezone);
137
138            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
139            $sTime->setTimezone($apTimezoneOBJ);
140            $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
141            $eTime->setTimezone($apTimezoneOBJ);
142
143            if (isset($v['allDay']) && $v['allDay'] == 1) {
144                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
145                $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
146                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
147            } else {
148                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
149                $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
150                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
151            }
152
153            if(isset($v['due']) && $v['due'] != ''){
154                $dueTime = new DateTime('@' . (int) ($v['due'] / 1000), $timezone);
155                $dueTime->setTimezone($apTimezoneOBJ);
156
157                $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
158            }
159           
160            $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
161                   
162            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
163                $participants = $v['participants'];
164            else
165                $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
166           
167            if (is_array($participants) && count($participants) > 0)
168                foreach ($participants as $ii => $vv) {
169               
170                    if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
171                    {
172                        if ($vv['isExternal'] == 1)
173                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
174                        else
175                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
176                    }
177               
178                    if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
179                    {
180                        $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']))));
181                        if(is_array($alarms))
182                            self::createAlarms($alarms, $todo);
183                    }
184               
185                }
186
187            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
188                $this->createAttendee($v['participants'], $todo);
189
190            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
191                $this->createAttachment($v['attachments'], $todo);
192
193            $todo->setProperty('uid', $v['uid']); 
194           
195            break;
196
197                default:
198                    break;
199            }
200        }
201
202       
203        return $ical->createCalendar();
204    }
205   
206    public function createAlarms($alarms, &$vevent)
207    {   
208            foreach ($alarms as $ia => $va)
209            {
210                $valarm = new valarm();
211                $valarm->setProperty('ACTION' , self::codeAlarmAction($va['type']));
212               
213                $duration = array();
214               
215                switch ($va['unit'])
216                {
217                        case 'h':
218                                $duration['hour'] = $va['time'];
219                        break;
220                        case 'm':
221                                $duration['min'] = $va['time'];
222                        break;
223                        case 's':
224                                $duration['sec'] = $va['time'];
225                                break;
226                }
227               
228                $valarm->setProperty('trigger' ,$duration);
229                $vevent->setComponent($valarm);
230            }   
231       
232    }
233
234    //Trata a criacao de anexos do ics
235    public function createAttachment($attachments, &$vevent) {
236        foreach ($attachments as $key => $attachment) {
237            $pParams = array("ENCODING" => "BASE64", "VALUE" => "BINARY",
238                "X-FILENAME" => $attachment['name']);
239
240            $vevent->setProperty("attach", $attachment['source'], $pParams);
241        }
242    }
243
244    //Trata a criacao de attendees com tratamento de delegate
245    public function createAttendee($attendees, &$vevent) {
246        $delegate = array();
247        foreach ($attendees as $di => $dv) {
248            if (isset($dv['delegatedFrom']) && $dv['delegatedFrom'] != 0) {
249                $delegate[$dv['delegatedFrom']] = $dv;
250            }
251        }
252
253        foreach ($attendees as $pi => $pv) {
254            $isResponseDelegated = false;
255            if ((isset($pv['delegatedFrom']) && $pv['delegatedFrom'] == 0) || !isset($pv['delegatedFrom']))  {
256                if ($pv['isOrganizer'] == 1)
257                    $vevent->setProperty('organizer', $pv['user']['mail'], array('CN' => $pv['user']['name']));
258                else {
259                    $pParams = array();
260                    $pParams['CN'] = $pv['user']['name'];
261                    $pParams['PARTSTAT'] = self::_getStatus($pv['status']);
262
263                    if (isset($pv['id']) && isset($delegate[$pv['id']])) {
264                        $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
265                        $pParams['DELEGATED-TO'] = $delegate[$pv['id']]['user']['mail'];
266                        $pParams['CN'] = $pv['user']['name'];
267
268                        $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
269
270                        if ($delegate[$pv['id']]['status'] == STATUS_UNANSWERED) {
271                            $pParams['RSVP'] = $pv['receiveNotification'] == 1 ? 'TRUE' : 'FALSE';
272                            unset($pParams['PARTSTAT']);
273                        }else
274                            $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
275
276                        unset($pParams['DELEGATED-TO']);
277                        $pParams['DELEGATED-FROM'] = $pv['user']['mail'];
278
279                        $vevent->setProperty('attendee', $delegate[$pv['id']]['user']['mail'], $pParams);
280                        continue;
281                    }
282                    $pParams['RSVP'] = 'TRUE';
283
284                    $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
285
286                }
287            }
288           
289           
290        }
291    }
292
293    public function parse($data, $params = false) {
294        Config::regSet('noAlarm', TRUE); //Evita o envio de notificação
295        $vcalendar = new icalCreator( );
296        $vcalendar->parse(trim($data));
297        $vcalendar->sort();
298
299        $return = array();
300        $method = $vcalendar->getProperty('method', FALSE, FALSE);
301        $params['prodid'] = $vcalendar->getProperty('prodid', false, false);
302        $params['X-WR-TIMEZONE'] = ( $xrTimezone = $vcalendar->getProperty('X-WR-TIMEZONE', false, false)) ? self::nomalizeTZID($xrTimezone[1]) : false ;
303
304        while ($component = $vcalendar->getComponent()) {
305            $interation = array();
306            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
307
308            switch (strtoupper($component->objName)) {
309                case 'VEVENT':
310
311                    switch ($method) {
312                        case 'PUBLISH':
313                            //Caso o evento não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
314                            if (!$schedulable = self::_getSchedulable($uid))
315                                $interation = self::_makeVEVENT($schedulable, $component, $params);
316                            else{
317                                $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
318                                array('AND',
319                                    array('=', 'calendar', $params['calendar']),
320                                    array('=', 'schedulable', $schedulable['id'])
321                                )));
322
323                                if(!$links &&  !isset($links[0]))
324                                    Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
325
326                                }
327                            break;
328
329                        case 'REQUEST':
330                            $schedulable = self::_getSchedulable($uid);
331
332                            if ($schedulable) { //Caso o evento exista
333                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
334                                    $calendarToSchedulable = array();
335                                    $calendarToSchedulable['calendar'] = $params['calendar'];
336                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
337                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
338   
339                                    if (isset($params['status'])) {
340                                        if($params['owner'] != Config::me("uidNumber")){                                           
341                                            $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                                           
342                                            $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
343                                        }else
344                                            $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
345                                        $interation['participant://' . $pID]['status'] = $params['status'];
346                                    }
347
348                                    Config::regSet('noAlarm', FALSE); //reativa notificação
349                                } else {
350
351                                    if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
352                                        $interation = self::_makeVEVENT($schedulable, $component, $params);
353                                    else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
354                                        //Ler melhor rfc sobre isto 3.2.2.2
355                                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
356                                    }
357
358                                    if (isset($params['status'])) {
359                                        if($params['owner'] != Config::me("uidNumber")){                                           
360                                           $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                                     
361                                            $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
362                                        }else
363                                            $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
364                                        //Verifica a importação de eventos em que não participo
365                                        if ($pID) {
366                                            $interation['participant://' . $pID]['status'] = $params['status'];
367                                        }
368                                    }
369                                }
370                            } else { // Importar evento
371                                $interation = self::_makeVEVENT(array(), $component, $params);
372
373                                if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
374
375                                    /* Data de Inicio */
376                                    $startTime = $component->getProperty('dtstart', false, true);
377
378                                    $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
379
380                                    /* Tiem zone do evento */   
381                                    if ($tzid)
382                                        $sc['timezone'] = self::nomalizeTZID($tzid);
383                                    else
384                                        $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
385
386                                    $objTimezone = new DateTimeZone($sc['timezone']);
387
388                                    if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
389                                        $sc['allDay'] = 1;
390                                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
391                                    } 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 */
392                                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
393                                    else {
394                                        $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
395                                        if (strpos($params['prodid'], 'Outlook') !== false) {
396                                            //Se o ics veio em utc não aplicar horario de verão
397                                            $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
398                                            $sTime->setTimezone($objTimezone);
399                                            if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
400                                                $sc['startTime'] = $sc['startTime'] - 3600000;
401                                        }
402                                    }
403
404
405                                    /* Data de Termino */
406                                    $endTime = $component->getProperty('dtend', false, true);
407
408                                    if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
409                                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
410                                    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 */
411                                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
412                                    else {
413                                        $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
414                                        if (strpos($params['prodid'], 'Outlook') !== false) {
415                                            //Se o ics veio em utc não aplicar horario de verão
416                                            $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
417                                            $eTime->setTimezone($objTimezone);
418                                            if ($eTime->format('I'))
419                                                $sc['endTime'] = $sc['endTime'] - 3600000;
420                                        }
421                                    }
422
423
424                                    if ($uid = $component->getProperty('uid', false, false))
425                                        ;
426                                    $sc['uid'] = $uid;
427
428
429                                    $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
430
431                                    /* Definindo Description */
432                                    if ($desc = $component->getProperty('description', false, false))
433                                        $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
434
435                                    /* Definindo location */
436                                    if ($location = $component->getProperty('location', false, false))
437                                        $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
438
439
440
441                                    if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
442                                        $participant = array();
443                                        $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
444
445                                        $participantID = mt_rand() . '2(Formatter)';
446
447                                        $participant['isOrganizer'] = '1';
448
449                                        $user = null;
450
451                                        $participant['isExternal'] = 1;
452                                        /* Gera um randon id para o contexto formater */
453                                        $userID = mt_rand() . '4(Formatter)';
454
455                                        $user['mail'] = $mailUser;
456                                        $organizerMail = $mailUser;
457
458                                        $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
459                                        $user['isExternal'] = '1';
460                                        $participant['user'] = $user;
461
462                                        $sc['participants'][] = $participant;
463                                    }
464
465
466                                    $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
467                                    $participant['isOrganizer'] = '0';
468                                    $participant['isExternal'] = 0;
469                                    $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
470                                    $sc['participants'][] = $participant;
471                                    $sc['type'] = EVENT_ID;
472
473
474                                    $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
475                                    $ical['type'] = 'application/ics';
476                                    $ical['name'] = 'outlook.ics';
477
478                                    $ical2['source'] = $ical['source'];
479                                    $ical2['type'] = 'text/calendar; method=REPLY';
480                                    $ical2['name'] = 'thunderbird.ics';
481
482                                    $timezone = new DateTimeZone('UTC');
483                                    $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
484                                    $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
485
486                                    if (isset($sc['timezone'])) {
487                                        $sTime->setTimezone(new DateTimeZone($sc['timezone']));
488                                        $eTime->setTimezone(new DateTimeZone($sc['timezone']));
489                                    }
490
491                                    $data = array('startDate' => date_format($sTime, 'd/m/Y'),
492                                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
493                                        'endDate' => date_format($eTime, 'd/m/Y'),
494                                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
495                                        'eventTitle' => $sc['summary'],
496                                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
497                                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
498                                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
499
500                                    $subject['notificationType'] = 'Convite Aceito';
501                                    $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
502                                    $subject['startDate'] = date_format($sTime, 'd/m/Y');
503                                    $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
504                                    $subject['endDate'] = date_format($eTime, 'd/m/Y');
505                                    $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
506                                    $subject['participant'] = Config::me('uid');
507
508                                    $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
509
510                                    switch ($params['status']) {
511                                        case STATUS_ACCEPTED:
512                                            $tpl = 'notify_accept_body';
513                                            $subject['notificationType'] = 'Convite Aceito';
514                                            break;
515                                        case STATUS_TENTATIVE:
516                                            $tpl = 'notify_attempt_body';
517                                            $subject['notificationType'] = 'Convite  aceito provisoriamente';
518                                            break;
519                                        case STATUS_CANCELLED:
520                                            $tpl = 'notify_reject_body';
521                                            $subject['notificationType'] = 'Convite rejeitado';
522                                            break;
523                                    }
524                                    require_once ROOTPATH . '/api/parseTPL.php';
525
526                                    $mail = array();
527                                    $mail['attachments'][] = $ical;
528                                    $mail['attachments'][] = $ical2;
529
530                                    $mail['isHtml'] = true;
531                                    $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
532                                    $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
533                                    ;
534                                    $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
535                                    $mail['to'] = $organizerMail;
536
537
538                                    Controller::create(array('service' => 'SMTP'), $mail);
539                                }
540                            }
541                            break;
542
543                        case 'REFRESH':
544                            break;
545
546                        case 'CANCEL':
547                            if ($schedulable = self::_getSchedulable($uid))
548                                $interation['schedulable://' . $schedulable['id']] = false;
549                            break;
550
551                        case 'ADD':
552                            break;
553
554                        case 'REPLY':
555                            if ($schedulable = self::_getSchedulable($uid)) {
556                                while ($property = $component->getProperty('attendee', FALSE, TRUE))
557                                    if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
558                                        $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
559
560                                $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
561                            }
562                            break;
563
564                        case 'COUNTER':
565                            if ($params['acceptedSuggestion'] !== 'false') {
566
567                                $schedulable = self::_getSchedulable($uid);
568                                $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
569
570                                $interation = self::_makeCOUNTER($schedulable, $component, $params);
571                                Config::regSet('noAlarm', FALSE);
572                            } else {
573                                $response = array();
574                                $response['from'] = $params['from'];
575                                $response['type'] = 'suggestionResponse';
576                                $response['status'] = 'DECLINECOUNTER';
577                                $response['schedulable'] = self::_getSchedulable($uid);
578
579                                Controller::create(array('concept' => 'notification'), $response);
580                            }
581                            break;
582
583                        case 'DECLINECOUNTER':
584                            break;
585
586                        default:
587
588                            $schedulable = self::_getSchedulable($uid);
589
590                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
591                                $interation = self::_makeVEVENT($schedulable, $component, $params);
592
593                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
594                                    $calendarToSchedulable = array();
595                                    $calendarToSchedulable['calendar'] = $params['calendar'];
596                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
597                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
598                                }
599                            }
600                            else // Importar evento
601                                $interation = self::_makeVEVENT(array(), $component, $params);
602                            break;
603                    }
604       
605                   
606                    $return[] = $interation;
607                    break;
608                /***********************************************************************TODO*******************************************************************************/
609        case 'VTODO':
610        switch ($method) {
611            case 'PUBLISH':
612                //Caso a tarefa não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
613                if (!$schedulable = self::_getSchedulable($uid))
614                    $interation = self::_makeVTODO($schedulable, $component, $params);
615                else{
616                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
617                    array('AND',
618                        array('=', 'calendar', $params['calendar']),
619                        array('=', 'schedulable', $schedulable['id'])
620                    )));
621
622                    if(!$links &&  !isset($links[0]))
623                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
624                }
625                break;
626
627            case 'REQUEST':
628                $schedulable = self::_getSchedulable($uid);
629
630                if ($schedulable) { //Caso tarefa exista
631                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
632                       
633                        $calendarToSchedulable = array();
634                        $calendarToSchedulable['calendar'] = $params['calendar'];
635                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
636                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
637       
638                        if (isset($params['status'])) {
639                            if($params['owner'] != Config::me("uidNumber")){                       
640                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                       
641                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
642                            }else
643                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
644                                $interation['participant://' . $pID]['status'] = $params['status'];
645                        }
646                        Config::regSet('noAlarm', FALSE); //reativa notificação
647                    } else {
648
649                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
650                            $interation = self::_makeVEVENT($schedulable, $component, $params);
651                        else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
652                        //Ler melhor rfc sobre isto 3.2.2.2
653                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
654                        }
655
656                        if (isset($params['status'])) {
657                            if($params['owner'] != Config::me("uidNumber")){                       
658                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                     
659                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
660                            }else
661                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
662                            //Verifica a importação de eventos em que não participo
663                            if ($pID) {
664                                $interation['participant://' . $pID]['status'] = $params['status'];
665                            }
666                        }
667                    }
668                } else { // Importar tarefa
669                    $interation = self::_makeVEVENT(array(), $component, $params);
670
671                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
672
673                        /* Data de Inicio */
674                        $startTime = $component->getProperty('dtstart', false, true);
675                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
676
677                        /* Tiem zone do evento */   
678                        if ($tzid)
679                            $sc['timezone'] = self::nomalizeTZID($tzid);
680                        else
681                            $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
682
683                        $objTimezone = new DateTimeZone($sc['timezone']);
684
685                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
686                            $sc['allDay'] = 1;
687                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
688                        } 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 */
689                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
690                        else {
691                            $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
692                            if (strpos($params['prodid'], 'Outlook') !== false) {
693                                //Se o ics veio em utc não aplicar horario de verão
694                                $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
695                                $sTime->setTimezone($objTimezone);
696                                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
697                                $sc['startTime'] = $sc['startTime'] - 3600000;
698                            }
699                        }
700
701                        /* Data de Termino */
702                        $endTime = $component->getProperty('dtend', false, true);
703
704                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
705                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
706                        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 */
707                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
708                        else {
709                            $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
710                            if (strpos($params['prodid'], 'Outlook') !== false) {
711                                //Se o ics veio em utc não aplicar horario de verão
712                                $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
713                                $eTime->setTimezone($objTimezone);
714                                if ($eTime->format('I'))
715                                    $sc['endTime'] = $sc['endTime'] - 3600000;
716                            }
717                        }
718
719
720                        if ($uid = $component->getProperty('uid', false, false))                   
721                            $sc['uid'] = $uid;
722
723                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
724
725                        /* Definindo Description */
726                        if ($desc = $component->getProperty('description', false, false))
727                            $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
728
729            if ($priority = $component->getProperty('priority', false, false))
730                $sc['priority'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $priority), 'UTF-8', 'UTF-8,ISO-8859-1');
731
732            if ($status = $component->getProperty('status', false, false))
733                $sc['status'] = $this->decodeStatusTodo(mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $status), 'UTF-8', 'UTF-8,ISO-8859-1'));
734
735            if ($percentage = $component->getProperty('percent-complete', false, false))
736                $sc['percentage'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $percentage), 'UTF-8', 'UTF-8,ISO-8859-1');
737
738            $todo->setProperty('priority', $v['priority']);
739            $todo->setProperty('percent-complete', $v['percentage']);
740            $todo->setProperty('status', $this->_getStatusTodo($v['status']));
741
742                        /* Definindo location */
743                        if ($location = $component->getProperty('location', false, false))
744                            $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
745
746
747
748                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
749                            $participant = array();
750                            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
751
752                            $participantID = mt_rand() . '2(Formatter)';
753
754                            $participant['isOrganizer'] = '1';
755
756                            $user = null;
757
758                            $participant['isExternal'] = 1;
759                            /* Gera um randon id para o contexto formater */
760                            $userID = mt_rand() . '4(Formatter)';
761
762                            $user['mail'] = $mailUser;
763                            $organizerMail = $mailUser;
764
765                            $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
766                            $user['isExternal'] = '1';
767                            $participant['user'] = $user;
768
769                            $sc['participants'][] = $participant;
770                        }
771
772
773                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
774                        $participant['isOrganizer'] = '0';
775                        $participant['isExternal'] = 0;
776                        $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
777                        $sc['participants'][] = $participant;
778                        $sc['type'] = TODO_ID;
779
780
781                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
782                        $ical['type'] = 'application/ics';
783                        $ical['name'] = 'outlook.ics';
784
785                        $ical2['source'] = $ical['source'];
786                        $ical2['type'] = 'text/calendar; method=REPLY';
787                        $ical2['name'] = 'thunderbird.ics';
788
789                        $timezone = new DateTimeZone('UTC');
790                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
791                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
792
793                        if (isset($sc['timezone'])) {
794                            $sTime->setTimezone(new DateTimeZone($sc['timezone']));
795                            $eTime->setTimezone(new DateTimeZone($sc['timezone']));
796                        }
797
798                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
799                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
800                        'endDate' => date_format($eTime, 'd/m/Y'),
801                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
802                        'eventTitle' => $sc['summary'],
803                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
804                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
805                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
806
807                        $subject['notificationType'] = 'Convite Aceito';
808                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
809                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
810                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
811                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
812                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
813                        $subject['participant'] = Config::me('uid');
814
815                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
816
817                        switch ($params['status']) {
818                            case STATUS_ACCEPTED:
819                                $tpl = 'notify_accept_body';
820                                $subject['notificationType'] = 'Convite Aceito';
821                                break;
822                            case STATUS_TENTATIVE:
823                                $tpl = 'notify_attempt_body';
824                                $subject['notificationType'] = 'Convite  aceito provisoriamente';
825                                break;
826                            case STATUS_CANCELLED:
827                                $tpl = 'notify_reject_body';
828                                $subject['notificationType'] = 'Convite rejeitado';
829                                break;
830                        }
831
832                        require_once ROOTPATH . '/api/parseTPL.php';
833
834                        $mail = array();
835                        $mail['attachments'][] = $ical;
836                        $mail['attachments'][] = $ical2;
837
838                        $mail['isHtml'] = true;
839                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
840                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
841
842                        $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
843                        $mail['to'] = $organizerMail;
844
845
846                        Controller::create(array('service' => 'SMTP'), $mail);
847                    }
848                }
849                break;
850
851            case 'REFRESH':
852                break;
853
854            case 'CANCEL':
855                if ($schedulable = self::_getSchedulable($uid))
856                    $interation['schedulable://' . $schedulable['id']] = false;
857                break;
858
859            case 'ADD':
860                break;
861
862            case 'REPLY':
863                if ($schedulable = self::_getSchedulable($uid)) {
864                    while ($property = $component->getProperty('attendee', FALSE, TRUE))
865                        if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
866                            $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
867
868                    $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
869                }
870                break;
871
872            case 'COUNTER':
873                if ($params['acceptedSuggestion'] !== 'false') {
874
875                    $schedulable = self::_getSchedulable($uid);
876                    $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
877
878                    $interation = self::_makeCOUNTER($schedulable, $component, $params);
879                    Config::regSet('noAlarm', FALSE);
880                } else {
881                    $response = array();
882                    $response['from'] = $params['from'];
883                    $response['type'] = 'suggestionResponse';
884                    $response['status'] = 'DECLINECOUNTER';
885                    $response['schedulable'] = self::_getSchedulable($uid);
886
887                    Controller::create(array('concept' => 'notification'), $response);
888                }
889                break;
890
891            case 'DECLINECOUNTER':
892                break;
893
894            default:
895
896                $schedulable = self::_getSchedulable($uid);
897
898                if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
899                    $interation = self::_makeVEVENT($schedulable, $component, $params);
900
901                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
902                        $calendarToSchedulable = array();
903                        $calendarToSchedulable['calendar'] = $params['calendar'];
904                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
905                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
906                    }
907                }
908                else // Importar evento
909                $interation = self::_makeVEVENT(array(), $component, $params);
910
911                break;
912            }
913   
914            $return[] = $interation;
915        break;
916        /***********************************************************************TODO*******************************************************************************/
917        case 'VTIMEZONE':
918                break;
919            }
920        }
921        return $return;
922    }
923
924    public function analize($data, $params = false) {
925        $vcalendar = new icalCreator( );
926        $vcalendar->parse(trim($data));
927        $vcalendar->sort();
928
929        $return = array();
930        $method = $vcalendar->getProperty('method', FALSE, FALSE);
931
932        while ($component = $vcalendar->getComponent()) {
933            $interation = array();
934            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
935            switch (strtoupper($component->objName)) {
936                case 'VEVENT':
937
938                    switch ($method) {
939                        case 'PUBLISH':
940                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
941                            break;
942
943                        case 'REQUEST':
944                            $schedulable = self::_getSchedulable($uid);
945                            if ($schedulable) { //Caso o evento exista
946                                $isOrganizer = false;
947                                $isParticipant = false;
948
949                                foreach ($schedulable['participants'] as $value)
950                                    if ($value['user']['id'] == $params['owner']) {
951                                        $isParticipant = true;
952                                        if ($value['isOrganizer'])
953                                            $isOrganizer = true;
954
955                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
956                                            $interation = ICAL_ACTION_UPDATE;
957                                            $interation = ( strrpos($value['acl'], ATTENDEE_ACL_PARTICIPATION_REQUIRED) ) ? ICAL_ACTION_IMPORT_REQUIRED : array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
958                                            break;
959                                        }
960                                    } else {
961                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
962                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
963                                        else
964                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
965                                    }
966                                if (!$isParticipant){
967                                      $interation = self::_checkParticipantByPermissions($schedulable);
968                                    }
969                            }else
970                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
971                           
972                            if(($interation != ICAL_ACTION_NONE) && ($interation != ICAL_ACTION_ORGANIZER_NONE) && ($interation != ICAL_ACTION_ORGANIZER_UPDATE) && ($interation != ICAL_ACTION_NONE)) {
973                                if($params['owner'] != Config::me("uidNumber")){
974                                    $sig = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=', 'user', $params['owner']), array('=', 'isOwner', '1'))));
975                                    $calendars = array();
976                                    foreach ($sig as $val)
977                                        $calendars[] = $val['calendar'];
978                               
979                                    $calendarsPermission = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('=', 'user', Config::me("uidNumber")), array('IN', 'calendar', $calendars))));   
980                                   
981                                    foreach ($calendarsPermission as $val)
982                                        $ids[] = $val['calendar'];
983
984                                    $interation = array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION ,'calendar' => $ids);
985                                }
986                            }
987
988                            break;
989
990                        case 'REFRESH':
991                            break;
992
993                        case 'CANCEL':
994                            $interation = ICAL_ACTION_DELETE;
995                            break;
996
997                        case 'ADD':
998                            break;
999
1000                        case 'REPLY':
1001                            $interation = ICAL_ACTION_REPLY;
1002                            break;
1003
1004                        case 'COUNTER':
1005                            $interation = ICAL_ACTION_SUGGESTION;
1006                            break;
1007
1008                        case 'DECLINECOUNTER':
1009                            $interation = ICAL_ACTION_NONE;
1010                            break;
1011
1012                        default:
1013                            $schedulable = self::_getSchedulable($uid);
1014
1015                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1016                                $interation = ICAL_ACTION_UPDATE;
1017                            else if ($schedulable)
1018                                $interation = ICAL_ACTION_NONE;
1019                            else // Importar evento
1020                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1021
1022                            break;
1023                    }
1024
1025                    $return[$uid] = $interation;
1026                    break;
1027                case 'VTODO':
1028                    switch ($method) {
1029                        case 'PUBLISH':
1030                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1031                            break;
1032
1033                        case 'REQUEST':
1034                            $schedulable = self::_getSchedulable($uid);
1035                           
1036                            if ($schedulable) { //Caso o evento exista
1037                                $isOrganizer = false;
1038                                $isParticipant = false;
1039
1040                                foreach ($schedulable['participants'] as $value)
1041                                    if ($value['user']['id'] == $params['owner']) {
1042                                        $isParticipant = true;
1043                                        if ($value['isOrganizer'])
1044                                            $isOrganizer = true;
1045
1046                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {   
1047                                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1048                                            break;
1049                                        }
1050                                    } else {
1051                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1052                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1053                                        else
1054                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1055                                    }
1056                                if (!$isParticipant){
1057                                      $interation = self::_checkParticipantByPermissions($schedulable);
1058                                    }
1059                            }else
1060                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1061                            break;
1062
1063                        case 'REFRESH':
1064                            break;
1065
1066                        case 'CANCEL':
1067                            $interation = ICAL_ACTION_DELETE;
1068                            break;
1069
1070                        case 'ADD':
1071                            break;
1072
1073                        case 'REPLY':
1074                            $interation = ICAL_ACTION_REPLY;
1075                            break;
1076
1077                        case 'COUNTER':
1078                            $interation = ICAL_ACTION_SUGGESTION;
1079                            break;
1080
1081                        case 'DECLINECOUNTER':
1082                            $interation = ICAL_ACTION_NONE;
1083                            break;
1084
1085                        default:
1086                            $schedulable = self::_getSchedulable($uid);
1087
1088                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1089                                $interation = ICAL_ACTION_UPDATE;
1090                            else if ($schedulable)
1091                                $interation = ICAL_ACTION_NONE;
1092                            else // Importar evento
1093                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1094
1095                            break;
1096                    }
1097
1098                    $return[$uid] = $interation;
1099                    break;
1100                case 'VTIMEZONE':
1101                break;
1102            }
1103        }
1104
1105        return $return;
1106    }
1107
1108    /* Helpers */
1109
1110    private static function _getTzOffset($rTz, $oTz = null, $time = 'now') {
1111        if ($oTz === null) {
1112            if (!is_string($oTz = date_default_timezone_get())) {
1113                return false; // A UTC timestamp was returned -- bail out!
1114            }
1115        }
1116        $origin_dtz = new DateTimeZone(self::nomalizeTZID($oTz));
1117        $remote_dtz = new DateTimeZone(self::nomalizeTZID($rTz));
1118        $origin_dt = new DateTime($time, $origin_dtz);
1119        $remote_dt = new DateTime("now", $remote_dtz);
1120
1121        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
1122
1123
1124        return $offset;
1125    }
1126
1127    private function _getStatus($id) {
1128        $a = array(
1129            STATUS_CONFIRMED => 'ACCEPTED',
1130            STATUS_CANCELLED => 'CANCELLED',
1131            STATUS_TENTATIVE => 'TENTATIVE',
1132            STATUS_UNANSWERED => 'NEEDS-ACTION',
1133            STATUS_DELEGATED => 'DELEGATED'
1134        );
1135
1136        return isset($a[$id]) ? $a[$id] : 'NEEDS-ACTION';
1137    }
1138
1139    public function decodeStatusTodo( $action )
1140    {
1141     $a = array(
1142        'NEED_ACTION' => STATUS_TODO_NEED_ACTION,
1143        'IN_PROGRESS' => STATUS_TODO_IN_PROGRESS  ,
1144        'COMPLETED' =>  STATUS_TODO_COMPLETED ,
1145        'CANCELLED'  => STATUS_TODO_CANCELLED
1146    );
1147
1148    return isset($a[$id]) ? $a[$id] : 'STATUS_TODO_NEED_ACTION';
1149   
1150    }
1151
1152
1153    private function _getStatusTodo($id) {
1154        $a = array(
1155            STATUS_TODO_NEED_ACTION => 'NEED_ACTION',
1156            STATUS_TODO_IN_PROGRESS => 'IN_PROGRESS',
1157            STATUS_TODO_COMPLETED => 'COMPLETED',
1158            STATUS_TODO_CANCELLED => 'CANCELLED'
1159        );
1160
1161    return isset($a[$id]) ? $a[$id] : 'NEED_ACTION';
1162    }
1163
1164    private static function _checkParticipantByPermissions($schedulable) {
1165
1166        $calendarIds = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=','isOwner','0'), array('=', 'user', Config::me("uidNumber")))));
1167
1168        if($calendarIds && isset($calendarIds[0])){
1169            $ids = array();
1170            foreach($calendarIds as $value)
1171                    array_push($ids, $value['calendar']);
1172
1173            $signaturesOfOwners = Controller::find(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('IN', 'calendar', $ids) , array('=','isOwner','1')), 'deepness' => 2 ));
1174           
1175            foreach($signaturesOfOwners as $value){
1176                if(self::_getParticipantByMail($value['user']['mail'], $schedulable['participants'])){
1177                    $eventoFromCalendar = Controller::read( array( 'concept' => 'calendarToSchedulable') , false, array('filter' => array('AND', array('=','schedulable',$schedulable['id']), array('=','calendar', $value['calendar']['id']))));
1178
1179                    return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => array($value['calendar']['id']) );
1180                }
1181            }   
1182        }
1183        return ICAL_ACTION_ORGANIZER_NONE;
1184    }
1185   
1186   
1187    private static function _getParticipantByMail($mail, &$participants) {
1188        if ($participants && $participants != '')
1189            foreach ($participants as $i => $v)
1190                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
1191                    return $v['id'];
1192        return false;
1193    }
1194
1195    static private function nomalizeTZID($TZID) {
1196        if (isset(self::$timezonesMap[$TZID]))
1197            return self::$timezonesMap[$TZID];
1198        else if (in_array($TZID, self::$suportedTimzones))
1199            return $TZID;
1200        else
1201            return date_default_timezone_get();
1202    }
1203
1204    static private function date2timestamp($datetime, $tz = null) {
1205        if (!isset($datetime['hour']))
1206            $datetime['hour'] = '0';
1207        if (!isset($datetime['min']))
1208            $datetime['min'] = '0';
1209        if (!isset($datetime['sec']))
1210            $datetime['sec'] = '0';
1211
1212        foreach ($datetime as $dkey => $dvalue)
1213            if ('tz' != $dkey)
1214                $datetime[$dkey] = (integer) $dvalue;
1215
1216        if ($tz)
1217            $datetime['tz'] = $tz;
1218
1219        $offset = ( isset($datetime['tz']) && ( '' < trim($datetime['tz']))) ? iCalUtilityFunctions::_tz2offset($datetime['tz']) : 0;
1220
1221        return gmmktime($datetime['hour'], $datetime['min'], ($datetime['sec'] + $offset), $datetime['month'], $datetime['day'], $datetime['year']);
1222    }
1223
1224    static private function _makeCOUNTER($schedulable, $component, $params) {
1225        $interation = array();
1226        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1227
1228        /* Data de Inicio */
1229        $startTime = $component->getProperty('dtstart', false, true);
1230
1231        /* Tiem zone do evento */
1232        if (isset($startTime['params']['TZID']))
1233            $schedulable['timezone'] = self::nomalizeTZID($startTime['params']['TZID']);
1234        else
1235            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1236
1237        $objTimezone = new DateTimeZone($schedulable['timezone']);
1238
1239        if ($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1240            $schedulable['allDay'] = 1;
1241            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1242        } 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 */
1243            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID'], '@' . self::date2timestamp($startTime['value'])) . '000';
1244            $schedulable['allDay'] = 0;
1245        } else {
1246            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1247            if (strpos($params['prodid'], 'Outlook') !== false) {
1248                //Se o ics veio em utc não aplicar horario de verão
1249                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1250                $sTime->setTimezone($objTimezone);
1251                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1252                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1253            }
1254        }
1255
1256        /* Data de Termino */
1257        $endTime = $component->getProperty('dtend', false, true);
1258
1259        if ($endTime['params']['VALUE'] === 'DATE')
1260            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1261        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 */
1262            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID'], '@' . self::date2timestamp($endTime['value'])) . '000';
1263        else {
1264            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1265            if (strpos($params['prodid'], 'Outlook') !== false) {
1266                //Se o ics veio em utc não aplicar horario de verão
1267                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1268                $eTime->setTimezone($objTimezone);
1269                if ($eTime->format('I'))
1270                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1271            }
1272        }
1273        unset($schedulable['participants']);
1274        $interation['schedulable://' . $eventID] = $schedulable;
1275
1276        return $interation;
1277    }
1278
1279        static private function _makeVEVENT($schedulable, $component, $params) {
1280        $interation = array();
1281        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1282
1283        /* Data de Inicio */
1284        $startTime = $component->getProperty('dtstart', false, true);
1285
1286        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1287
1288        /* Tiem zone do evento */
1289        if ($tzid){
1290            $tzid = self::nomalizeTZID($tzid);
1291            $schedulable['timezone'] = $tzid;
1292        }else
1293            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1294
1295        $objTimezone = new DateTimeZone($schedulable['timezone']);
1296
1297        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1298            $schedulable['allDay'] = 1;
1299            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1300        } 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 */
1301            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1302            $schedulable['allDay'] = 0;
1303        } else {
1304            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1305            if (strpos($params['prodid'], 'Outlook') !== false) {
1306                //Se o ics veio em utc não aplicar horario de verão
1307                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1308                $sTime->setTimezone($objTimezone);
1309                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1310                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1311            }
1312        }
1313
1314        /* Data de Termino */
1315        $endTime = $component->getProperty('dtend', false, true);
1316
1317        $tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
1318       
1319        if($tzid)
1320            $tzid = self::nomalizeTZID($tzid);
1321
1322        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
1323            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1324        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 */
1325            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($endTime['value'])) . '000';
1326        else {
1327            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1328            if (strpos($params['prodid'], 'Outlook') !== false) {
1329                //Se o ics veio em utc não aplicar horario de verão
1330                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1331                $eTime->setTimezone($objTimezone);
1332                if ($eTime->format('I'))
1333                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1334            }
1335        }
1336
1337
1338        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1339
1340        /* Definindo Description */
1341        if ($desc = $component->getProperty('description', false, false))
1342            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1343
1344        /* Definindo location */
1345        if ($location = $component->getProperty('location', false, false))
1346            $schedulable['location'] = mb_convert_encoding($location, 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1347
1348
1349        /* Definindo Class */
1350        $class = $component->getProperty('class', false, false);
1351        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1352            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1353        else if (!isset($schedulable['class']))
1354            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1355
1356        /* Definindo RRULE */
1357        if ($rrule = $component->getProperty('rrule', false, false)) {
1358            /* Gera um randon id para o contexto formater */
1359            $repeatID = mt_rand() . '3(Formatter)';
1360
1361            $repeat = array();
1362            $repeat['schedulable'] = $eventID;
1363            foreach ($rrule as $i => $v) {
1364                if (strtolower($i) == 'freq')
1365                    $repeat['frequency'] = $v;
1366                else if (strtolower($i) == 'until')
1367                    $repeat['endTime'] = $v;
1368                else
1369                    $repeat[strtolower($i)] = $v;
1370            }
1371
1372            $interation['repeat://' . $repeatID] = $repeat;
1373        }
1374
1375
1376        $schedulable['calendar'] = $params['calendar'];
1377
1378        $participantsInEvent = array();
1379
1380        //TODO: Participants com delegated nao estao sendo levados em conta
1381        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1382            $participant = array();
1383
1384            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1385
1386            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
1387            $participant['schedulable'] = $eventID;
1388
1389            if (isset($params['status']) && $mailUser == Config::me('mail'))
1390                $participant['status'] = $params['status'];
1391            else
1392                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1393
1394
1395            $participant['isOrganizer'] = '0';
1396
1397            /* Verifica se este usuario é um usuario interno do ldap */
1398            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1399
1400            $user = null;
1401            if ($intUser && count($intUser) > 0) {
1402                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1403                $participant['user'] = $intUser[0]['id'];
1404            } else {
1405                $participant['isExternal'] = 1;
1406                /* Gera um randon id para o contexto formater */
1407                $userID = mt_rand() . '4(Formatter)';
1408
1409                $user['mail'] = $mailUser;
1410                $user['isExternal'] = '1';
1411                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1412                $user['participants'] = array($participantID);
1413                $participant['user'] = $userID;
1414                $interation['user://' . $userID] = $user;
1415            }
1416
1417            $interation['participant://' . $participantID] = $participant;
1418            $schedulable['participants'][] = $participantID;
1419        };
1420
1421        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1422            $participant = array();
1423            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1424
1425            $participantID = mt_rand() . '2(Formatter)';
1426
1427            $participant['schedulable'] = $eventID;
1428            $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1429            $participant['isOrganizer'] = '1';
1430            $participant['acl'] = 'rowi';
1431
1432            /* Verifica se este usuario é um usuario interno do ldap */
1433            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1434
1435            $user = null;
1436            if ($intUser && count($intUser) > 0) {
1437                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1438                $participant['user'] = $intUser[0]['id'];
1439            } else {
1440                $participant['isExternal'] = 1;
1441                /* Gera um randon id para o contexto formater */
1442                $userID = mt_rand() . '4(Formatter)';
1443
1444                $user['mail'] = $mailUser;
1445                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1446                $user['participants'] = array($participantID);
1447                $user['isExternal'] = '1';
1448                $participant['user'] = $userID;
1449                $interation['user://' . $userID] = $user;
1450            }
1451
1452            $interation['participant://' . $participantID] = $participant;
1453            $schedulable['participants'][] = $participantID;
1454        } else if (!is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
1455            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
1456
1457            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
1458                $participantID = mt_rand() . '2(Formatter)';
1459
1460                $participant['schedulable'] = $eventID;
1461                $participant['status'] = STATUS_CONFIRMED;
1462                $participant['isOrganizer'] = '1';
1463                $participant['acl'] = 'rowi';
1464                $participant['isExternal'] = 0;
1465                $participant['user'] = $params['owner'];
1466                $interation['participant://' . $participantID] = $participant;
1467                $schedulable['participants'][] = $participantID;
1468            }
1469        }
1470       
1471        $alarms = array();
1472       
1473        /* Definindo ALARMES */
1474        while ($alarmComp = $component->getComponent('valarm'))
1475        {
1476                $alarm = array();
1477                $alarmID = mt_rand() . '6(Formatter)';
1478                $action =  $alarmComp->getProperty('action', false, true);
1479                $trygger = $alarmComp->getProperty('trigger', false, true);
1480                $alarm['type'] = self::decodeAlarmAction($action['value']);
1481
1482                 if(isset($trygger['value']['day']))
1483                {
1484                        $alarm['time'] = $trygger['value']['day'];
1485                        $alarm['unit'] = 'd';
1486                }
1487                else if(isset($trygger['value']['hour']))
1488                {
1489                        $alarm['time'] = $trygger['value']['hour'];
1490                        $alarm['unit'] = 'h';
1491                }
1492                else if(isset($trygger['value']['min']))
1493                {
1494                        $alarm['time'] = $trygger['value']['min'];
1495                        $alarm['unit'] = 'm';
1496                }
1497               
1498                foreach ($interation as $iint => &$vint)
1499                {
1500                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
1501                        {
1502                                $alarm['participant'] = str_replace('participant://', '', $iint);       
1503                                $vint['alarms'][] = $alarmID;
1504                        }
1505                }
1506                $alarm['schedulable'] = $eventID;
1507                               
1508                $interation['alarm://' . $alarmID ] = $alarm;
1509               
1510        }
1511       
1512       
1513        /* Definindo DTSTAMP */
1514        if ($dtstamp = self::_getTime($component, 'dtstamp'))
1515            $schedulable['dtstamp'] = $dtstamp;
1516
1517        /* Definindo TRANSP */
1518        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
1519            $schedulable['transparent'] = 1;
1520
1521        /* Definindo last_update */
1522        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
1523            $schedulable['lastUpdate'] = $lastUpdate;
1524
1525
1526        if ($sequence = $component->getProperty('SEQUENCE', false, false))
1527            $schedulable['sequence'] = $sequence;
1528
1529        if ($uid = $component->getProperty('uid', false, false))
1530            ;
1531        $schedulable['uid'] = $uid;
1532
1533        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
1534
1535            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
1536                'size' => strlen($attach['value']),
1537                'type' => self::_getContentType($attach['params']['X-FILENAME'])
1538            );
1539
1540            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
1541
1542            if (!is_array($ids)) {
1543                $attachCurrent['source'] = $attach['value'];
1544                //insere o anexo no banco e pega id para colcar no relacionamento                               
1545                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
1546            }else
1547                $idAttachment = array('id' => $ids[0]['id']);
1548
1549            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
1550            $calendarToAttachment['attachment'] = $idAttachment['id'];
1551            $calendarToAttachment['schedulable'] = $eventID;
1552            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
1553
1554            $schedulable['attachments'][] = $calendarToAttachmentId;
1555        }
1556
1557        $interation['schedulable://' . $eventID] = $schedulable;
1558
1559        return $interation;
1560    }
1561   
1562    static private function _makeVTODO($schedulable, $component, $params) {
1563        $interation = array();
1564        $todoID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1565
1566        /* Data de Inicio */
1567        $startTime = $component->getProperty('dtstart', false, true);
1568
1569        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1570
1571        /* Tiem zone do evento */
1572        if ($tzid){
1573            $tzid = self::nomalizeTZID($tzid);
1574            $schedulable['timezone'] = $tzid;
1575        }else
1576            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1577
1578        $objTimezone = new DateTimeZone($schedulable['timezone']);
1579
1580        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1581            $schedulable['allDay'] = 1;
1582            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1583        } 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 */
1584            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1585            $schedulable['allDay'] = 0;
1586        } else {
1587            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1588            if (strpos($params['prodid'], 'Outlook') !== false) {
1589                //Se o ics veio em utc não aplicar horario de verão
1590                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1591                $sTime->setTimezone($objTimezone);
1592                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1593                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1594            }
1595        }
1596
1597        /* Data de Termino */
1598        $endTime = $component->getProperty('dtend', false, true);
1599
1600        $tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
1601       
1602        if($tzid)
1603            $tzid = self::nomalizeTZID($tzid);
1604
1605        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
1606            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1607        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 */
1608            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($endTime['value'])) . '000';
1609        else {
1610            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1611            if (strpos($params['prodid'], 'Outlook') !== false) {
1612                //Se o ics veio em utc não aplicar horario de verão
1613                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1614                $eTime->setTimezone($objTimezone);
1615                if ($eTime->format('I'))
1616                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1617            }
1618        }
1619
1620        $schedulable['type'] = '2'; //type schedulable
1621        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1622
1623        /* Definindo Description */
1624        if ($desc = $component->getProperty('description', false, false))
1625            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1626
1627        /* Definindo Class */
1628        $class = $component->getProperty('class', false, false);
1629        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1630            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1631        else if (!isset($schedulable['class']))
1632            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1633
1634        $schedulable['calendar'] = $params['calendar'];
1635
1636        $participantsInTodo = array();
1637
1638        //TODO: Participants com delegated nao estao sendo levados em conta
1639        while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
1640            $participant = array();
1641
1642            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1643
1644            $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : mt_rand() . '2(Formatter)';
1645            $participant['schedulable'] = $eventID;
1646
1647            if (isset($params['status']) && $mailUser == Config::me('mail'))
1648                $participant['status'] = $params['status'];
1649            else
1650                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1651
1652
1653            $participant['isOrganizer'] = '0';
1654
1655            /* Verifica se este usuario é um usuario interno do ldap */
1656            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1657
1658            $user = null;
1659            if ($intUser && count($intUser) > 0) {
1660                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1661                $participant['user'] = $intUser[0]['id'];
1662            } else {
1663                $participant['isExternal'] = 1;
1664                /* Gera um randon id para o contexto formater */
1665                $userID = mt_rand() . '4(Formatter)';
1666
1667                $user['mail'] = $mailUser;
1668                $user['isExternal'] = '1';
1669                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1670                $user['participants'] = array($participantID);
1671                $participant['user'] = $userID;
1672                $interation['user://' . $userID] = $user;
1673            }
1674
1675            $interation['participant://' . $participantID] = $participant;
1676            $schedulable['participants'][] = $participantID;
1677        };
1678
1679        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
1680            $participant = array();
1681            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
1682
1683            $participantID = mt_rand() . '2(Formatter)';
1684
1685            $participant['schedulable'] = $eventID;
1686            $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
1687            $participant['isOrganizer'] = '1';
1688            $participant['acl'] = 'rowi';
1689
1690            /* Verifica se este usuario é um usuario interno do ldap */
1691            $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
1692
1693            $user = null;
1694            if ($intUser && count($intUser) > 0) {
1695                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
1696                $participant['user'] = $intUser[0]['id'];
1697            } else {
1698                $participant['isExternal'] = 1;
1699                /* Gera um randon id para o contexto formater */
1700                $userID = mt_rand() . '4(Formatter)';
1701
1702                $user['mail'] = $mailUser;
1703                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1704                $user['participants'] = array($participantID);
1705                $user['isExternal'] = '1';
1706                $participant['user'] = $userID;
1707                $interation['user://' . $userID] = $user;
1708            }
1709
1710            $interation['participant://' . $participantID] = $participant;
1711            $schedulable['participants'][] = $participantID;
1712            } else if (!isset($schedulable['participants']) || !is_array($schedulable['participants']) || count($schedulable['participants']) < 1) {//caso não tenha organizador o usuario se torna organizador
1713            $user = Controller::read(array('concept' => 'user', 'id' => $params['owner']), array('mail'));
1714
1715            if (!self::_getParticipantByMail($user['mail'], $schedulable['participants'])) {
1716                $participantID = mt_rand() . '2(Formatter)';
1717
1718                $participant['schedulable'] = $todoID;
1719                $participant['status'] = STATUS_CONFIRMED;
1720                $participant['isOrganizer'] = '1';
1721                $participant['acl'] = 'rowi';
1722                $participant['isExternal'] = 0;
1723                $participant['user'] = $params['owner'];
1724                $interation['participant://' . $participantID] = $participant;
1725                $schedulable['participants'][] = $participantID;
1726            }
1727        }
1728       
1729        $alarms = array();
1730       
1731        /* Definindo ALARMES */
1732        while ($alarmComp = $component->getComponent('valarm'))
1733        {
1734                $alarm = array();
1735                $alarmID = mt_rand() . '6(Formatter)';
1736                $action =  $alarmComp->getProperty('action', false, true);
1737                $trygger = $alarmComp->getProperty('trigger', false, true);
1738                $alarm['type'] = self::decodeAlarmAction($action['value']);
1739
1740                 if(isset($trygger['value']['day']))
1741                {
1742                        $alarm['time'] = $trygger['value']['day'];
1743                        $alarm['unit'] = 'd';
1744                }
1745                else if(isset($trygger['value']['hour']))
1746                {
1747                        $alarm['time'] = $trygger['value']['hour'];
1748                        $alarm['unit'] = 'h';
1749                }
1750                else if(isset($trygger['value']['min']))
1751                {
1752                        $alarm['time'] = $trygger['value']['min'];
1753                        $alarm['unit'] = 'm';
1754                }
1755               
1756                foreach ($interation as $iint => &$vint)
1757                {
1758                        if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
1759                        {
1760                                $alarm['participant'] = str_replace('participant://', '', $iint);       
1761                                $vint['alarms'][] = $alarmID;
1762                        }
1763                }
1764                $alarm['schedulable'] = $eventID;
1765                               
1766                $interation['alarm://' . $alarmID ] = $alarm;
1767               
1768        }
1769       
1770       
1771        /* Definindo DTSTAMP */
1772        if ($dtstamp = self::_getTime($component, 'dtstamp'))
1773            $schedulable['dtstamp'] = $dtstamp;
1774
1775        /* Definindo TRANSP */
1776        if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && strtoupper($tranp) == 'OPAQUE')
1777            $schedulable['transparent'] = 1;
1778
1779        /* Definindo last_update */
1780        if ($lastUpdate = self::_getTime($component, 'LAST-MODIFIED'))
1781            $schedulable['lastUpdate'] = $lastUpdate;
1782
1783
1784        if ($sequence = $component->getProperty('SEQUENCE', false, false))
1785            $schedulable['sequence'] = $sequence;
1786
1787        if ($uid = $component->getProperty('uid', false, false))
1788            ;
1789        $schedulable['uid'] = $uid;
1790
1791        while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
1792
1793            $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
1794                'size' => strlen($attach['value']),
1795                'type' => self::_getContentType($attach['params']['X-FILENAME'])
1796            );
1797
1798            $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
1799
1800            if (!is_array($ids)) {
1801                $attachCurrent['source'] = $attach['value'];
1802                //insere o anexo no banco e pega id para colcar no relacionamento                               
1803                $idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
1804            }else
1805                $idAttachment = array('id' => $ids[0]['id']);
1806
1807            $calendarToAttachmentId = mt_rand() . '2(Formatter)';
1808            $calendarToAttachment['attachment'] = $idAttachment['id'];
1809            $calendarToAttachment['schedulable'] = $eventID;
1810            $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
1811
1812            $schedulable['attachments'][] = $calendarToAttachmentId;
1813        }
1814
1815        $interation['schedulable://' . $todoID] = $schedulable;
1816
1817        return $interation;
1818    }
1819
1820    static private function _getSchedulable($uid) {
1821        $schedulable = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'uid', $uid), 'deepness' => 2));
1822        return (isset($schedulable[0])) ? $schedulable[0] : false;
1823    }
1824
1825    static private function _existInMyCalendars($id, $owner) {
1826        $sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'isOwner', '1'), array('=', 'user', $owner))));
1827        $calendars = array();
1828        foreach ($sig as $val)
1829            $calendars[] = $val['calendar'];
1830
1831        $return = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('AND', array('IN', 'calendar', $calendars), array('=', 'schedulable', $id))));
1832
1833        return (isset($return[0])) ? $return[0]['calendar'] : false;
1834    }
1835
1836    static private function _getTime(&$component, $property) {
1837        if ($date = $component->getProperty($property, false, true))
1838            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';
1839
1840        return false;
1841    }
1842
1843    static private function _getContentType($fileName) {
1844        $strFileType = strtolower(substr($fileName, strrpos($fileName, '.')));
1845
1846        switch ($strFileType) {
1847            case ".asf": return "video/x-ms-asf";
1848            case ".avi": return "video/avi";
1849            case ".doc": return "application/msword";
1850            case ".zip": return "application/zip";
1851            case ".xls": return "application/vnd.ms-excel";
1852            case ".gif": return "image/gif";
1853            case ".bmp": return "image/bmp";
1854            case ".jpeg":
1855            case ".jpg": return "image/jpeg";
1856            case ".wav": return "audio/wav";
1857            case ".mp3": return "audio/mpeg3";
1858            case ".mpeg":
1859            case ".mpg": return "video/mpeg";
1860            case ".rtf": return "application/rtf";
1861            case ".html":
1862            case ".htm": return "text/html";
1863            case ".xml": return "text/xml";
1864            case ".xsl": return "text/xsl";
1865            case ".css": return "text/css";
1866            case ".php": return "text/php";
1867            case ".asp": return "text/asp";
1868            case ".pdf": return "application/pdf";
1869            case ".png": return "image/png";
1870            case ".txt": return "text/plain";
1871            case ".log": return "text/plain";
1872            case ".wmv": return "video/x-ms-wmv";
1873            case ".sxc": return "application/vnd.sun.xml.calc";
1874            case ".odt": return "application/vnd.oasis.opendocument.text";
1875            case ".stc": return "application/vnd.sun.xml.calc.template";
1876            case ".sxd": return "application/vnd.sun.xml.draw";
1877            case ".std": return "application/vnd.sun.xml.draw.template";
1878            case ".sxi": return "application/vnd.sun.xml.impress";
1879            case ".sti": return "application/vnd.sun.xml.impress.template";
1880            case ".sxm": return "application/vnd.sun.xml.math";
1881            case ".sxw": return "application/vnd.sun.xml.writer";
1882            case ".sxq": return "application/vnd.sun.xml.writer.global";
1883            case ".stw": return "application/vnd.sun.xml.writer.template";
1884            case ".pps": return "application/vnd.ms-powerpoint";
1885            case ".odt": return "application/vnd.oasis.opendocument.text";
1886            case ".ott": return "application/vnd.oasis.opendocument.text-template";
1887            case ".oth": return "application/vnd.oasis.opendocument.text-web";
1888            case ".odm": return "application/vnd.oasis.opendocument.text-master";
1889            case ".odg": return "application/vnd.oasis.opendocument.graphics";
1890            case ".otg": return "application/vnd.oasis.opendocument.graphics-template";
1891            case ".odp": return "application/vnd.oasis.opendocument.presentation";
1892            case ".otp": return "application/vnd.oasis.opendocument.presentation-template";
1893            case ".ods": return "application/vnd.oasis.opendocument.spreadsheet";
1894            case ".ots": return "application/vnd.oasis.opendocument.spreadsheet-template";
1895            case ".odc": return "application/vnd.oasis.opendocument.chart";
1896            case ".odf": return "application/vnd.oasis.opendocument.formula";
1897            case ".odi": return "application/vnd.oasis.opendocument.image";
1898            case ".ndl": return "application/vnd.lotus-notes";
1899            case ".eml": return "text/plain";
1900            case ".ps" : return "application/postscript";
1901            default : return "application/octet-stream";
1902        }
1903    }
1904   
1905    public function codeAlarmAction( $action )
1906    {
1907        switch ($action)
1908        {
1909                case ALARM_MAIL :
1910                                return  'EMAIL';
1911                                break;
1912                case ALARM_ALERT :
1913                                return  'DISPLAY';
1914                                break;
1915                case 'mail' :
1916                                        return  'EMAIL';
1917                                        break;
1918                case 'alert'  :
1919                                        return  'DISPLAY';
1920                                        break;
1921        }
1922       
1923    }
1924   
1925    public function decodeAlarmAction( $action )
1926    {
1927        switch ( $action )
1928        {
1929                case 'EMAIL'  :
1930                        return  'mail';
1931                        break;
1932                case 'DISPLAY' :
1933                        return  'alert';
1934                        break;
1935
1936        }
1937   
1938    }
1939
1940}
1941
1942?>
Note: See TracBrowser for help on using the repository browser.