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

Revision 7068, 106.4 KB checked in by acoutinho, 12 years ago (diff)

Ticket #3054 - Inconsistencia ao importar alguma tarefa individual

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