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

Revision 8256, 118.4 KB checked in by cristiano, 10 years ago (diff)

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

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