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

Revision 6996, 99.9 KB checked in by acoutinho, 12 years ago (diff)

Ticket #2966 - Merge de novas funcionalidades com trunk #2951, #2952

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