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

Revision 7243, 106.6 KB checked in by acoutinho, 12 years ago (diff)

Ticket #3110 - Problema com horario de um evento na sincronizacao com davical

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