source: branches/2.4/prototype/services/iCal.php @ 7594

Revision 7594, 109.8 KB checked in by douglas, 11 years ago (diff)

Ticket #3143 - problema ao copiar evento ou tarefa no modulo expressocalendar

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