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

Revision 7006, 105.9 KB checked in by acoutinho, 12 years ago (diff)

Ticket #3016 - Inconsistencia ao importar uma tarefa a partir do email

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