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

Revision 7660, 110.1 KB checked in by cristiano, 11 years ago (diff)

Ticket #3239 - Inconsistência na importação de eventos com repetição

Line 
1<?php
2
3//require_once ROOTPATH . '/plugins/icalcreator/iCalUtilityFunctions.class.php';
4require_once ROOTPATH . '/plugins/icalcreator/iCalcreator.class.php';
5require_once ROOTPATH . '/modules/calendar/constants.php';
6
7use prototype\api\Config as Config;
8
9//TODO:Timeout request
10set_time_limit(600);
11
12class iCal implements Formatter {
13
14    static $timezonesMap = array('(GMT-12.00) International Date Line West' => 'Etc/GMT+12', '(GMT-11.00) Midway Island / Samoa' => 'Pacific/Midway', '(GMT-10.00) Hawaii' => 'Pacific/Honolulu', '(GMT-09.00) Alaska' => 'America/Anchorage', '(GMT-08.00) Pacific Time (US & Canada) / Tijuana' => 'America/Los_Angeles', '(GMT-08.00) Tijuana / Baja California' => 'America/Tijuana', '(GMT-07.00) Arizona' => 'America/Phoenix', '(GMT-07.00) Chihuahua / La Paz / Mazatlan - Old' => 'America/Chihuahua', '(GMT-07.00) Mountain Time (US & Canada)' => 'America/Denver', '(GMT-06.00) Central America' => 'America/Guatemala', '(GMT-06.00) Central Time (US & Canada)' => 'America/Chicago', '(GMT-06.00) Guadalajara / Mexico City / Monterrey - Old' => 'America/Mexico_City', '(GMT-06.00) Saskatchewan' => 'America/Regina', '(GMT-05.00) Bogota / Lima / Quito' => 'America/Bogota', '(GMT-05.00) Eastern Time (US & Canada)' => 'America/New_York', '(GMT-05.00) Indiana (East)' => 'America/Indiana/Indianapolis', '(GMT-04.30) Caracas' => 'America/Caracas', '(GMT-04.00) Atlantic Time (Canada)' => 'America/Halifax', '(GMT-04.00) Georgetown' => 'America/Guyana', '(GMT-04.00) Caracas / La Paz' => 'America/La_Paz', '(GMT-04.00) Manaus' => 'America/Manaus', '(GMT-04.00) Santiago' => 'America/Santiago', '(GMT-03.30) Newfoundland' => 'America/St_Johns', '(GMT-03.00) Brasilia' => 'America/Sao_Paulo', 'GMT -0300 (Standard) / GMT -0200 (Daylight)' => 'America/Sao_Paulo', '(GMT-03.00) Buenos Aires / Georgetown' => 'America/Argentina/Buenos_Aires', '(GMT-03.00) Greenland' => 'America/Godthab', '(GMT-03.00) Montevideo' => 'America/Montevideo', '(GMT-02.00) Mid-Atlantic' => 'Atlantic/South_Georgia', '(GMT-01.00) Azores' => 'Atlantic/Azores', '(GMT-01.00) Cape Verde Is.' => 'Atlantic/Cape_Verde', '(GMT) Casablanca' => 'Africa/Casablanca', '(GMT) Greenwich Mean Time - Dublin / Edinburgh / Lisbon / London' => 'Europe/London', '(GMT) Casablanca / Monrovia' => 'Africa/Monrovia', '(GMT+01.00) Amsterdam / Berlin / Bern / Rome / Stockholm / Vienna' => 'Europe/Berlin', '(GMT+01.00) Belgrade / Bratislava / Budapest / Ljubljana / Prague' => 'Europe/Belgrade', '(GMT+01.00) Brussels / Copenhagen / Madrid / Paris' => 'Europe/Brussels', '(GMT+01.00) Sarajevo / Skopje / Warsaw / Zagreb' => 'Europe/Warsaw', '(GMT+01.00) West Central Africa' => 'Africa/Algiers', '(GMT+02.00) Windhoek' => 'Africa/Windhoek', '(GMT+02.00) Amman' => 'Asia/Amman', '(GMT+02.00) Bucharest' => 'Europe/Athens', '(GMT+02.00) Beirut' => 'Asia/Beirut', '(GMT+02.00) Cairo' => 'Africa/Cairo', '(GMT+02.00) Harare / Pretoria' => 'Africa/Harare', '(GMT+02.00) Helsinki / Kyiv / Riga / Sofia / Tallinn / Vilnius' => 'Europe/Helsinki', '(GMT+02.00) Jerusalem' => 'Asia/Jerusalem', '(GMT+02.00) Minsk' => 'Europe/Minsk', '(GMT+03.00) Baghdad' => 'Asia/Baghdad', '(GMT+03.00) Kuwait / Riyadh' => 'Asia/Kuwait', '(GMT+03.00) Moscow / St. Petersburg / Volgograd' => 'Europe/Moscow', '(GMT+03.00) Nairobi' => 'Africa/Nairobi', '(GMT+04.00) Caucasus Standard Time' => 'Asia/Tbilisi', '(GMT+03.30) Tehran' => 'Asia/Tehran', '(GMT+04.00) Abu Dhabi / Muscat' => 'Asia/Muscat', '(GMT+04.00) Baku / Tbilisi / Yerevan' => 'Asia/Baku', '(GMT+04.00) Yerevan' => 'Asia/Yerevan', '(GMT+04.30) Kabul' => 'Asia/Kabul', '(GMT+05.00) Ekaterinburg' => 'Asia/Yekaterinburg', '(GMT+05.00) Islamabad / Karachi / Tashkent' => 'Asia/Karachi', '(GMT+05.00) Tashkent' => 'Asia/Tashkent', '(GMT+05.30) Chennai / Kolkata / Mumbai / New Delhi' => 'Asia/Kolkata', '(GMT+06.00) Sri Jayawardenepura' => 'Asia/Colombo', '(GMT+05.45) Kathmandu' => 'Asia/Katmandu', '(GMT+06.00) Almaty / Novosibirsk' => 'Asia/Novosibirsk', '(GMT+06.00) Astana / Dhaka' => 'Asia/Dhaka', '(GMT+06.30) Rangoon' => 'Asia/Rangoon', '(GMT+07.00) Bangkok / Hanoi / Jakarta' => 'Asia/Bangkok', '(GMT+07.00) Krasnoyarsk' => 'Asia/Krasnoyarsk', '(GMT+08.00) Beijing / Chongqing / Hong Kong / Urumqi' => 'Asia/Hong_Kong', '(GMT+08.00) Irkutsk / Ulaan Bataar' => 'Asia/Irkutsk', '(GMT+08.00) Kuala Lumpur / Singapore' => 'Asia/Kuala_Lumpur', '(GMT+08.00) Perth' => 'Australia/Perth', '(GMT+08.00) Taipei' => 'Asia/Taipei', '(GMT+09.00) Osaka / Sapporo / Tokyo' => 'Asia/Tokyo', '(GMT+09.00) Seoul' => 'Asia/Seoul', '(GMT+09.00) Yakutsk' => 'Asia/Yakutsk', '(GMT+09.30) Adelaide' => 'Australia/Adelaide', '(GMT+09.30) Darwin' => 'Australia/Darwin', '(GMT+10.00) Brisbane' => 'Australia/Brisbane', '(GMT+10.00) Canberra / Melbourne / Sydney' => 'Australia/Sydney', '(GMT+10.00) Guam / Port Moresby' => 'Pacific/Guam', '(GMT+10.00) Hobart' => 'Australia/Hobart', '(GMT+10.00) Vladivostok' => 'Asia/Vladivostok', '(GMT+11.00) Magadan / Solomon Is. / New Caledonia' => 'Asia/Magadan', '(GMT+12.00) Auckland / Wellington' => 'Pacific/Auckland', '(GMT+12.00) Fiji / Kamchatka / Marshall Is.' => 'Pacific/Fiji', '(GMT+13.00) Nuku\'alofa' => 'Pacific/Tongatapu', 'E. South America Standard Time' => 'America/Sao_Paulo', 'E. South America' => 'America/Sao_Paulo');
15//    static $timezonesOutlookID = array('Europe/London' => '1' ,'Europe/Brussels' => '3' ,'Europe/Berlin' => '4' ,'America/New_York' => '5' ,'Europe/Belgrade' => '6' ,'Europe/Minsk' => '7' ,'America/Sao_Paulo' => '8' ,'America/Halifax' => '9' ,'America/New_York' => '10' ,'America/Chicago' => '11' ,'America/Denver' => '12' ,'America/Los_Angeles' => '13' ,'America/Anchorage' => '14' ,'Pacific/Honolulu' => '15' ,'Pacific/Midway' => '16' ,'Pacific/Auckland' => '17' ,'Australia/Brisbane' => '18' ,'Australia/Adelaide' => '19' ,'Asia/Tokyo' => '20' ,'Asia/Hong_Kong' => '21' ,'Asia/Bangkok' => '22' ,'Asia/Kolkata' => '23' ,'Asia/Muscat' => '24' ,'Asia/Tehran' => '25' ,'Asia/Baghdad' => '26' ,'Asia/Jerusalem' => '27' ,'America/St_Johns' => '28' ,'Atlantic/Azores' => '29' ,'Atlantic/South_Georgia' => '30' ,'Africa/Casablanca' => '31' ,'America/La_Paz' => '33' ,'America/Indiana/Indianapolis' => '34' ,'America/Bogota' => '35' ,'America/Regina' => '36' ,'America/Mexico_City' => '37' ,'America/Phoenix' => '38' ,'Etc/GMT+12' => '39' ,'Pacific/Fiji' => '40' ,'Asia/Magadan' => '41' ,'Australia/Hobart' => '42' ,'Pacific/Guam' => '43' ,'Australia/Darwin' => '44' ,'Asia/Hong_Kong' => '45' ,'Asia/Novosibirsk' => '46' ,'Asia/Kabul' => '48' ,'Africa/Cairo' => '49' ,'Africa/Harare' => '50' ,'Europe/Moscow' => '51' ,'Australia/Sydney' => '52' ,'Australia/Sydney' => '53' ,'Australia/Adelaide' => '54' ,'Australia/Hobart' => '55' ,'America/Santiago' => '56' ,'Australia/Pert' => '57' ,'America/Tijuana' => '59' ,'Asia/Tbilisi' => '60' ,'Australia/Sydney' => '61' ,'America/Caracas' => '62' ,'Asia/Amman' => '63' ,'Asia/Baku' => '64' ,'Asia/Yerevan' => '65' ,'Europe/Moscow' => '66' ,'America/Argentina/Buenos_Aires' => '67' ,'America/Montevideo' => '72'); 
16    static $suportedTimzones = array('Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville', 'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Lome', 'Africa/Luanda', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Malabo', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Africa/Mogadishu', 'Africa/Monrovia', 'Africa/Nairobi', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Porto-Novo', 'Africa/Sao_Tome', 'Africa/Timbuktu', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Anguilla', 'America/Antigua', 'America/Araguaina', 'America/Argentina/Buenos_Aires', 'America/Argentina/Catamarca', 'America/Argentina/ComodRivadavia', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/La_Rioja', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Aruba', 'America/Asuncion', 'America/Atikokan', 'America/Atka', 'America/Bahia', 'America/Barbados', 'America/Belem', 'America/Belize', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Bogota', 'America/Boise', 'America/Buenos_Aires', 'America/Cambridge_Bay', 'America/Campo_Grande', 'America/Cancun', 'America/Caracas', 'America/Catamarca', 'America/Cayenne', 'America/Cayman', 'America/Chicago', 'America/Chihuahua', 'America/Coral_Harbour', 'America/Cordoba', 'America/Costa_Rica', 'America/Cuiaba', 'America/Curacao', 'America/Danmarkshavn', 'America/Dawson_Creek', 'America/Dawson', 'America/Denver', 'America/Detroit', 'America/Dominica', 'America/Edmonton', 'America/Eirunepe', 'America/El_Salvador', 'America/Ensenada', 'America/Fort_Wayne', 'America/Fortaleza', 'America/Glace_Bay', 'America/Godthab', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Indiana/Indianapolis', 'America/Indiana/Knox', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indianapolis', 'America/Inuvik', 'America/Iqaluit', 'America/Jamaica', 'America/Jujuy', 'America/Juneau', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Knox_IN', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Louisville', 'America/Maceio', 'America/Managua', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Matamoros', 'America/Mazatlan', 'America/Mendoza', 'America/Menominee', 'America/Merida', 'America/Mexico_City', 'America/Miquelon', 'America/Moncton', 'America/Monterrey', 'America/Montevideo', 'America/Montreal', 'America/Montserrat', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Nome', 'America/Noronha', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Ojinaga', 'America/Panama', 'America/Pangnirtung', 'America/Paramaribo', 'America/Phoenix', 'America/Port_of_Spain', 'America/Port-au-Prince', 'America/Porto_Acre', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Recife', 'America/Regina', 'America/Resolute', 'America/Rio_Branco', 'America/Rosario', 'America/Santa_Isabel', 'America/Santarem', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/Shiprock', 'America/St_Barthelemy', 'America/St_Johns', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Swift_Current', 'America/Tegucigalpa', 'America/Thule', 'America/Thunder_Bay', 'America/Tijuana', 'America/Toronto', 'America/Tortola', 'America/Vancouver', 'America/Virgin', 'America/Whitehorse', 'America/Winnipeg', 'America/Yakutat', 'America/Yellowknife', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Antarctica/McMurdo', 'Antarctica/Palmer', 'Antarctica/Rothera', 'Antarctica/South_Pole', 'Antarctica/Syowa', 'Antarctica/Vostok', 'Arctic/Longyearbyen', 'Asia/Aden', 'Asia/Almaty', 'Asia/Amman', 'Asia/Anadyr', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Ashkhabad', 'Asia/Baghdad', 'Asia/Bahrain', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Calcutta', 'Asia/Choibalsan', 'Asia/Chongqing', 'Asia/Chungking', 'Asia/Colombo', 'Asia/Dacca', 'Asia/Damascus', 'Asia/Dhaka', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Gaza', 'Asia/Harbin', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Asia/Istanbul', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Kashgar', 'Asia/Kathmandu', 'Asia/Katmandu', 'Asia/Kolkata', 'Asia/Krasnoyarsk', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Kuwait', 'Asia/Macao', 'Asia/Macau', 'Asia/Magadan', 'Asia/Makassar', 'Asia/Manila', 'Asia/Muscat', 'Asia/Nicosia', 'Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Oral', 'Asia/Phnom_Penh', 'Asia/Pontianak', 'Asia/Pyongyang', 'Asia/Qatar', 'Asia/Qyzylorda', 'Asia/Rangoon', 'Asia/Riyadh', 'Asia/Saigon', 'Asia/Sakhalin', 'Asia/Samarkand', 'Asia/Seoul', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Tel_Aviv', 'Asia/Thimbu', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Ujung_Pandang', 'Asia/Ulaanbaatar', 'Asia/Ulan_Bator', 'Asia/Urumqi', 'Asia/Vientiane', 'Asia/Vladivostok', 'Asia/Yakutsk', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faeroe', 'Atlantic/Faroe', 'Atlantic/Jan_Mayen', 'Atlantic/Madeira', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/St_Helena', 'Atlantic/Stanley', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Broken_Hill', 'Australia/Canberra', 'Australia/Currie', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Hobart', 'Australia/LHI', 'Australia/Lindeman', 'Australia/Lord_Howe', 'Australia/Melbourne', 'Australia/NSW', 'Australia/North', 'Australia/Perth', 'Australia/Queensland', 'Australia/South', 'Australia/Sydney', 'Australia/Tasmania', 'Australia/Victoria', 'Australia/West', 'Australia/Yancowinna', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Athens', 'Europe/Belfast', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Bratislava', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Dublin', 'Europe/Gibraltar', 'Europe/Guernsey', 'Europe/Helsinki', 'Europe/Isle_of_Man', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Lisbon', 'Europe/Ljubljana', 'Europe/London', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Mariehamn', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Nicosia', 'Europe/Oslo', 'Europe/Paris', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/San_Marino', 'Europe/Sarajevo', 'Europe/Simferopol', 'Europe/Skopje', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Tiraspol', 'Europe/Uzhgorod', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zagreb', 'Europe/Zaporozhye', 'Europe/Zurich', 'Indian/Antananarivo', 'Indian/Chagos', 'Indian/Christmas', 'Indian/Cocos', 'Indian/Comoro', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Mayotte', 'Indian/Reunion', 'Pacific/Apia', 'Pacific/Auckland', 'Pacific/Chatham', 'Pacific/Easter', 'Pacific/Efate', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Funafuti', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Johnston', 'Pacific/Kiritimati', 'Pacific/Kosrae', 'Pacific/Kwajalein', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Midway', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pago_Pago', 'Pacific/Palau', 'Pacific/Pitcairn', 'Pacific/Ponape', 'Pacific/Port_Moresby', 'Pacific/Rarotonga', 'Pacific/Saipan', 'Pacific/Samoa', 'Pacific/Tahiti', 'Pacific/Tarawa', 'Pacific/Tongatapu', 'Pacific/Truk', 'Pacific/Wake', 'Pacific/Wallis', 'Pacific/Yap', 'UTC');
17
18    public function format($data, $params = false)
19    {
20                $timezones = array_flip(self::$timezonesMap);
21                $sytemTimezone = (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo';
22                $params['defaultTZI'] = self::nomalizeTZID((isset($params['defaultTZI']) && $params['defaultTZI'] != 'null') ? $params['defaultTZI'] : $sytemTimezone );
23                $params['X-WR-TIMEZONE'] = isset($timezones[$params['defaultTZI']]) ? $timezones[$params['defaultTZI']] : $params['defaultTZI'];
24               
25                return (isset($params['compatible']) && $params['compatible']) ?
26                                        array('ical' => $this->createIcal($data, $params) , 'compatible' => $this->createCompatibleIcal($data, $params)) :
27                                        $this->createIcal($data, $params);
28
29    }
30
31    protected function createIcal($data, $params = false )
32    {
33        $ical = new vcalendar();
34                $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
35
36                /*
37                 * Seta propiedades obrigatorias para alguns softwares (Outlook)
38                 */
39                $ical->setProperty('x-wr-calname', 'Calendar Expresso');
40                $ical->setProperty('X-WR-CALDESC', 'Calendar Expresso');
41                $ical->setProperty('X-WR-TIMEZONE', $params['X-WR-TIMEZONE']);
42
43                foreach ($data as $i => $v) {
44
45                    switch ($v['type']) {
46                        case EVENT_ID:
47                            $vevent = $ical->newComponent('vevent');
48
49                            $vevent->setProperty('summary', $v['summary']);
50                            $vevent->setProperty('description', isset($v['description']) ? $v['description'] : '');
51                            $vevent->setProperty('location', $v['location']);
52                            $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
53
54                            $timezone = new DateTimeZone('UTC');
55                            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
56                            $apTimezoneOBJ = new DateTimeZone($apTimezone);
57
58                            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
59                            $sTime->setTimezone($apTimezoneOBJ);
60
61                $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
62                $eTime->setTimezone($apTimezoneOBJ);
63
64                            if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' ))
65                                    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
66                           
67
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('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
79                    $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
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                $timezoneDayligth = Controller::read(array('concept' => 'timezones'), null, array('filter' => array('=', 'tzid', $apTimezone)));
116
117                if(!empty( $timezoneDayligth ) && count( $timezoneDayligth ) > 0){
118
119                    if(array_key_exists(0, $timezoneDayligth))
120                        $timezoneDayligth = $timezoneDayligth[0];
121
122                    date_default_timezone_set('UTC');
123
124                    require_once ROOTPATH . '/plugins/when/When.php';
125
126                    $r = new When();
127
128                    $start = new DateTime('1970-01-01 '.$timezoneDayligth['standardDtstart']);
129
130                    $r = new When();
131                    $r->recur($start, $timezoneDayligth['standardFrequency'])
132                        ->until($start->modify('+1 years'))
133                        ->bymonth(array( $timezoneDayligth['standardBymonth'] ))
134                        ->byday(array(  $timezoneDayligth['daylightByday'] ));
135
136                   $date = $r->next();
137
138                    $timezone = $ical->newComponent('vtimezone');
139                    $timezone->setProperty('tzid',$apTimezone );
140
141                    $standard  = $timezone->newComponent( "standard" );
142                    $standard->setProperty( "tzoffsetfrom", $timezoneDayligth['standardFrom'] );
143                    $standard->setProperty( "tzoffsetto", $timezoneDayligth['standardTo'] );
144
145
146                    $standard->setProperty( "dtstart", $date->format(DATE_RFC822), array("VALUE" => "DATE") );
147
148                    $rrule = array(
149                        'FREQ' => $timezoneDayligth['standardFrequency'],
150                        'BYMONTH' =>  $timezoneDayligth['standardBymonth'],
151                        'BYday' => array(preg_replace("/[^0-9]/", "", $timezoneDayligth['standardByday']),  "DAY" => preg_replace("/[^a-zA-Z\s]/", "", $timezoneDayligth['standardByday']))
152                    );
153
154                    $standard->setProperty('rrule', $rrule);
155
156                    $daylight  = $timezone->newComponent( "daylight" );
157
158                    $daylight->setProperty( "tzoffsetfrom", $timezoneDayligth['daylightFrom'] );
159                    $daylight->setProperty( "tzoffsetto", $timezoneDayligth['daylightTo'] );
160
161
162                    $start = new DateTime('1970-01-01 '.$timezoneDayligth['daylightDtstart']);
163
164                    $r->recur($start, $timezoneDayligth['daylightFrequency'])
165                        ->until($start->modify('+1 years'))
166                        ->bymonth(array( $timezoneDayligth['daylightBymonth'] ))
167                        ->byday(array(  $timezoneDayligth['daylightByday'] ));
168
169                    $date = $r->next();
170
171                    $daylight->setProperty( "dtstart", $date->format(DATE_RFC822), array("VALUE" => "DATE") );
172
173                    $rrule = array(
174                        'FREQ' => $timezoneDayligth['daylightFrequency'],
175                        'BYMONTH' =>  $timezoneDayligth['daylightBymonth'],
176                        'BYday' => array(preg_replace("/[^0-9]/", "", $timezoneDayligth['daylightByday']),  "DAY" => preg_replace("/[^a-zA-Z\s]/", "", $timezoneDayligth['daylightByday']))
177                    );
178
179                    $daylight->setProperty('rrule', $rrule);
180                }
181
182                            break;
183            case TODO_ID:
184
185                $todo = $ical->newComponent('todo');
186
187                $todo->setProperty('summary', $v['summary']);
188                $todo->setProperty('description', isset($v['description']) ? $v['description'] : '');
189                $todo->setProperty('priority', $v['priority']);
190                $todo->setProperty('percent-complete', $v['percentage']);
191                $todo->setProperty('status', $this->_getStatusTodo($v['status']));
192
193                $timezone = new DateTimeZone('UTC');
194                $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
195                $apTimezoneOBJ = new DateTimeZone($apTimezone);
196
197                $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
198                $sTime->setTimezone($apTimezoneOBJ);
199                $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
200                $eTime->setTimezone($apTimezoneOBJ);
201
202                if (isset($v['allDay']) && $v['allDay'] == 1) {
203                    $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
204                    $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
205                    //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
206                } else {
207                    $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
208                    $todo->setProperty('dtend', $eTime->format(DATE_RFC822), array('TZID' => $apTimezone));
209                    //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
210                }
211
212                if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
213                    $dueTime = new DateTime('@' . (int) ($v['due'] / 1000), $timezone);
214                    $dueTime->setTimezone($apTimezoneOBJ);
215
216                    $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
217                    $todo->setProperty('dueTime', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
218                }               
219                       
220                if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
221                    $participants = $v['participants'];
222                else
223                    $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
224               
225                if (is_array($participants) && count($participants) > 0)
226                    foreach ($participants as $ii => $vv) {
227                   
228                        if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
229                        {
230                            if ($vv['isExternal'] == 1)
231                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
232                            else
233                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
234                        }
235                   
236                        if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
237                        {
238                            $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']))));
239                            if(is_array($alarms))
240                                self::createAlarms($alarms, $todo);
241                        }
242                   
243                    }
244
245                if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
246                    $this->createAttendee($v['participants'], $todo);
247
248                if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
249                    $this->createAttachment($v['attachments'], $todo);
250
251                $todo->setProperty('uid', $v['uid']); 
252               
253                break;
254                        default:
255                            break;
256                    }
257                }
258                return $ical->createCalendar();
259    }
260
261    protected function createCompatibleIcal($data, $params = false )
262    {
263        $ical = new vcalendar();
264                $ical->setProperty('method', isset($params['method']) ? $params['method'] : 'PUBLISH' );
265
266                /*
267                 * Seta propiedades obrigatorias para alguns softwares (Outlook)
268                 */
269                $ical->setProperty('x-wr-calname', 'Calendar Expresso');
270                $ical->setProperty('X-WR-CALDESC', 'Calendar Expresso');
271                $ical->setProperty('X-WR-TIMEZONE', $params['X-WR-TIMEZONE']);
272
273                foreach ($data as $i => $v) {
274
275                    switch ($v['type']) {
276                        case EVENT_ID:
277                            $vevent = $ical->newComponent('vevent');
278
279                            $vevent->setProperty('summary', $v['summary']);
280                            $vevent->setProperty('description', isset($v['description']) ? $v['description'] : '');
281                            $vevent->setProperty('location', $v['location']);
282                            $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
283
284                            $timezone = new DateTimeZone('UTC');
285                            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
286                            $eTime = new DateTime('@' . (int) ($v['endTime'] / 1000), $timezone);
287
288                            if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' ))
289                                    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
290
291                            if (isset($v['allDay']) && $v['allDay'] == 1) {
292                                $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
293                                $vevent->setProperty('dtend', $eTime->format(DATE_RFC822), array("VALUE" => "DATE"));
294                                $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
295                            } else {
296                                $vevent->setProperty('dtstart', $sTime->format(DATE_RFC822));
297                                $vevent->setProperty('dtend', $eTime->format(DATE_RFC822));
298                                $vevent->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
299                            }
300                                           
301                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
302                                $participants = $v['participants'];
303                            else
304                                        $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
305                           
306                                if (is_array($participants) && count($participants) > 0)
307                                        foreach ($participants as $ii => $vv) {
308                                       
309                                                if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
310                                                {
311                                                        if ($vv['isExternal'] == 1)
312                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
313                                                        else
314                                                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
315                                                }
316                                       
317                                                if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
318                                                {
319                                                        $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']))));
320                                                        if(is_array($alarms))
321                                                                self::createAlarms($alarms, $vevent);
322                                                }
323                                       
324                                        }
325                           
326
327                            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
328                                        $this->createAttendee($v['participants'], $vevent);
329
330                            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
331                                        $this->createAttachment($v['attachments'], $vevent);
332
333                            $vevent->setProperty('uid', $v['uid']); 
334                           
335                            break;
336
337                        default:
338                            break;
339                       
340        case TODO_ID:
341
342            $todo = $ical->newComponent('todo');
343
344            $todo->setProperty('summary', $v['summary']);
345            $todo->setProperty('description', isset($v['description']) ? $v['description'] : '');
346            $todo->setProperty('priority', $v['priority']);
347            $todo->setProperty('percent-complete', $v['percentage']);
348            $todo->setProperty('status', $this->_getStatusTodo($v['status']));
349
350            $timezone = new DateTimeZone('UTC');
351            $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
352            $apTimezoneOBJ = new DateTimeZone($apTimezone);
353
354            $sTime = new DateTime('@' . (int) ($v['startTime'] / 1000), $timezone);
355            $sTime->setTimezone($apTimezoneOBJ);
356
357            if (isset($v['allDay']) && $v['allDay'] == 1) {
358                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
359                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
360            } else {
361                $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array('TZID' => $apTimezone));
362                //$todo->setProperty('X-MICROSOFT-CDO-ALLDAYEVENT', 'FALSE');
363            }
364
365            if(isset($v['due']) && $v['due'] != '' && (int)$v['due'] > 0){
366                $dueTime = new DateTime('@' . (int) ($v['due'] / 1000), $timezone);
367                $dueTime->setTimezone($apTimezoneOBJ);
368
369                $todo->setProperty('due', $dueTime->format(DATE_RFC822), array('TZID' => $apTimezone));
370            }
371                   
372            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
373                $participants = $v['participants'];
374            else
375                $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
376           
377            if (is_array($participants) && count($participants) > 0)
378                foreach ($participants as $ii => $vv) {
379               
380                    if(isset($participants[$ii]['user']) && !is_array($participants[$ii]['user']))
381                    {
382                        if ($vv['isExternal'] == 1)
383                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
384                        else
385                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
386                    }
387               
388                    if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
389                    {
390                        $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']))));
391                        if(is_array($alarms))
392                            self::createAlarms($alarms, $todo);
393                    }
394               
395                }
396
397            if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
398                $this->createAttendee($v['participants'], $todo);
399
400            if (isset($v['attachments']) && is_array($v['attachments']) && count($v['attachments']) > 0)
401                $this->createAttachment($v['attachments'], $todo);
402
403            $todo->setProperty('uid', $v['uid']); 
404           
405            break;
406
407                default:
408                    break;
409            }
410        }
411
412       
413        return $ical->createCalendar();
414    }
415
416    protected function formatIcalRepeat($pRepeat)
417    {
418        $repeat = array();
419
420                foreach ($pRepeat as $ir => $rv) {
421                    if ($rv) {
422                if ($ir == 'frequency' && $rv !== 'none')
423                    $repeat['FREQ'] = $rv;
424                else if ($ir == 'endTime') {
425                    $time = new DateTime('@' . (int) ($rv / 1000), new DateTimeZone('UTC'));
426                    $time->setTimezone($apTimezoneOBJ);
427                    $repeat['until'] = $time->format(DATE_RFC822);
428                }else if ($ir == 'count')
429                    $repeat[$ir] = $rv;
430                else if ($ir == 'interval')
431                    $repeat[$ir] = $rv;
432                else if ($ir !== 'schedulable' && $ir !== 'id' && $ir !== 'startTime')
433                    $repeat[$ir] = explode(',', $rv);
434                    }
435                }
436                return $repeat;
437    }
438
439   
440    public function createAlarms($alarms, &$vevent)
441    {   
442            foreach ($alarms as $va)
443            {
444                $valarm = new valarm();
445                $valarm->setProperty('ACTION' , self::codeAlarmAction($va['type']));
446               
447                $duration = array();
448               
449                switch ($va['unit'])
450                {
451                        case 'h':
452                                $duration['hour'] = $va['time'];
453                        break;
454                        case 'm':
455                                $duration['min'] = $va['time'];
456                        break;
457                        case 's':
458                                $duration['sec'] = $va['time'];
459                                break;
460                }
461               
462                $valarm->setProperty('trigger' ,$duration);
463                $vevent->setComponent($valarm);
464            }   
465       
466    }
467
468    //Trata a criacao de anexos do ics
469    public function createAttachment($attachments, &$vevent) {
470        foreach ($attachments as $key => $attachment) {
471            $pParams = array("ENCODING" => "BASE64", "VALUE" => "BINARY",
472                "X-FILENAME" => $attachment['name']);
473
474            $vevent->setProperty("attach", $attachment['source'], $pParams);
475        }
476    }
477
478    //Trata a criacao de attendees com tratamento de delegate
479    public function createAttendee($attendees, &$vevent) {
480        $delegate = array();
481        foreach ($attendees as $di => $dv) {
482            if (isset($dv['delegatedFrom']) && $dv['delegatedFrom'] != 0) {
483                $delegate[$dv['delegatedFrom']] = $dv;
484            }
485        }
486
487        foreach ($attendees as $pi => $pv) {
488            $isResponseDelegated = false;
489            if ((isset($pv['delegatedFrom']) && $pv['delegatedFrom'] == 0) || !isset($pv['delegatedFrom']))  {
490                if ($pv['isOrganizer'] == 1)
491                    $vevent->setProperty('organizer', $pv['user']['mail'], array('CN' => $pv['user']['name']));
492                else {
493                    $pParams = array();
494                    $pParams['CN'] = $pv['user']['name'];
495                    $pParams['PARTSTAT'] = self::_getStatus($pv['status']);
496
497                    if (isset($pv['id']) && isset($delegate[$pv['id']])) {
498                        $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
499                        $pParams['DELEGATED-TO'] = $delegate[$pv['id']]['user']['mail'];
500                        $pParams['CN'] = $pv['user']['name'];
501
502                        $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
503
504                        if ($delegate[$pv['id']]['status'] == STATUS_UNANSWERED) {
505                            $pParams['RSVP'] = $pv['receiveNotification'] == 1 ? 'TRUE' : 'FALSE';
506                            unset($pParams['PARTSTAT']);
507                        }else
508                            $pParams['PARTSTAT'] = self::_getStatus($delegate[$pv['id']]['status']);
509
510                        unset($pParams['DELEGATED-TO']);
511                        $pParams['DELEGATED-FROM'] = $pv['user']['mail'];
512
513                        $vevent->setProperty('attendee', $delegate[$pv['id']]['user']['mail'], $pParams);
514                        continue;
515                    }
516                    $pParams['RSVP'] = 'TRUE';
517
518                    $vevent->setProperty('attendee', $pv['user']['mail'], $pParams);
519
520                }
521            }
522           
523           
524        }
525    }
526
527    public function parse($data, $params = false) {
528        Config::regSet('noAlarm', TRUE); //Evita o envio de notificação
529        $vcalendar = new vcalendar( );
530        $vcalendar->parse(trim($data));
531        $vcalendar->sort();
532
533        $return = array();
534        $method = $vcalendar->getProperty('method', FALSE, FALSE);
535        $params['prodid'] = $vcalendar->getProperty('prodid', false, false);
536        $params['X-WR-TIMEZONE'] = ( $xrTimezone = $vcalendar->getProperty('X-WR-TIMEZONE', false, false)) ? self::nomalizeTZID($xrTimezone[1]) : false ;
537
538        while ($component = $vcalendar->getComponent()) {
539            $interation = array();
540            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
541
542            switch (strtoupper($component->objName)) {
543                case 'VEVENT':
544
545                    switch ($method) {
546                        case 'PUBLISH':
547                            //Caso o evento não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
548                if (!$schedulable = self::_getSchedulable($uid))
549                                    $interation = self::_makeVEVENT($schedulable, $component, $params);
550                else{
551                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
552                                        array('AND',
553                                            array('=', 'calendar', $params['calendar']),
554                                            array('=', 'schedulable', $schedulable['id'])
555                                        )));
556
557                    if(!$links &&  !isset($links[0]))
558                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
559
560                    }
561                            break;
562
563                        case 'REQUEST':
564                            $schedulable = self::_getSchedulable($uid);
565
566                            if ($schedulable) { //Caso o evento exista
567                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
568                                    $calendarToSchedulable = array();
569                                    $calendarToSchedulable['calendar'] = $params['calendar'];
570                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
571                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
572   
573                                    if (isset($params['status'])) {
574                                        if($params['owner'] != Config::me("uidNumber")){                                           
575                                            $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                                           
576                                            $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
577                                        }else{
578                                            $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
579                            //caso nõa seja participante adiciona a lista de participantes
580                            if(!$pID){
581                                $pID =  mt_rand() . '2(Formatter)';
582                                $interation['participant://' . $pID]['status'] = $params['status'];
583                                $interation['participant://' . $pID]['user'] = $params['owner'];
584                                $interation['participant://' . $pID]['isOrganizer'] = '0';
585                                $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
586                            }else
587                                            $interation['participant://' . $pID]['status'] = $params['status'];
588                        }
589                                    }
590
591                                    Config::regSet('noAlarm', FALSE); //reativa notificação
592                                } else {
593
594                                    if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
595                                        $interation = self::_makeVEVENT($schedulable, $component, $params);
596                                    else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
597                                        //Ler melhor rfc sobre isto 3.2.2.2
598                                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
599                                    }
600
601                                    if (isset($params['status'])) {
602                                        if($params['owner'] != Config::me("uidNumber")){                                           
603                                           $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                                     
604                                            $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
605                                        }else
606                                            $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
607                                        //Verifica a importação de eventos em que não participo
608                                        if ($pID) {
609                                            $interation['participant://' . $pID]['status'] = $params['status'];
610                                        }
611                                    }
612                                }
613                            } else { // Importar evento
614                                $interation = self::_makeVEVENT(array(), $component, $params);
615
616                                if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
617
618                                    /* Data de Inicio */
619                                    $startTime = $component->getProperty('dtstart', false, true);
620
621                                    $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
622
623                                    /* Tiem zone do evento */   
624                                    if ($tzid)
625                                        $sc['timezone'] = self::nomalizeTZID($tzid);
626                                    else
627                                        $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
628
629                                    $objTimezone = new DateTimeZone($sc['timezone']);
630
631                                    if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
632                                        $sc['allDay'] = 1;
633                                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
634                                    } 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 */
635                                        $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
636                                    else {
637                                        $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
638                                        if (strpos($params['prodid'], 'Outlook') !== false) {
639                                            //Se o ics veio em utc não aplicar horario de verão
640                                            $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
641                                            $sTime->setTimezone($objTimezone);
642                                            if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
643                                                $sc['startTime'] = $sc['startTime'] - 3600000;
644                                        }
645                                    }
646
647
648                                    /* Data de Termino */
649                                    $endTime = $component->getProperty('dtend', false, true);
650
651                                    if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
652                                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
653                                    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 */
654                                        $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
655                                    else {
656                                        $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
657                                        if (strpos($params['prodid'], 'Outlook') !== false) {
658                                            //Se o ics veio em utc não aplicar horario de verão
659                                            $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
660                                            $eTime->setTimezone($objTimezone);
661                                            if ($eTime->format('I'))
662                                                $sc['endTime'] = $sc['endTime'] - 3600000;
663                                        }
664                                    }
665
666
667                                    if ($uid = $component->getProperty('uid', false, false))
668                                        ;
669                                    $sc['uid'] = $uid;
670
671
672                                    $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
673
674                                    /* Definindo Description */
675                                    if ($desc = $component->getProperty('description', false, false))
676                                        $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
677
678                                    /* Definindo location */
679                                    if ($location = $component->getProperty('location', false, false))
680                                        $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
681
682
683
684                                    if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
685                                        $participant = array();
686                                        $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
687
688                                        $participantID = mt_rand() . '2(Formatter)';
689
690                                        $participant['isOrganizer'] = '1';
691
692                                        $user = null;
693
694                                        $participant['isExternal'] = 1;
695                                        /* Gera um randon id para o contexto formater */
696                                        $userID = mt_rand() . '4(Formatter)';
697
698                                        $user['mail'] = $mailUser;
699                                        $organizerMail = $mailUser;
700
701                                        $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
702                                        $user['isExternal'] = '1';
703                                        $participant['user'] = $user;
704
705                                        $sc['participants'][] = $participant;
706                                    }
707
708
709                                    $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
710                                    $participant['isOrganizer'] = '0';
711                                    $participant['isExternal'] = 0;
712                                    $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
713                                    $sc['participants'][] = $participant;
714                                    $sc['type'] = EVENT_ID;
715
716
717                                    $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
718                                    $ical['type'] = 'application/ics';
719                                    $ical['name'] = 'outlook.ics';
720
721                                    $ical2['source'] = $ical['source'];
722                                    $ical2['type'] = 'text/calendar; method=REPLY';
723                                    $ical2['name'] = 'thunderbird.ics';
724
725                                    $timezone = new DateTimeZone('UTC');
726                                    $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
727                                    $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
728
729                                    if (isset($sc['timezone'])) {
730                                        $sTime->setTimezone(new DateTimeZone($sc['timezone']));
731                                        $eTime->setTimezone(new DateTimeZone($sc['timezone']));
732                                    }
733
734                                    $data = array('startDate' => date_format($sTime, 'd/m/Y'),
735                                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
736                                        'endDate' => date_format($eTime, 'd/m/Y'),
737                                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
738                                        'eventTitle' => $sc['summary'],
739                                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
740                                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
741                                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
742
743                                    $subject['notificationType'] = 'Convite Aceito';
744                                    $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
745                                    $subject['startDate'] = date_format($sTime, 'd/m/Y');
746                                    $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
747                                    $subject['endDate'] = date_format($eTime, 'd/m/Y');
748                                    $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
749                                    $subject['participant'] = Config::me('uid');
750
751                                    $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
752
753                                    switch ($params['status']) {
754                                        case STATUS_ACCEPTED:
755                                            $tpl = 'notify_accept_body';
756                                            $subject['notificationType'] = 'Convite Aceito';
757                                            break;
758                                        case STATUS_TENTATIVE:
759                                            $tpl = 'notify_attempt_body';
760                                            $subject['notificationType'] = 'Convite  aceito provisoriamente';
761                                            break;
762                                        case STATUS_CANCELLED:
763                                            $tpl = 'notify_reject_body';
764                                            $subject['notificationType'] = 'Convite rejeitado';
765                                            break;
766                                    }
767                                    require_once ROOTPATH . '/api/parseTPL.php';
768
769                                    $mail = array();
770                                    $mail['attachments'][] = $ical;
771                                    $mail['attachments'][] = $ical2;
772
773                                    $mail['isHtml'] = true;
774                                    $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
775                                    $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
776                                    ;
777                                    $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
778                                    $mail['to'] = $organizerMail;
779
780
781                                    Controller::create(array('service' => 'SMTP'), $mail);
782                                }
783                            }
784                            break;
785
786                        case 'REFRESH':
787                            break;
788
789                        case 'CANCEL':
790                            if ($schedulable = self::_getSchedulable($uid))
791                                $interation['schedulable://' . $schedulable['id']] = false;
792                            break;
793                               
794                        case 'ADD':
795                            break;
796
797                        case 'REPLY':
798                            if ($schedulable = self::_getSchedulable($uid)) {
799                                while ($property = $component->getProperty('attendee', FALSE, TRUE))
800                                    if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
801                                        $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
802
803                                $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
804                            }
805                            break;
806
807                        case 'COUNTER':
808                            if ($params['acceptedSuggestion'] !== 'false') {
809
810                                $schedulable = self::_getSchedulable($uid);
811                                $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
812
813                                $interation = self::_makeCOUNTER($schedulable, $component, $params);
814                                Config::regSet('noAlarm', FALSE);
815                            } else {
816                                $response = array();
817                                $response['from'] = $params['from'];
818                                $response['type'] = 'suggestionResponse';
819                                $response['status'] = 'DECLINECOUNTER';
820                                $response['schedulable'] = self::_getSchedulable($uid);
821
822                                Controller::create(array('concept' => 'notification'), $response);
823                            }
824                            break;
825
826                        case 'DECLINECOUNTER':
827                            break;
828
829                        default:
830
831                            $schedulable = self::_getSchedulable($uid);
832
833                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
834                                $interation = self::_makeVEVENT($schedulable, $component, $params);
835
836                                if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
837                                    $calendarToSchedulable = array();
838                                    $calendarToSchedulable['calendar'] = $params['calendar'];
839                                    $calendarToSchedulable['schedulable'] = $schedulable['id'];
840                                    $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
841                                }
842                            }
843                            else // Importar evento
844                                $interation = self::_makeVEVENT(array(), $component, $params);
845                            break;
846                    }
847       
848                   
849                    $return[] = $interation;
850                    break;
851        /***********************************************************************TODO*******************************************************************************/
852        case 'VTODO':
853        switch ($method) {
854            case 'PUBLISH':
855                //Caso a tarefa não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
856                if (!$schedulable = self::_getSchedulable($uid))
857                    $interation = self::_makeVTODO($schedulable, $component, $params);
858                else{
859                    $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
860                    array('AND',
861                        array('=', 'calendar', $params['calendar']),
862                        array('=', 'schedulable', $schedulable['id'])
863                    )));
864
865                    if(!$links &&  !isset($links[0]))
866                        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $params['calendar'], 'schedulable' => $schedulable['id']));
867                }
868                break;
869
870            case 'REQUEST':
871                $schedulable = self::_getSchedulable($uid);
872
873                if ($schedulable) { //Caso tarefa exista
874                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
875                       
876                        $calendarToSchedulable = array();
877                        $calendarToSchedulable['calendar'] = $params['calendar'];
878                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
879                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
880       
881                        if (isset($params['status'])) {
882                            if($params['owner'] != Config::me("uidNumber")){                       
883                                $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                       
884                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
885                            }else
886                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
887                                $interation['participant://' . $pID]['status'] = $params['status'];
888                        }
889                        Config::regSet('noAlarm', FALSE); //reativa notificação
890                    } else {
891
892                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
893                            $interation = self::_makeVEVENT($schedulable, $component, $params);
894                        else if ($component->getProperty('sequence', false, false) === $schedulable['sequence']) {
895                        //Ler melhor rfc sobre isto 3.2.2.2
896                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
897                        }
898
899                        if (isset($params['status'])) {
900                            if($params['owner'] != Config::me("uidNumber")){                       
901                               $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );                     
902                                $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
903                            }else{
904                                $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
905                                //Verifica a importação de tarefas em que não participo
906                                if ($pID) {
907                                    $pID =  mt_rand() . '2(Formatter)';
908                                    $interation['participant://' . $pID]['status'] = $params['status'];
909                                    $interation['participant://' . $pID]['user'] = $params['owner'];
910                                    $interation['participant://' . $pID]['isOrganizer'] = '0';
911                                    $interation['participant://' . $pID]['schedulable'] = $schedulable['id'];
912                                }else
913                                    $interation['participant://' . $pID]['status'] = $params['status'];
914                            }
915                        }
916                    }
917                } else { // Importar tarefa
918                    $interation = self::_makeVTODO(array(), $component, $params);
919
920                    if (strpos($params['prodid'], 'kigkonsult.se') !== false) { //envia notificação para fora
921
922                        /* Data de Inicio */
923                        $startTime = $component->getProperty('dtstart', false, true);
924                        $tzid = isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
925
926                        /* Tiem zone do evento */   
927                        if ($tzid)
928                            $sc['timezone'] = self::nomalizeTZID($tzid);
929                        else
930                            $sc['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
931
932                        $objTimezone = new DateTimeZone($sc['timezone']);
933
934                        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
935                            $sc['allDay'] = 1;
936                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
937                        } 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 */
938                            $sc['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID']) . '000';
939                        else {
940                            $sc['startTime'] = self::date2timestamp($startTime['value']) . '000';
941                            if (strpos($params['prodid'], 'Outlook') !== false) {
942                                //Se o ics veio em utc não aplicar horario de verão
943                                $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), new DateTimeZone('UTC'));
944                                $sTime->setTimezone($objTimezone);
945                                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
946                                $sc['startTime'] = $sc['startTime'] - 3600000;
947                            }
948                        }
949
950                        /* Data de Termino */
951                        $endTime = $component->getProperty('dtend', false, true);
952
953                        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
954                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $sc['timezone']) . '000';
955                        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 */
956                            $sc['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID']) . '000';
957                        else {
958                            $sc['endTime'] = self::date2timestamp($endTime['value']) . '000';
959                            if (strpos($params['prodid'], 'Outlook') !== false) {
960                                //Se o ics veio em utc não aplicar horario de verão
961                                $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), new DateTimeZone('UTC'));
962                                $eTime->setTimezone($objTimezone);
963                                if ($eTime->format('I'))
964                                    $sc['endTime'] = $sc['endTime'] - 3600000;
965                            }
966                        }
967
968
969                        if ($uid = $component->getProperty('uid', false, false))                   
970                            $sc['uid'] = $uid;
971
972                        $sc['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'UTF-8', 'UTF-8,ISO-8859-1');
973
974                        /* Definindo Description */
975                        if ($desc = $component->getProperty('description', false, false))
976                            $sc['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'UTF-8', 'UTF-8,ISO-8859-1');
977
978            if ($priority = $component->getProperty('priority', false, false))
979                $sc['priority'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $priority), 'UTF-8', 'UTF-8,ISO-8859-1');
980
981            if ($status = $component->getProperty('status', false, false))
982                $sc['status'] = $this->decodeStatusTodo(mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $status), 'UTF-8', 'UTF-8,ISO-8859-1'));
983
984            if ($percentage = $component->getProperty('percent-complete', false, false))
985                $sc['percentage'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $percentage), 'UTF-8', 'UTF-8,ISO-8859-1');
986
987                        /* Definindo location */
988                        if ($location = $component->getProperty('location', false, false))
989                            $sc['location'] = mb_convert_encoding($location, 'UTF-8', 'UTF-8,ISO-8859-1');
990
991
992
993                        if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
994                            $participant = array();
995                            $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
996
997                            $participantID = mt_rand() . '2(Formatter)';
998
999                            $participant['isOrganizer'] = '1';
1000
1001                            $user = null;
1002
1003                            $participant['isExternal'] = 1;
1004                            /* Gera um randon id para o contexto formater */
1005                            $userID = mt_rand() . '4(Formatter)';
1006
1007                            $user['mail'] = $mailUser;
1008                            $organizerMail = $mailUser;
1009
1010                            $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
1011                            $user['isExternal'] = '1';
1012                            $participant['user'] = $user;
1013
1014                            $sc['participants'][] = $participant;
1015                        }
1016
1017
1018                        $participant['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1019                        $participant['isOrganizer'] = '0';
1020                        $participant['isExternal'] = 0;
1021                        $participant['user'] = array('mail' => Config::me('mail'), 'name' => Config::me('cn'));
1022                        $sc['participants'][] = $participant;
1023                        $sc['type'] = TODO_ID;
1024
1025
1026                        $ical['source'] = Controller::format(array('service' => 'iCal'), array($sc), array('method' => 'REPLY'));
1027                        $ical['type'] = 'application/ics';
1028                        $ical['name'] = 'outlook.ics';
1029
1030                        $ical2['source'] = $ical['source'];
1031                        $ical2['type'] = 'text/calendar; method=REPLY';
1032                        $ical2['name'] = 'thunderbird.ics';
1033
1034                        $timezone = new DateTimeZone('UTC');
1035                        $sTime = new DateTime('@' . (int) ($sc['startTime'] / 1000), $timezone);
1036                        $eTime = new DateTime('@' . (int) ($sc['endTime'] / 1000), $timezone);
1037
1038                        if (isset($sc['timezone'])) {
1039                            $sTime->setTimezone(new DateTimeZone($sc['timezone']));
1040                            $eTime->setTimezone(new DateTimeZone($sc['timezone']));
1041                        }
1042
1043                        $data = array('startDate' => date_format($sTime, 'd/m/Y'),
1044                        'startTime' => (isset($sc['allDay']) && $sc['allDay'] ) ? '' : date_format($sTime, 'H:i'),
1045                        'endDate' => date_format($eTime, 'd/m/Y'),
1046                        'endTime' => isset($sc['allDay']) ? '' : date_format($eTime, 'H:i'),
1047                        'eventTitle' => $sc['summary'],
1048                        'eventLocation' => isset($sc['location']) ? $sc['location'] : '',
1049                        'timezone' => ($sc['timezone']) ? $sc['timezone'] : 'UTC',
1050                        'participant' => (isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail']));
1051
1052                        $subject['notificationType'] = 'Convite Aceito';
1053                        $subject['eventTitle'] = mb_convert_encoding($sc['summary'], 'ISO-8859-1', 'ISO-8859-1,UTF-8');
1054                        $subject['startDate'] = date_format($sTime, 'd/m/Y');
1055                        $subject['startTime'] = ($sc['allDay']) ? '' : date_format($sTime, 'H:i');
1056                        $subject['endDate'] = date_format($eTime, 'd/m/Y');
1057                        $subject['endTime'] = ($sc['allDay']) ? '' : date_format($eTime, 'H:i');
1058                        $subject['participant'] = Config::me('uid');
1059
1060                        $params['status'] = isset($params['status']) ? $params['status'] : STATUS_ACCEPTED;
1061
1062                        switch ($params['status']) {
1063                            case STATUS_ACCEPTED:
1064                                $tpl = 'notify_accept_body';
1065                                $subject['notificationType'] = 'Convite Aceito';
1066                                break;
1067                            case STATUS_TENTATIVE:
1068                                $tpl = 'notify_attempt_body';
1069                                $subject['notificationType'] = 'Convite  aceito provisoriamente';
1070                                break;
1071                            case STATUS_CANCELLED:
1072                                $tpl = 'notify_reject_body';
1073                                $subject['notificationType'] = 'Convite rejeitado';
1074                                break;
1075                        }
1076
1077                        require_once ROOTPATH . '/api/parseTPL.php';
1078
1079                        $mail = array();
1080                        $mail['attachments'][] = $ical;
1081                        $mail['attachments'][] = $ical2;
1082
1083                        $mail['isHtml'] = true;
1084                        $mail['body'] = parseTPL::load_tpl($data, ROOTPATH . '/modules/calendar/templates/' . $tpl . '.tpl');
1085                        $mail['subject'] = parseTPL::load_tpl($subject, ROOTPATH . '/modules/calendar/templates/notify_subject.tpl');
1086
1087                        $mail['from'] = '"' . Config::me('cn') . '" <' . Config::me('mail') . '>';
1088                        $mail['to'] = $organizerMail;
1089
1090
1091                        Controller::create(array('service' => 'SMTP'), $mail);
1092                    }
1093                }
1094                break;
1095
1096            case 'REFRESH':
1097                break;
1098
1099            case 'CANCEL':
1100                if ($schedulable = self::_getSchedulable($uid))
1101                    $interation['schedulable://' . $schedulable['id']] = false;
1102                break;
1103
1104            case 'ADD':
1105                break;
1106
1107            case 'REPLY':
1108                if ($schedulable = self::_getSchedulable($uid)) {
1109                    while ($property = $component->getProperty('attendee', FALSE, TRUE))
1110                        if ($pID = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
1111                            $interation['participant://' . $pID] = array('id' => $pID, 'status' => constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])));
1112
1113                    $interation['schedulable://' . $schedulable['id']]['sequence'] = $schedulable['sequence'] + 1;
1114                }
1115                break;
1116
1117            case 'COUNTER':
1118                if ($params['acceptedSuggestion'] !== 'false') {
1119
1120                    $schedulable = self::_getSchedulable($uid);
1121                    $params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
1122
1123                    $interation = self::_makeCOUNTER($schedulable, $component, $params);
1124                    Config::regSet('noAlarm', FALSE);
1125                } else {
1126                    $response = array();
1127                    $response['from'] = $params['from'];
1128                    $response['type'] = 'suggestionResponse';
1129                    $response['status'] = 'DECLINECOUNTER';
1130                    $response['schedulable'] = self::_getSchedulable($uid);
1131
1132                    Controller::create(array('concept' => 'notification'), $response);
1133                }
1134                break;
1135
1136            case 'DECLINECOUNTER':
1137                break;
1138
1139            default:
1140
1141                $schedulable = self::_getSchedulable($uid);
1142
1143                if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) { //Caso o evento exista
1144                    $interation = self::_makeVEVENT($schedulable, $component, $params);
1145
1146                    if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
1147                        $calendarToSchedulable = array();
1148                        $calendarToSchedulable['calendar'] = $params['calendar'];
1149                        $calendarToSchedulable['schedulable'] = $schedulable['id'];
1150                        $interation['calendarToSchedulable://' . mt_rand() . '(Formatter)'] = $calendarToSchedulable;
1151                    }
1152                }
1153                else // Importar evento
1154                $interation = self::_makeVEVENT(array(), $component, $params);
1155
1156                break;
1157            }
1158   
1159            $return[] = $interation;
1160        break;
1161        /***********************************************************************TODO*******************************************************************************/
1162        case 'VTIMEZONE':
1163                break;
1164            }
1165        }
1166        return $return;
1167    }
1168
1169    public function analize($data, $params = false) {
1170        $vcalendar = new vcalendar( );
1171        $vcalendar->parse(trim($data));
1172        $vcalendar->sort();
1173
1174        $return = array();
1175        $method = $vcalendar->getProperty('method', FALSE, FALSE);
1176
1177        while ($component = $vcalendar->getComponent()) {
1178            $interation = array();
1179            $uid = $component->getProperty('uid', false, false); //Resgata o uid do componente
1180            switch (strtoupper($component->objName)) {
1181                case 'VEVENT':
1182
1183                    switch ($method) {
1184                        case 'PUBLISH':
1185                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1186                            break;
1187
1188                        case 'REQUEST':
1189                            $schedulable = self::_getSchedulable($uid);
1190                            if ($schedulable) { //Caso o evento exista
1191                                $isOrganizer = false;
1192                                $isParticipant = false;
1193
1194                                foreach ($schedulable['participants'] as $value)
1195                                    if ($value['user']['id'] == $params['owner']) {
1196                                        $isParticipant = true;
1197                                        if ($value['isOrganizer'])
1198                                            $isOrganizer = true;
1199
1200                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
1201                                            $interation = ICAL_ACTION_UPDATE;
1202                                            $interation = ( strrpos($value['acl'], ATTENDEE_ACL_PARTICIPATION_REQUIRED) ) ? ICAL_ACTION_IMPORT_REQUIRED : array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1203                                            break;
1204                                        }
1205                                    } else {
1206                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1207                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1208                                        else
1209                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1210                                    }
1211                                if (!$isParticipant){
1212                                      $interation = self::_checkParticipantByPermissions($schedulable);
1213                                    }
1214                            }else
1215                                    $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1216                           
1217                            if(($interation != ICAL_ACTION_NONE) && ($interation != ICAL_ACTION_ORGANIZER_NONE) && ($interation != ICAL_ACTION_ORGANIZER_UPDATE) && ($interation != ICAL_ACTION_NONE)) {
1218                                if($params['owner'] != Config::me("uidNumber")){
1219                                    $sig = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=', 'user', $params['owner']), array('=', 'isOwner', '1'))));
1220                                    $calendars = array();
1221                                    foreach ($sig as $val)
1222                                        $calendars[] = $val['calendar'];
1223                               
1224                                    $calendarsPermission = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('=', 'user', Config::me("uidNumber")), array('IN', 'calendar', $calendars))));   
1225                                   
1226                                    foreach ($calendarsPermission as $val)
1227                                        $ids[] = $val['calendar'];
1228
1229                                    $interation = array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION ,'calendar' => $ids);
1230                                }
1231                            }
1232
1233                            break;
1234
1235                        case 'REFRESH':
1236                            break;
1237
1238                        case 'CANCEL':
1239                            $interation = ICAL_ACTION_DELETE;
1240                            break;
1241
1242                        case 'ADD':
1243                            break;
1244
1245                        case 'REPLY':
1246                                if ($schedulable = self::_getSchedulable($uid)) {
1247                                        while ($property = $component->getProperty('attendee', FALSE, TRUE))
1248                                            if ($attendee = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants'], true))
1249                                                        $interation = (constant('STATUS_' . strtoupper($property['params']['PARTSTAT'])) == $attendee['status']) ?  ICAL_ACTION_NONE : ICAL_ACTION_REPLY;
1250                            }else
1251                                $interation = ICAL_NOT_FOUND;
1252                            break;
1253
1254                        case 'COUNTER':
1255                            $interation = ICAL_ACTION_SUGGESTION;
1256                            break;
1257
1258                        case 'DECLINECOUNTER':
1259                            $interation = ICAL_ACTION_NONE;
1260                            break;
1261
1262                        default:
1263                            $schedulable = self::_getSchedulable($uid);
1264
1265                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1266                                $interation = ICAL_ACTION_UPDATE;
1267                            else if ($schedulable)
1268                                $interation = ICAL_ACTION_NONE;
1269                            else // Importar evento
1270                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1271
1272                            break;
1273                    }
1274
1275                    $return[$uid] = $interation;
1276                    break;
1277                case 'VTODO':
1278                    switch ($method) {
1279                        case 'PUBLISH':
1280                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1281                            break;
1282
1283                        case 'REQUEST':
1284                            $schedulable = self::_getSchedulable($uid);
1285                           
1286                            if ($schedulable) { //Caso o evento exista
1287                                $isOrganizer = false;
1288                                $isParticipant = false;
1289
1290                                foreach ($schedulable['participants'] as $value)
1291                                    if ($value['user']['id'] == $params['owner']) {
1292                                        $isParticipant = true;
1293                                        if ($value['isOrganizer'])
1294                                            $isOrganizer = true;
1295
1296                                        if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {   
1297                                            $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1298                                            break;
1299                                        }
1300                                    } else {
1301                                        if (self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
1302                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_UPDATE : ICAL_ACTION_UPDATE;
1303                                        else
1304                                            $interation = ($isOrganizer) ? ICAL_ACTION_ORGANIZER_NONE : ICAL_ACTION_NONE;
1305                                    }
1306                                if (!$isParticipant){
1307                                      $interation = self::_checkParticipantByPermissions($schedulable);
1308                                    }
1309                            }else
1310                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1311                            break;
1312
1313                        case 'REFRESH':
1314                            break;
1315
1316                        case 'CANCEL':
1317                            $interation = ICAL_ACTION_DELETE;
1318                            break;
1319
1320                        case 'ADD':
1321                            break;
1322
1323                        case 'REPLY':
1324                            $interation = ICAL_ACTION_REPLY;
1325                            break;
1326
1327                        case 'COUNTER':
1328                            $interation = ICAL_ACTION_SUGGESTION;
1329                            break;
1330
1331                        case 'DECLINECOUNTER':
1332                            $interation = ICAL_ACTION_NONE;
1333                            break;
1334
1335                        default:
1336                            $schedulable = self::_getSchedulable($uid);
1337
1338                            if ($schedulable && ( self::_getTime($component, 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty('sequence', false, false) > $schedulable['sequence'])) //Caso o evento exista
1339                                $interation = ICAL_ACTION_UPDATE;
1340                            else if ($schedulable)
1341                                $interation = ICAL_ACTION_NONE;
1342                            else // Importar evento
1343                                $interation = array('action' => ICAL_ACTION_IMPORT, 'type' => 'groupIds');
1344
1345                            break;
1346                    }
1347
1348                    $return[$uid] = $interation;
1349                    break;
1350                case 'VTIMEZONE':
1351                break;
1352            }
1353        }
1354
1355        return $return;
1356    }
1357
1358    /* Helpers */
1359
1360    private static function _getTzOffset($rTz, $oTz = null, $time = 'now') {
1361        if ($oTz === null) {
1362            if (!is_string($oTz = date_default_timezone_get())) {
1363                return false; // A UTC timestamp was returned -- bail out!
1364            }
1365        }
1366        $origin_dtz = new DateTimeZone(self::nomalizeTZID($oTz));
1367        $remote_dtz = new DateTimeZone(self::nomalizeTZID($rTz));
1368        $origin_dt = new DateTime($time, $origin_dtz);
1369        $remote_dt = new DateTime("now", $remote_dtz);
1370
1371        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
1372
1373
1374        return $offset;
1375    }
1376
1377    private function _getStatus($id) {
1378        $a = array(
1379            STATUS_CONFIRMED => 'ACCEPTED',
1380            STATUS_CANCELLED => 'CANCELLED',
1381            STATUS_TENTATIVE => 'TENTATIVE',
1382            STATUS_UNANSWERED => 'NEEDS-ACTION',
1383            STATUS_DELEGATED => 'DELEGATED'
1384        );
1385
1386        return isset($a[$id]) ? $a[$id] : 'NEEDS-ACTION';
1387    }
1388
1389    public function decodeStatusTodo( $action )
1390    {
1391     $a = array(
1392        'NEED_ACTION' => STATUS_TODO_NEED_ACTION,
1393        'IN_PROGRESS' => STATUS_TODO_IN_PROGRESS  ,
1394        'COMPLETED' =>  STATUS_TODO_COMPLETED ,
1395        'CANCELLED'  => STATUS_TODO_CANCELLED
1396    );
1397
1398    return isset($a[$action]) ? $a[$action] : 'STATUS_TODO_NEED_ACTION';
1399   
1400    }
1401
1402
1403    private function _getStatusTodo($id) {
1404        $a = array(
1405            STATUS_TODO_NEED_ACTION => 'NEED_ACTION',
1406            STATUS_TODO_IN_PROGRESS => 'IN_PROGRESS',
1407            STATUS_TODO_COMPLETED => 'COMPLETED',
1408            STATUS_TODO_CANCELLED => 'CANCELLED'
1409        );
1410
1411    return isset($a[$id]) ? $a[$id] : 'NEED_ACTION';
1412    }
1413
1414    private static function _checkParticipantByPermissions($schedulable) {
1415
1416        $calendarIds = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=','isOwner','0'), array('=', 'user', Config::me("uidNumber")))));
1417
1418        if($calendarIds && isset($calendarIds[0])){
1419            $ids = array();
1420            foreach($calendarIds as $value)
1421                    array_push($ids, $value['calendar']);
1422
1423            $signaturesOfOwners = Controller::find(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('IN', 'calendar', $ids) , array('=','isOwner','1')), 'deepness' => 2 ));
1424           
1425            foreach($signaturesOfOwners as $value){
1426                        if(self::_getParticipantByMail($value['user']['mail'], $schedulable['participants'])){
1427                            $eventoFromCalendar = Controller::read( array( 'concept' => 'calendarToSchedulable') , false, array('filter' => array('AND', array('=','schedulable',$schedulable['id']), array('=','calendar', $value['calendar']['id']))));
1428
1429                            return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => array($value['calendar']['id']) );
1430                        }
1431            }   
1432        }
1433        return array('action' => ICAL_ACTION_IMPORT, 'type' => 'calendarIds');
1434    }
1435   
1436   
1437    private static function _getParticipantByMail($mail, &$participants, $isFull = false) {
1438        if ($participants && $participants != '')
1439            foreach ($participants as $i => $v)
1440                if ((is_array($v) && isset($v['user'])) && ($v['user']['mail'] == $mail || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress']))))
1441                      return !!$isFull ? $v : $v['id'];
1442        return false;
1443    }
1444
1445    static private function nomalizeTZID($TZID) {
1446        if (isset(self::$timezonesMap[$TZID]))
1447            return self::$timezonesMap[$TZID];
1448        else if (in_array($TZID, self::$suportedTimzones))
1449            return $TZID;
1450        else
1451            return date_default_timezone_get();
1452    }
1453
1454    static private function date2timestamp($datetime, $tz = null) {
1455        if (!isset($datetime['hour']))
1456            $datetime['hour'] = '0';
1457        if (!isset($datetime['min']))
1458            $datetime['min'] = '0';
1459        if (!isset($datetime['sec']))
1460            $datetime['sec'] = '0';
1461
1462        foreach ($datetime as $dkey => $dvalue)
1463            if ('tz' != $dkey)
1464                $datetime[$dkey] = (integer) $dvalue;
1465
1466        if ($tz)
1467            $datetime['tz'] = $tz;
1468
1469        $offset = ( isset($datetime['tz']) && ( '' < trim($datetime['tz']))) ? iCalUtilityFunctions::_tz2offset($datetime['tz']) : 0;
1470
1471        return gmmktime($datetime['hour'], $datetime['min'], ($datetime['sec'] + $offset), $datetime['month'], $datetime['day'], $datetime['year']);
1472    }
1473
1474    static private function _makeCOUNTER($schedulable, $component, $params) {
1475        $interation = array();
1476        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1477
1478        /* Data de Inicio */
1479        $startTime = $component->getProperty('dtstart', false, true);
1480
1481        /* Tiem zone do evento */
1482        if (isset($startTime['params']['TZID']))
1483            $schedulable['timezone'] = self::nomalizeTZID($startTime['params']['TZID']);
1484        else
1485            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1486
1487        $objTimezone = new DateTimeZone($schedulable['timezone']);
1488
1489        if ($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1490            $schedulable['allDay'] = 1;
1491            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1492        } 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 */
1493            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $startTime['params']['TZID'], '@' . self::date2timestamp($startTime['value'])) . '000';
1494            $schedulable['allDay'] = 0;
1495        } else {
1496            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1497            if (strpos($params['prodid'], 'Outlook') !== false) {
1498                //Se o ics veio em utc não aplicar horario de verão
1499                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1500                $sTime->setTimezone($objTimezone);
1501                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1502                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1503            }
1504        }
1505
1506        /* Data de Termino */
1507        $endTime = $component->getProperty('dtend', false, true);
1508
1509        if ($endTime['params']['VALUE'] === 'DATE')
1510            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1511        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 */
1512            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $endTime['params']['TZID'], '@' . self::date2timestamp($endTime['value'])) . '000';
1513        else {
1514            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1515            if (strpos($params['prodid'], 'Outlook') !== false) {
1516                //Se o ics veio em utc não aplicar horario de verão
1517                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1518                $eTime->setTimezone($objTimezone);
1519                if ($eTime->format('I'))
1520                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1521            }
1522        }
1523        unset($schedulable['participants']);
1524        $interation['schedulable://' . $eventID] = $schedulable;
1525
1526        return $interation;
1527    }
1528
1529    static private function _makeVEVENT($schedulable, $component, $params) {
1530        $interation = array();
1531        $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
1532
1533        /* Data de Inicio */
1534        $startTime = $component->getProperty('dtstart', false, true);
1535
1536        $tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
1537
1538        /* Tiem zone do evento */
1539        if ($tzid){
1540            $tzid = self::nomalizeTZID($tzid);
1541            $schedulable['timezone'] = $tzid;
1542        }else
1543            $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
1544
1545        $objTimezone = new DateTimeZone($schedulable['timezone']);
1546
1547        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
1548            $schedulable['allDay'] = 1;
1549            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
1550        } 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 */
1551            $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
1552            $schedulable['allDay'] = 0;
1553        } else {
1554            $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
1555            if (strpos($params['prodid'], 'Outlook') !== false) {
1556                //Se o ics veio em utc não aplicar horario de verão
1557                $sTime = new DateTime('@' . (int) ($schedulable['startTime'] / 1000), new DateTimeZone('UTC'));
1558                $sTime->setTimezone($objTimezone);
1559                if ($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
1560                    $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
1561            }
1562        }
1563
1564        /* Data de Termino */
1565        $endTime = $component->getProperty('dtend', false, true);
1566
1567        $tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
1568       
1569        if($tzid)
1570            $tzid = self::nomalizeTZID($tzid);
1571
1572        if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
1573            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
1574        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 */
1575            $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $tzid, '@' . self::date2timestamp($endTime['value'])) . '000';
1576        else {
1577            $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
1578            if (strpos($params['prodid'], 'Outlook') !== false) {
1579                //Se o ics veio em utc não aplicar horario de verão
1580                $eTime = new DateTime('@' . (int) ($schedulable['endTime'] / 1000), new DateTimeZone('UTC'));
1581                $eTime->setTimezone($objTimezone);
1582                if ($eTime->format('I'))
1583                    $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
1584            }
1585        }
1586
1587
1588        $schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1589
1590        /* Definindo Description */
1591        if ($desc = $component->getProperty('description', false, false))
1592            $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1593
1594        /* Definindo location */
1595        if ($location = $component->getProperty('location', false, false))
1596            $schedulable['location'] = mb_convert_encoding($location, 'ISO-8859-1', 'UTF-8,ISO-8859-1');
1597
1598
1599        /* Definindo Class */
1600        $class = $component->getProperty('class', false, false);
1601        if ($class && defined(constant(strtoupper('CLASS_' . $class))))
1602            $schedulable['class'] = constant(strtoupper('CLASS_' . $class));
1603        else if (!isset($schedulable['class']))
1604            $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
1605
1606        /* Definindo RRULE */
1607        if ($rrule = $component->getProperty('rrule', false, false)) {
1608            /* Gera um randon id para o contexto formater */
1609            $repeatID = mt_rand() . '3(Formatter)';
1610
1611            $repeat = array();
1612            $repeat['schedulable'] = $eventID;
1613            $repeat['startTime'] = $schedulable['startTime'];
1614            foreach ($rrule as $i => $v) {
1615                if (strtolower($i) == 'freq')
1616                    $repeat['frequency'] = $v;
1617                else if (strtolower($i) == 'until')
1618            {
1619                $repeat['endTime'] = strtotime($v['year'].'-'.$v['month'].'-'.$v['day'].' '.$v['hour'].':'.$v['min'].':'.$v['sec'].' '.$v['tz']) .'000' ;
1620            }
1621                else
1622                    $repeat[strtolower($i)] = $v;
1623            }
1624
1625            $interation['repeat://' . $repeatID] = $repeat;
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.