source: sandbox/2.4.2-expresso1/prototype/services/iCal.php @ 6891

Revision 6891, 84.6 KB checked in by acoutinho, 12 years ago (diff)

Ticket #2966 - Notificao e resposta de tasks / codec de normalizacao impressao de eventos

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