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

Revision 7695, 114.1 KB checked in by acoutinho, 11 years ago (diff)

Ticket #3258 - Inconsistencia na atualizacao de evento na agenda

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