source: branches/2.5/prototype/services/iCal.php @ 8257

Revision 8257, 118.4 KB checked in by douglas, 10 years ago (diff)

Ticket #3501 - Nao sensibilizacao de status apos importacao de evento

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