source: contrib/davical/inc/caldav-PUT-functions.php @ 3733

Revision 3733, 134.0 KB checked in by gabriel.malheiros, 13 years ago (diff)

Ticket #1541 - <Davical customizado para o Expresso.Utiliza Caldav e CardDav?>

Line 
1<?php
2/**
3* CalDAV Server - handle PUT method
4*
5* @package   davical
6* @subpackage   caldav
7* @author    Andrew McMillan <andrew@morphoss.com>
8* @copyright Morphoss Ltd - http://www.morphoss.com/
9* @license   http://gnu.org/copyleft/gpl.html GNU GPL v2 or later version
10*/
11
12/**
13* Check if the user wants to put just one VEVENT/VTODO or a whole calendar
14* if the collection = calendar = $request_container doesn't exist then create it
15* return true if it's a whole calendar
16*/
17
18require_once('iCalendar.php');
19require_once('DAVResource.php');
20include_once ("drivers_ldap.php");
21$bad_events = null;
22
23/**
24* A regex which will match most reasonable timezones acceptable to PostgreSQL.
25*/
26$tz_regex = ':^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Brazil|Canada|Chile|Etc|Europe|Indian|Mexico|Mideast|Pacific|US)/[a-z_]+$:i';
27
28/**
29* This function launches an error
30* @param boolean $caldav_context Whether we are responding via CalDAV or interactively
31* @param int $user_no the user who will receive this ics file
32* @param string $path the $path where the PUT failed to store such as /user_foo/home/
33* @param string $message An optional error message to return to the client
34* @param int $error_no An optional value for the HTTP error code
35*/
36function rollback_on_error( $caldav_context, $user_no, $path, $message='', $error_no=500 ) {
37  global $c, $bad_events;
38  if ( !$message ) $message = translate('Database error');
39  $qry = new AwlQuery();
40  $qry->Rollback();
41  if ( $caldav_context ) {
42    if ( isset($bad_events) && isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
43      $bad_events[] = $message;
44    }
45    else {
46      global $request;
47      $request->DoResponse( $error_no, $message );
48    }
49    // and we don't return from that, ever...
50  }
51
52  $c->messages[] = sprintf(translate('Status: %d, Message: %s, User: %d, Path: %s'), $error_no, $message, $user_no, $path);
53
54}
55
56
57
58/**
59* Work out the location we are doing the PUT to, and check that we have the rights to
60* do the needful.
61* @param string $username The name of the destination user
62* @param int $user_no The user making the change
63* @param string $path The DAV path the resource is bing PUT to
64* @param boolean $caldav_context Whether we are responding via CalDAV or interactively
65* @param boolean $public Whether the collection will be public, should we need to create it
66*/
67function controlRequestContainer( $username, $user_no, $path, $caldav_context, $public = null ) {
68  global $c, $bad_events;
69
70  // Check to see if the path is like /foo /foo/bar or /foo/bar/baz etc. (not ending with a '/', but contains at least one)
71  if ( preg_match( '#^(.*/)([^/]+)$#', $path, $matches ) ) {//(
72    $request_container = $matches[1];   // get everything up to the last '/'
73  }
74  else {
75    // In this case we must have a URL with a trailing '/', so it must be a collection.
76    $request_container = $path;
77  }
78
79  if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
80    $bad_events = array();
81  }
82
83  /**
84  * Before we write the event, we check the container exists, creating it if it doesn't
85  */
86  if ( $request_container == "/$username/" ) {
87    /**
88    * Well, it exists, and we support it, but it is against the CalDAV spec
89    */
90    dbg_error_log( 'WARN', ' Storing events directly in user\'s base folders is not recommended!');
91  }
92  else {
93    $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
94    $qry = new AwlQuery( $sql, array( ':dav_name' => $request_container) );
95    if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) {
96      rollback_on_error( $caldav_context, $user_no, $path );
97    }
98    if ( !isset($c->readonly_webdav_collections) || $c->readonly_webdav_collections == true ) {
99      if ( $qry->rows() == 0 ) {
100        $request->DoResponse( 405 ); // Method not allowed
101      }
102      return;
103    }
104    if ( $qry->rows() == 0 ) {
105      if ( $public == true ) $public = 't'; else $public = 'f';
106      if ( preg_match( '{^(.*/)([^/]+)/$}', $request_container, $matches ) ) {
107        $parent_container = $matches[1];
108        $displayname = $matches[2];
109      }
110      $sql = 'INSERT INTO collection ( user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, created, modified, publicly_readable, resourcetypes )
111VALUES( :user_no, :parent_container, :dav_name, :dav_etag, :dav_displayname, TRUE, current_timestamp, current_timestamp, :is_public::boolean, :resourcetypes )';
112      $params = array(
113      ':user_no' => $user_no,
114      ':parent_container' => $parent_container,
115      ':dav_name' => $request_container,
116      ':dav_etag' => md5($user_no. $request_container),
117      ':dav_displayname' => $displayname,
118      ':is_public' => $public,
119      ':resourcetypes' => '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>'
120      );
121      $qry->QDo( $sql, $params );
122    }
123    else if ( isset($public) ) {
124      $collection = $qry->Fetch();
125      $sql = 'UPDATE collection SET publicly_readable = :is_public::boolean WHERE collection_id = :collection_id';
126      $params = array( ':is_public' => ($public?'t':'f'), ':collection_id' => $collection->collection_id );
127      if ( ! $qry->QDo($sql,$params) ) {
128        rollback_on_error( $caldav_context, $user_no, $path );
129      }
130    }
131  }
132}
133
134
135/**
136* Check if this collection should force all events to be PUBLIC.
137* @param string $user_no the user that owns the collection
138* @param string $dav_name the collection to check
139* @return boolean Return true if public events only are allowed.
140*/
141function public_events_only( $user_no, $dav_name ) {
142  global $c;
143
144  $sql = 'SELECT public_events_only FROM collection WHERE dav_name = :dav_name';
145
146  $qry = new AwlQuery($sql, array(':dav_name' => $dav_name) );
147
148  if( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 1 ) {
149    $collection = $qry->Fetch();
150
151    if ($collection->public_events_only == 't') {
152      return true;
153    }
154  }
155
156  // Something went wrong, must be false.
157  return false;
158}
159
160
161/**
162* Deliver scheduling requests to attendees
163* @param iCalComponent $ical the VCALENDAR to deliver
164*/
165function handle_schedule_request( $ical ) {
166  global $c, $session, $request;
167  $resources = $ical->GetComponents('VTIMEZONE',false);
168  $ic = $resources[0];
169  $etag = md5 ( $request->raw_post );
170  $reply = new XMLDocument( array("DAV:" => "", "urn:ietf:params:xml:ns:caldav" => "C" ) );
171  $responses = array();
172
173  $attendees = $ic->GetProperties('ATTENDEE');
174  $wr_attendees = $ic->GetProperties('X-WR-ATTENDEE');
175  if ( count ( $wr_attendees ) > 0 ) {
176    dbg_error_log( "POST", "Non-compliant iCal request.  Using X-WR-ATTENDEE property" );
177    foreach( $wr_attendees AS $k => $v ) {
178      $attendees[] = $v;
179    }
180  }
181  dbg_error_log( "POST", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
182
183  foreach( $attendees AS $k => $attendee ) {
184    $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
185    if ( $attendee_email == $request->principal->email ) {
186      dbg_error_log( "POST", "not delivering to owner" );
187      continue;
188    }
189    if ( $attendee->GetParameterValue ( 'PARTSTAT' ) != 'NEEDS-ACTION' || preg_match ( '/^[35]\.[3-9]/',  $attendee->GetParameterValue ( 'SCHEDULE-STATUS' ) ) ) {
190      dbg_error_log( "POST", "attendee %s does not need action", $attendee_email );
191      continue;
192    }
193
194    dbg_error_log( "POST", "Delivering to %s", $attendee_email );
195
196    $attendee_principal = new CalDAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
197    if ( $attendee_principal == false ){
198      $attendee->SetParameterValue ('SCHEDULE-STATUS','3.7;Invalid Calendar User');
199      continue;
200    }
201    $deliver_path = preg_replace ( '/^.*caldav.php/','', $attendee_principal->schedule_inbox_url );
202
203    $ar = new DAVResource($deliver_path);
204    $priv =  $ar->HavePrivilegeTo('schedule-deliver-invite' );
205    if ( ! $ar->HavePrivilegeTo('schedule-deliver-invite' ) ){
206      $reply = new XMLDocument( array('DAV:' => '') );
207      $privnodes = array( $reply->href(ConstructURL($attendee_principal->schedule_inbox_url)), new XMLElement( 'privilege' ) );
208      // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
209      $reply->NSElement( $privnodes[1], 'schedule-deliver-invite' );
210      $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
211      $xmldoc = $reply->Render('error',$xml);
212      $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"');
213    }
214
215
216    $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
217    $ncal = new iCalComponent (  );
218    $ncal->VCalendar ();
219    $ncal->AddProperty ( 'METHOD', 'REQUEST' );
220    $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
221    $content = $ncal->Render();
222    $cid = $ar->GetProperty('collection_id');
223    dbg_error_log('DELIVER', 'to user: %s, to path: %s, collection: %s, from user: %s, caldata %s', $attendee_principal->user_no, $deliver_path, $cid, $request->user_no, $content );
224    write_resource( $attendee_principal->user_no, $deliver_path . $etag . '.ics' ,
225      $content , $ar->GetProperty('collection_id'), $request->user_no,
226      md5($content), $ncal, $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
227    $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
228  }
229        // don't write an entry in the out box, ical doesn't delete it or ever read it again
230  $ncal = new iCalComponent (  );
231  $ncal->VCalendar ();
232  $ncal->AddProperty ( 'METHOD', 'REQUEST' );
233  $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
234  $content = $ncal->Render();
235        $deliver_path = preg_replace ( '/^.*caldav.php/','', $request->principal->schedule_inbox_url );
236  $ar = new DAVResource($deliver_path);
237  write_resource( $request->user_no, $deliver_path . $etag . '.ics' ,
238    $content , $ar->GetProperty('collection_id'), $request->user_no,
239    md5($content), $ncal, $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
240  //$etag = md5($content);
241  header('ETag: "'. $etag . '"' );
242  header('Schedule-Tag: "'.$etag . '"' );
243  $request->DoResponse( 201, 'Created' );
244}
245
246/**
247* Deliver scheduling replies to organizer and other attendees
248* @param iCalComponent $ical the VCALENDAR to deliver
249* @return false on error
250*/
251function handle_schedule_reply ( $ical ) {
252  global $c, $session, $request;
253  $resources = $ical->GetComponents('VTIMEZONE',false);
254  $ic = $resources[0];
255  $etag = md5 ( $request->raw_post );
256        $organizer = $ic->GetProperties('ORGANIZER');
257        // for now we treat events with out organizers as an error
258        if ( count ( $organizer ) < 1 )
259                return false;
260  $attendees = array_merge($organizer,$ic->GetProperties('ATTENDEE'));
261  $wr_attendees = $ic->GetProperties('X-WR-ATTENDEE');
262  if ( count ( $wr_attendees ) > 0 ) {
263    dbg_error_log( "POST", "Non-compliant iCal request.  Using X-WR-ATTENDEE property" );
264    foreach( $wr_attendees AS $k => $v ) {
265      $attendees[] = $v;
266    }
267  }
268  dbg_error_log( "POST", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
269
270  foreach( $attendees AS $k => $attendee ) {
271          $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
272          dbg_error_log( "POST", "Delivering to %s", $attendee_email );
273          $attendee_principal = new CalDAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
274          $deliver_path = preg_replace ( '/^.*caldav.php/','', $attendee_principal->schedule_inbox_url );
275          $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
276    if ( $attendee_email == $request->principal->email ) {
277      dbg_error_log( "POST", "not delivering to owner" );
278      continue;
279    }
280          $ar = new DAVResource($deliver_path);
281          if ( ! $ar->HavePrivilegeTo('schedule-deliver-reply' ) ){
282            $reply = new XMLDocument( array('DAV:' => '') );
283             $privnodes = array( $reply->href(ConstructURL($attendee_principal->schedule_inbox_url)), new XMLElement( 'privilege' ) );
284             // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
285             $reply->NSElement( $privnodes[1], 'schedule-deliver-reply' );
286             $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
287             $xmldoc = $reply->Render('error',$xml);
288                         $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
289                         continue;
290          }
291
292          $ncal = new iCalComponent (  );
293          $ncal->VCalendar ();
294          $ncal->AddProperty ( 'METHOD', 'REPLY' );
295          $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
296          $content = $ncal->Render();
297          write_resource( $attendee_principal->user_no, $deliver_path . $etag . '.ics' ,
298            $content , $ar->GetProperty('collection_id'), $request->user_no,
299            md5($content), $ncal, $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
300        }
301  $request->DoResponse( 201, 'Created' );
302}
303
304
305
306
307/**
308* Create a scheduling request in the schedule inbox for the
309* @param iCalComponent $resource The VEVENT/VTODO/... resource we are scheduling
310* @param iCalProp $attendee The attendee we are scheduling
311* @return float The result of the scheduling request, per caldav-sched #3.5.4
312*/
313function write_scheduling_request( &$resource, $attendee ) {
314  $response = '5.3;'.translate('No scheduling support for user');
315  return '"'.$response.'"';
316}
317
318/**
319* Create scheduling requests in the schedule inbox for the
320* @param iCalComponent $resource The VEVENT/VTODO/... resource we are scheduling
321*/
322function create_scheduling_requests( &$resource ) {
323  if ( ! is_object($resource) ) {
324    dbg_error_log( 'PUT', 'create_scheduling_requests called with non-object parameter (%s)', gettype($resource) );
325    return;
326  }
327
328  $attendees = $resource->GetPropertiesByPath('/VCALENDAR/*/ATTENDEE');
329        $wr_attendees = $resource->GetPropertiesByPath('/VCALENDAR/*/X-WR-ATTENDEE');
330        if ( count ( $wr_attendees ) > 0 ) {
331    dbg_error_log( 'POST', 'Non-compliant iCal request.  Using X-WR-ATTENDEE property' );
332    foreach( $wr_attendees AS $k => $v ) {
333      $attendees[] = $v;
334    }
335  }
336  if ( count($attendees) == 0 ) {
337    dbg_error_log( 'PUT', 'Event has no attendees - no scheduling required.', count($attendees) );
338    return;
339  }
340
341  dbg_error_log( 'PUT', 'Adding to scheduling inbox %d attendees', count($attendees) );
342  foreach( $attendees AS $attendee ) {
343    $attendee->SetParameterValue( 'SCHEDULE-STATUS', write_scheduling_request( $resource, $attendee->Value() ) );
344  }
345}
346
347
348/**
349* Update scheduling requests in the schedule inbox for the
350* @param iCalComponent $resource The VEVENT/VTODO/... resource we are scheduling
351*/
352function update_scheduling_requests( &$resource ) {
353  if ( ! is_object($resource) ) {
354    dbg_error_log( 'PUT', 'update_scheduling_requests called with non-object parameter (%s)', gettype($resource) );
355    return;
356  }
357
358  $attendees = $resource->GetPropertiesByPath('/VCALENDAR/*/ATTENDEE');
359        $wr_attendees = $resource->GetPropertiesByPath('/VCALENDAR/*/X-WR-ATTENDEE');
360        if ( count ( $wr_attendees ) > 0 ) {
361    dbg_error_log( 'POST', 'Non-compliant iCal request.  Using X-WR-ATTENDEE property' );
362    foreach( $wr_attendees AS $k => $v ) {
363      $attendees[] = $v;
364    }
365  }
366  if ( count($attendees) == 0 ) {
367    dbg_error_log( 'PUT', 'Event has no attendees - no scheduling required.', count($attendees) );
368    return;
369  }
370
371  dbg_error_log( 'PUT', 'Adding to scheduling inbox %d attendees', count($attendees) );
372  foreach( $attendees AS $attendee ) {
373    $attendee->SetParameterValue( 'SCHEDULE-STATUS', write_scheduling_request( $resource, $attendee->Value() ) );
374  }
375}
376
377
378/**
379* This function will import a whole calendar
380* @param string $ics_content the ics file to import
381* @param int $user_no the user wich will receive this ics file
382* @param string $path the $path where it will be store such as /user_foo/home/
383* @param boolean $caldav_context Whether we are responding via CalDAV or interactively
384*
385* Any VEVENTs with the same UID will be concatenated together
386*/
387function import_collection( $ics_content, $user_no, $path, $caldav_context, $appending = false ) {
388  global $c, $session, $tz_regex;
389
390  if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || isset($c->dbg['put'])) ) {
391    $fh = fopen('/tmp/PUT-2.txt','w');
392    if ( $fh ) {
393      fwrite($fh,$ics_content);
394      fclose($fh);
395    }
396  }
397
398  $calendar = new iCalComponent($ics_content);
399  $timezones = $calendar->GetComponents('VTIMEZONE',true);
400  $components = $calendar->GetComponents('VTIMEZONE',false);
401
402  $displayname = $calendar->GetPValue('X-WR-CALNAME');
403  if ( !$appending && isset($displayname) ) {
404    $sql = 'UPDATE collection SET dav_displayname = :displayname WHERE dav_name = :dav_name';
405    $qry = new AwlQuery( $sql, array( ':displayname' => $displayname, ':dav_name' => $path) );
406    if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
407  }
408
409  $tz_ids    = array();
410  foreach( $timezones AS $k => $tz ) {
411    $tz_ids[$tz->GetPValue('TZID')] = $k;
412  }
413
414  /** Build an array of resources.  Each resource is an array of iCalComponent */
415  $resources = array();
416  foreach( $components AS $k => $comp ) {
417    $uid = $comp->GetPValue('UID');
418    if ( $uid == null || $uid == '' ) continue;
419    if ( !isset($resources[$uid]) ) $resources[$uid] = array();
420    $resources[$uid][] = $comp;
421
422    /** Ensure we have the timezone component for this in our array as well */
423    $tzid = $comp->GetPParamValue('DTSTART', 'TZID');
424    if ( !isset($tzid) || $tzid == '' ) $tzid = $comp->GetPParamValue('DUE','TZID');
425    if ( !isset($resources[$uid][$tzid]) && isset($tz_ids[$tzid]) ) {
426      $resources[$uid][$tzid] = $timezones[$tz_ids[$tzid]];
427    }
428  }
429
430
431  $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
432  $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
433  if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
434  if ( ! $qry->rows() == 1 ) {
435    dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
436    rollback_on_error( $caldav_context, $user_no, $path );
437  }
438  $collection = $qry->Fetch();
439
440  if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
441  $base_params = array( ':collection_id' => $collection->collection_id );
442  if ( !$appending ) {
443    if ( !$qry->QDo('DELETE FROM calendar_item WHERE collection_id = :collection_id', $base_params)
444      || !$qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id', $base_params) )
445      rollback_on_error( $caldav_context, $user_no, $collection->collection_id );
446  }
447
448  $dav_data_insert = <<<EOSQL
449INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
450    VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, current_timestamp, current_timestamp, :collection_id )
451EOSQL;
452
453  $calitem_insert = <<<EOSQL
454INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp, dtstart, dtend, summary, location, class, transp,
455                    description, rrule, tz_id, last_modified, url, priority, created, due, percent_complete, status, collection_id )
456    VALUES ( :user_no, :dav_name, currval('dav_id_seq'), :etag, :uid, :dtstamp, :dtstart, ##dtend##, :summary, :location, :class, :transp,
457                :description, :rrule, :tzid, :modified, :url, :priority, :created, :due, :percent_complete, :status, :collection_id)
458EOSQL;
459
460  $last_tz_locn = '';
461  foreach( $resources AS $uid => $resource ) {
462    if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
463
464    /** Construct the VCALENDAR data */
465    $vcal = new iCalComponent();
466    $vcal->VCalendar();
467    $vcal->SetComponents($resource);
468    create_scheduling_requests($vcal);
469    $icalendar = $vcal->Render();
470
471    /** As ever, we mostly deal with the first resource component */
472    $first = $resource[0];
473
474    $dav_data_params = $base_params;
475    $dav_data_params[':user_no'] = $user_no;
476    $dav_data_params[':dav_name'] = sprintf( '%s%s.ics', $path, $uid );
477    $dav_data_params[':etag'] = md5($icalendar);
478    $calitem_params = $dav_data_params;
479    $dav_data_params[':dav_data'] = $icalendar;
480    $dav_data_params[':caldav_type'] = $first->GetType();
481    $dav_data_params[':session_user'] = $session->user_no;
482    if ( !$qry->QDo($dav_data_insert,$dav_data_params) ) rollback_on_error( $caldav_context, $user_no, $path );
483
484    $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
485    if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
486      $dav_id = $row->dav_id;
487    }
488
489    $dtstart = $first->GetPValue('DTSTART');
490    $calitem_params[':dtstart'] = $dtstart;
491    if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
492      $dtstart = $first->GetPValue('DUE');
493    }
494
495    $dtend = $first->GetPValue('DTEND');
496    if ( isset($dtend) && $dtend != '' ) {
497      dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
498      $calitem_params[':dtend'] = $dtend;
499      $dtend = ':dtend';
500    }
501    else {
502      $dtend = 'NULL';
503      if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
504        $duration = preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') );
505        $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
506        $calitem_params[':duration'] = $duration;
507      }
508      elseif ( $first->GetType() == 'VEVENT' ) {
509        /**
510        * From RFC2445 4.6.1:
511        * For cases where a "VEVENT" calendar component specifies a "DTSTART"
512        * property with a DATE data type but no "DTEND" property, the events
513        * non-inclusive end is the end of the calendar date specified by the
514        * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
515        * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
516        * the event ends on the same calendar date and time of day specified by the
517        * "DTSTART" property.
518        *
519        * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
520        *
521        */
522        $value_type = $first->GetPParamValue('DTSTART','VALUE');
523        dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
524        if ( isset($value_type) && $value_type == 'DATE' )
525          $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
526        else
527          $dtend = ':dtstart';
528      }
529    }
530
531    $last_modified = $first->GetPValue('LAST-MODIFIED');
532    if ( !isset($last_modified) || $last_modified == '' ) $last_modified = gmdate( 'Ymd\THis\Z' );
533    $calitem_params[':modified'] = $last_modified;
534
535    $dtstamp = $first->GetPValue('DTSTAMP');
536    if ( !isset($dtstamp) || $dtstamp == '' ) $dtstamp = $last_modified;
537    $calitem_params[':dtstamp'] = $dtstamp;
538
539    /** RFC2445, 4.8.1.3: Default is PUBLIC, or also if overridden by the collection settings */
540    $class = ($collection->public_events_only == 't' ? 'PUBLIC' : $first->GetPValue('CLASS') );
541    if ( !isset($class) || $class == '' ) $class = 'PUBLIC';
542    $calitem_params[':class'] = $class;
543
544
545    /** Calculate what timezone to set, first, if possible */
546    $tzid = $first->GetPParamValue('DTSTART','TZID');
547    if ( !isset($tzid) || $tzid == '' ) $tzid = $first->GetPParamValue('DUE','TZID');
548    if ( isset($tzid) && $tzid != '' ) {
549      if ( isset($resource[$tzid]) ) {
550        $tz = $resource[$tzid];
551        $tz_locn = $tz->GetPValue('X-LIC-LOCATION');
552      }
553      else {
554        unset($tz);
555        unset($tz_locn);
556      }
557      if ( ! isset($tz_locn) || ! preg_match( $tz_regex, $tz_locn ) ) {
558        if ( preg_match( '#([^/]+/[^/]+)$#', $tzid, $matches ) ) {
559          $tz_locn = $matches[1];
560        }
561      }
562      dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($tz_locn) ? $tz_locn : '') );
563      if ( isset($tz_locn) && ($tz_locn != $last_tz_locn) && preg_match( $tz_regex, $tz_locn ) ) {
564        dbg_error_log( 'PUT', ' Setting timezone to %s', $tz_locn );
565        if ( $tz_locn != '' ) {
566          $qry->QDo('SET TIMEZONE TO \''.$tz_locn."'" );
567        }
568        $last_tz_locn = $tz_locn;
569      }
570      $params = array( ':tzid' => $tzid);
571      $qry = new AwlQuery('SELECT tz_locn FROM time_zone WHERE tz_id = :tzid', $params );
572      if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
573        $params[':tzlocn'] = $tz_locn;
574        $params[':tzspec'] = (isset($tz) ? $tz->Render() : null );
575        $qry->QDo('INSERT INTO time_zone (tz_id, tz_locn, tz_spec) VALUES(:tzid,:tzlocn,:tzspec)', $params );
576      }
577      if ( !isset($tz_locn) || $tz_locn == '' ) $tz_locn = $tzid;
578    }
579    else {
580      $tzid = null;
581    }
582
583    $sql = str_replace( '##dtend##', $dtend, $calitem_insert );
584    $calitem_params[':tzid'] = $tzid;
585    $calitem_params[':uid'] = $first->GetPValue('UID');
586    $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
587    $calitem_params[':location'] = $first->GetPValue('LOCATION');
588    $calitem_params[':transp'] = $first->GetPValue('TRANSP');
589    $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
590    $calitem_params[':rrule'] = $first->GetPValue('RRULE');
591    $calitem_params[':url'] = $first->GetPValue('URL');
592    $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
593    $calitem_params[':due'] = $first->GetPValue('DUE');
594    $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
595    $calitem_params[':status'] = $first->GetPValue('STATUS');
596
597    $created = $first->GetPValue('CREATED');
598    if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
599    $calitem_params[':created'] = $created;
600
601    if ( !$qry->QDo($sql,$calitem_params) ) rollback_on_error( $caldav_context, $user_no, $path);
602
603    write_alarms($dav_id, $first);
604    write_attendees($dav_id, $first);
605
606    create_scheduling_requests( $vcal );
607    if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
608  }
609
610  if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
611    if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
612  }
613}
614
615
616/**
617* Given a dav_id and an original iCalComponent, pull out each of the VALARMs
618* and write the values into the calendar_alarm table.
619*
620* @param int $dav_id The dav_id of the caldav_data we're processing
621* @param iCalComponent The VEVENT or VTODO containing the VALARM
622* @return null
623*/
624function write_alarms( $dav_id, $ical ) {
625  $qry = new AwlQuery('DELETE FROM calendar_alarm WHERE dav_id = '.$dav_id );
626  $qry->Exec('PUT',__LINE__,__FILE__);
627
628  $alarms = $ical->GetComponents('VALARM');
629  if ( count($alarms) < 1 ) return;
630
631  $qry->SetSql('INSERT INTO calendar_alarm ( dav_id, action, trigger, summary, description, component, next_trigger )
632          VALUES( '.$dav_id.', :action, :trigger, :summary, :description, :component,
633                                      :related::timestamp with time zone + :related_trigger::interval )' );
634  $qry->Prepare();
635  foreach( $alarms AS $v ) {
636    $trigger = array_merge($v->GetProperties('TRIGGER'));
637    $trigger = $trigger[0];
638    $related = null;
639    $related_trigger = '0M';
640    $trigger_type = $trigger->GetParameterValue('VALUE');
641    if ( !isset($trigger_type) || $trigger_type == 'DURATION' ) {
642      switch ( $trigger->GetParameterValue('RELATED') ) {
643        case 'DTEND':  $related = $ical->GetPValue('DTEND'); break;
644        case 'DUE':    $related = $ical->GetPValue('DUE');   break;
645        default:       $related = $ical->GetPValue('DTSTART');
646      }
647      $duration = $trigger->Value();
648      $minus = (substr($duration,0,1) == '-');
649      $related_trigger = trim(preg_replace( '#[PT-]#', ' ', $duration ));
650      if ( $minus ) {
651        $related_trigger = preg_replace( '{(\d+[WDHMS])}', '-$1 ', $related_trigger );
652      }
653    }
654    $qry->Bind(':action', $v->GetPValue('ACTION'));
655    $qry->Bind(':trigger', $trigger->Render());
656    $qry->Bind(':summary', $v->GetPValue('SUMMARY'));
657    $qry->Bind(':description', $v->GetPValue('DESCRIPTION'));
658    $qry->Bind(':component', $v->Render());
659    $qry->Bind(':related', $related );
660    $qry->Bind(':related_trigger', $related_trigger );
661    $qry->Exec('PUT',__LINE__,__FILE__);
662  }
663}
664
665
666/**
667* Parse out the attendee property and write a row to the
668* calendar_attendee table for each one.
669* @param int $dav_id The dav_id of the caldav_data we're processing
670* @param iCalComponent The VEVENT or VTODO containing the ATTENDEEs
671* @return null
672*/
673function write_attendees( $dav_id, $ical ) {
674  $qry = new AwlQuery('DELETE FROM calendar_attendee WHERE dav_id = '.$dav_id );
675  $qry->Exec('PUT',__LINE__,__FILE__);
676
677  $attendees = $ical->GetProperties('ATTENDEE');
678  if ( count($attendees) < 1 ) return;
679
680  $qry->SetSql('INSERT INTO calendar_attendee ( dav_id, status, partstat, cn, attendee, role, rsvp, property )
681          VALUES( '.$dav_id.', :status, :partstat, :cn, :attendee, :role, :rsvp, :property )' );
682  $qry->Prepare();
683  $processed = array();
684  foreach( $attendees AS $v ) {
685    $attendee = $v->Value();
686    if ( isset($processed[$attendee]) ) {
687      dbg_error_log( 'LOG', 'Duplicate attendee "%s" in resource "%d"', $attendee, $dav_id );
688      dbg_error_log( 'LOG', 'Original:  "%s"', $processed[$attendee] );
689      dbg_error_log( 'LOG', 'Duplicate: "%s"', $v->Render() );
690      continue; /** @TODO: work out why we get duplicate ATTENDEE on one VEVENT */
691    }
692    $qry->Bind(':attendee', $attendee );
693    $qry->Bind(':status',   $v->GetParameterValue('STATUS') );
694    $qry->Bind(':partstat', $v->GetParameterValue('PARTSTAT') );
695    $qry->Bind(':cn',       $v->GetParameterValue('CN') );
696    $qry->Bind(':role',     $v->GetParameterValue('ROLE') );
697    $qry->Bind(':rsvp',     $v->GetParameterValue('RSVP') );
698    $qry->Bind(':property', $v->Render() );
699    $qry->Exec('PUT',__LINE__,__FILE__);
700    $processed[$attendee] = $v->Render();
701  }
702}
703
704
705/**
706* Actually write the resource to the database.  All checking of whether this is reasonable
707* should be done before this is called.
708* @param int $user_no The user_no owning this resource on the server
709* @param string $path The path to the resource being written
710* @param string $caldav_data The actual resource to be written
711* @param int $collection_id The ID of the collection containing the resource being written
712* @param int $author The user_no who wants to put this resource on the server
713* @param string $etag An etag unique for this event
714* @param object $ic The parsed iCalendar object
715* @param string $put_action_type INSERT or UPDATE depending on what we are to do
716* @param boolean $caldav_context True, if we are responding via CalDAV, false for other ways of calling this
717* @param string Either 'INSERT' or 'UPDATE': the type of action we are doing
718* @param boolean $log_action Whether to log the fact that we are writing this into an action log (if configured)
719* @param string $weak_etag An etag that is NOT modified on ATTENDEE changes for this event
720* @return boolean True for success, false for failure.
721*/
722function write_resource( $user_no, $path, $caldav_data, $collection_id, $author, $etag, $ic, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
723  global $tz_regex;
724
725  $resources = $ic->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
726  if ( !isset($resources[0]) ) {
727    $resource_type = 'Unknown';
728    /** @TODO: Handle writing non-calendar resources, like address book entries or random file data */
729    rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
730    return false;
731  }
732  else {
733     if( count($resources) == 2)
734          $first = $resources[1];
735     else
736          $first = $resources[0];
737     $resource_type = $first->GetType();
738  }
739 
740  unset($put_action_type);
741  $nome = substr($user_no, 0, 9);
742  $UID = $first->GetPValue('UID');
743  $CALID = strtok($UID,"@");
744  $proprietario = strtok("@");
745  $qry = new AwlQuery("SELECT * FROM phpgw_cal_user WHERE cal_login=:nome AND cal_id=:CALID AND cal_status='A' AND cal_type='u' ", array(':nome' => $nome , ':CALID' => $CALID));
746  $qry->Exec("PUT");
747  if ($qry->rows() < 1) {
748                $qrycompa = new AwlQuery("SELECT * FROM phpgw_cal  WHERE cal_id=:CALID AND owner=:nome ", array(':CALID' => $CALID, ':nome' => $nome));
749                $qrycompa->Exec("PUT");
750                if ($qrycompa->rows() < 1) {
751                        $put_action_type = 'INSERT';
752                } else {
753                        //$put_action_type = 'UPDATE';
754                        $put_action_type = 'NDA';
755                }
756     }
757  elseif ($qry->rows() == 1) {
758                $put_action_type = 'UPDATE';
759    }
760           
761        $second = $first->GetComponents('VALARM');
762        if(count($second) >= 1)
763        { 
764            $alarme_time = $second[0]->GetPValue('TRIGGER');
765        }
766        $alarme_descarta = $first->GetPValue('X-MOZ-LASTACK');
767        $start = $first->GetPValue('DTSTART');
768        $dateTime = date_create($start);
769        $HJ = date("Y-m-d 00:00:00");
770        $hoje = date_create($HJ);
771        $hj_seg = $hoje->format("U");
772        //date_format( $dateTime, 2000, 12, 12);
773        $DT_START = $dateTime->format("U");
774        $hora = $dateTime->format("G");
775        $horas_seg = $hora * 60 * 60;
776        $minuto = $dateTime->format("i");
777        $min_seg = $minuto * 60;
778        $total_seg = $horas_seg + $min_seg;
779        $alarme_data = $total_seg + $hj_seg;
780
781         $end = $first->GetPValue('DTEND');
782        $dateTime_end = date_create($end);
783        ///date_format( $dateTime, 2000, 12, 12);
784        $DT_END = $dateTime_end->format("U");
785        $execao = $first->GetProperties('EXDATE');
786        $modify = $first->GetPValue('LAST-MODIFIED');
787        $dateTime_mod = date_create($modify);
788        //date_format( $dateTime, 2000, 12, 12);
789        $MOD = $dateTime_mod->format("U");
790        $seg = $alarme_data * 1000000;
791        $snooze = "X-MOZ-SNOOZE-TIME";
792        //if(count($second) >= 1){
793        $adia_alarme = $first->GetPValue("$snooze");
794        //dbg_error_log("PUT", "ADIA alarme: '%s' ", $adia_alarme);
795        //} 
796        $prioridade = $first->GetPValue('PRIORITY');
797        if ($prioridade == "") {
798                $prioridade = 1;
799        }
800        $RECUR = $first->GetPValue('RRULE');
801
802        $categoria_utf8 = $first->GetPValue('CATEGORIES');
803        $categoria = utf8_decode($categoria_utf8);
804        if ($RECUR == null) {
805                $tipo = E;
806        } else {
807                $tipo = M;
808        }
809
810        // EXDATE:20081126T190000Z
811        //Adicionado por Umberto
812        //Permite exclusão de varias recorrencias.
813        if ( is_array($execao)) {
814                foreach( $execao AS $k => $v ) {
815                        //$dateTime = date_create($deletarecorrencia);
816                        //$EXEC = $dateTime->format("U");
817                        $EXEC = dataTzParaSegundos($v->value());
818                        $TOTAL = "$TOTAL,$EXEC";
819                }
820                $EXEC = trim($TOTAL,",");
821
822        } else {
823                $EXEC = "";
824        }
825        //Fim da edição por Umberto
826        $titulo_utf8 =  $first->GetPValue('SUMMARY');
827        $titulo = utf8_decode($titulo_utf8);
828        $descricao_utf8 = preg_replace('/\n/', "\r\n",  $first->GetPValue('DESCRIPTION'));
829        $descricao = utf8_decode($descricao_utf8);
830        $recur_id = $first->GetPValue('RECURRENCE-ID');
831        $cidade_utf8 =  $first->GetPValue('LOCATION');
832        $cidade = utf8_decode($cidade_utf8);
833        $iporigem = getenv("REMOTE_ADDR");
834        $class =  $first->GetPValue('CLASS');
835        if ($class == 'PRIVATE') {
836                $public = 0;
837        } else {
838                $public = 1;
839        }
840        //############## Categoria ##################                           
841        if ( $categoria != ""){                                                 
842                $x= "select * from phpgw_categories WHERE cat_name = :categoria";
843                $phpgw_query = new AwlQuery($x,array(':categoria' => $categoria));                                   
844                $phpgw_query->Exec();                                             
845                if ( $phpgw_query->rows() == 0 ) {                                   
846                    $qry = new AwlQuery("INSERT INTO phpgw_categories (cat_id,cat_main,cat_parent,cat_level,cat_owner,cat_access,cat_appname,cat_name,cat_description,cat_data,last_mod) VALUES ( default,default,default,default,:nome,'private','calendar',:categoria,'','N;',:mod)", array(':nome' => $nome, ':categoria' => $categoria, ':mod' => $MOD));                                                                                                                                                                                         
847                    if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                           
848                    $x= "select * from phpgw_categories WHERE cat_name = '$categoria'";                                                                                                                                                     
849                    $phpgw_query =  new AwlQuery($x,array(':categoria' => $categoria));                                                                                                                                                                                         
850                    $phpgw_query->Exec();                                                                                                                                                                                                   
851                    $categg = $phpgw_query->Fetch();                                                                                                                                                                                         
852                    $category_id = $categg->cat_id;                                                                                                                                                                                         
853                   }
854                 else
855                   { while ($categgg = $phpgw_query->Fetch())
856                      {                                     
857                        if ( $categgg->cat_access == 'public' || $categgg->cat_owner == "$nome")
858                         {                                                                     
859                            $category_id = $categgg->cat_id;                                   
860                         }                                                                     
861                        else                                                                   
862                         { $category_id ="";                                                   
863                         }                                                                     
864                       }                                                                       
865                   }                                                                           
866         }                                                                                     
867        else                                                                                   
868         {                                                                                     
869            $category_id ="";                                                                   
870          }                                                                                     
871
872        //################# ALARME ##################
873
874        $tipo_data = substr($alarme_time, -1);
875        switch ($tipo_data) {                 
876                case "M":                     
877                        $valor = 60;         
878                        $tamanho = strlen($alarme_time);
879                        if ($tamanho == 6) {           
880                                $minutos = substr($alarme_time, 3, 5);
881                                $reducao = $minutos * $valor;         
882                        } else {                                     
883                                $minutos = substr($alarme_time, 3, 4);
884                                $reducao = $minutos * $valor;         
885                        }                                             
886                        break;                                       
887                case "H":                                             
888                        $valor = 60;                                 
889                        $tamanho = strlen($alarme_time);             
890                        if ($tamanho == 6) {                         
891                                $horas = substr($alarme_time, 3, 5); 
892                                $reducao = $horas * $valor * $valor; 
893                        } else {                                     
894                                $horas = substr($alarme_time, 3, 4); 
895                                $reducao = $horas * $valor * $valor; 
896                        }                                             
897                        break;                                       
898                case "D":                                             
899                        $valor = 60;                                 
900                        $num_horas = 24;                             
901                        $tamanho = strlen($alarme_time);             
902                        if ($tamanho == 5) {                         
903                                $dias = substr($alarme_time, 2, 4);   
904                                $reducao = $dias * $valor * $valor * $num_horas;
905                        } else {                                               
906                                $dias = substr($alarme_time, 2, 3);             
907                                $reducao = $dias * $valor * $valor * $num_horas;
908                        }                                                       
909                        break;                                                 
910                case "W":                                                       
911                        $valor = 60;                                           
912                        $num_horas = 24;                                       
913                        $num_dias = 7;                                         
914                        $tamanho = strlen($alarme_time);                       
915                        if ($tamanho == 5) {                                   
916                                $semanas = substr($alarme_time, 2, 4);         
917                                $reducao = $semanas * $valor * $valor * $num_horas * $num_dias;
918                        } else {                                                               
919                                $semanas = substr($alarme_time, 2, 3);                         
920                                $reducao = $semanas * $valor * $valor * $num_horas * $num_dias;
921                        }                                                                     
922                case "S":                                                                     
923                        continue;                                                             
924        }                                                                                     
925
926        $alarme = $DT_START - $reducao;
927        // ########### participantes ######################
928        $participantes =  $first->GetProperties('ATTENDEE');             
929        //$test = $ic->component->FirstNonTimezone();     
930        //$propriedades = $test->GetProperties('PARTSTAT');
931        //foreach ($propriedades as $k => $c){             
932        //}                                                   
933        dbg_log_array( "PUTTTTTT", 'PARTICIPANTES ', $participantes, true ); 
934        $mails = "";
935        $part = array();
936        $estado = array();
937        if (is_array($participantes)) {
938                $email=$nome;         
939                foreach($participantes AS $k => $v) {
940                        $user = $v->content;         
941                        list($aviso, $mail) = split(":", $user, 2);
942                        $filtro = "mail=$mail";                   
943                        $email=$email.",".$mail;                   
944                        $atributos = array("uidNumber");           
945                        //$atrr = new  ldapDrivers($c->authenticate_hook['config']);
946                        if (strlen($filtro) > 5){                                   
947                                $usuario = ldapDrivers::requestAtributo($filtro, $atributos);
948                                if ($usuario != false) {                                     
949                                        $part[$k] = $usuario['uidNumber'];                                         
950                                        $stat = $v->GetParameterValue('PARTSTAT');                                 
951                                        switch ($stat){                                                           
952                                                case "NEEDS-ACTION": $estado[$k] = 'U';                           
953                                                        break;                                                     
954                                                case "ACCEPTED": $estado[$k] = 'A';                               
955                                                        break;                                                     
956                                                case "DECLINED": $estado[$k] = 'R';                               
957                                                        break;                                                     
958                                                case "TENTATIVE": $estado[$k] = 'T';                               
959                                                        break;                                                     
960                                        }
961                                  dbg_error_log("PUT", "usuario participante: '%s' status '%s' e token '%d' ", $part[$k],$stat,$k);
962                                } else {
963                                        $mails = $mails . "$mail,";                                               
964                                }                                                                                 
965                        }                                                                                         
966                }                                                                                                 
967        } elseif (strlen($participantes) > 1) {                                                                   
968                $part = array();                                                                                   
969                list($aviso, $mail) = split(":", $participantes, 2);                                               
970                $filtro = "mail=$mail";                                                                           
971                $email=$email.",".$mail;                                                                           
972                $atributos = array("uidNumber");                                                                   
973                if (strlen($filtro) > 5){                                                                         
974                        $usuario = ldapDrivers::requestAtributo($filtro, $atributos);                             
975                        if ($usuario != false) {                                                                   
976                                $part[0] = $usuario['uidNumber'];                                                 
977                                $teste = $first->CollectParameterValues('PARTSTAT');                           
978                                foreach( $teste as $k => $v){                                                         
979                                        $stat = $k;                                                                   
980                                        }                                                                             
981                                switch ($stat){                                                                       
982                                        case "NEEDS-ACTION": $estado[0] = 'U';                                         
983                                                break;                                                                 
984                                        case "ACCEPTED": $estado[0] = 'A';                                             
985                                                break;                                                                 
986                                        case "DECLINED": $estado[0] = 'R';                                             
987                                                break;                                                                 
988                                        case "TENTATIVE": $estado[0] = 'T';                                           
989                                                break;                                                                 
990                                }                                                                                     
991
992                        } else {
993                                $mails = $mail;
994                        }                     
995                }                             
996        }
997                   
998        $email = trim($email,',');
999        if ($nome != $proprietario && strlen($proprietario > 5)){
1000                if (is_array($part)) {                           
1001                        foreach($part AS $k => $v) {             
1002                                         if (isset($alarme_descarta) && $part[$k] == $nome) {
1003                                                    $laststack = "X-MOZ-LASTACK-PART-$nome";
1004                                                    $qryusr =  new AwlQuery("select * from phpgw_cal_extra where cal_id =:cal_id AND cal_extra_name=:cal_extra AND cal_extra_value=:cal_extra_value ",array(':cal_id' => $CALID, ':cal_extra' => $laststack,':cal_extra_value' => $alarme_descarta));
1005                                                    if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                     
1006                                                    if ($qryusr->rows() == 0) {                                                                                                                             
1007
1008                                                    $qryusr =  new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal_id,:cal_extra,:cal_extra_value)",array(':cal_id' => $CALID, ':cal_extra' => $laststack,':cal_extra_value' => $alarme_descarta));
1009                                                    if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                   
1010                                                    }                                                                                                                                                   
1011                                         }                                                                                                                                                             
1012
1013                                $qryuppart = new AwlQuery("DELETE from phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID, ':part' => $part[$k]));
1014                                if (!$qryuppart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);       
1015                                $qryslt = new AwlQuery("SELECT * FROM phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID, ':part' => $part[$k]));
1016                                $result=$qryslt->Exec("PUT");                                                                             
1017                                if ($result->rows() < 1){                                                                                   
1018                                        $consulta = "INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id,:part,:estado,'u')";
1019                                        $qrypart = new AwlQuery($consulta,array(':cal_id' => $CALID, ':part' => $part[$k], ':estado' => $estado[$k]));                                                                                               
1020                                        if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                               
1021                                }                                                                                                                                       
1022                                else{                                                                                                                                   
1023                                        $consulta  = "UPDATE phpgw_cal_user SET ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id,:part,:estado,'u') WHERE cal_id = $CALID AND cal_login = :par";
1024                                        $qrypart = new AwlQuery($consulta,array(':cal_id' => $CALID, ':part' => $part[$k], ':estado' => $estado[$k],':par' => $part[$k] ));                                                                                                                               
1025
1026                                        if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1027                                }                                                                                                         
1028                        }                                                                                                                 
1029                }                                                                                                                         
1030
1031        }
1032        else{
1033        $hostbanco = "-@{$iporigem}";
1034        if ($put_action_type == 'INSERT') {
1035               
1036                $qry = new AwlQuery("INSERT INTO phpgw_cal ( cal_id, uid, owner, category, datetime, mdatetime, edatetime,
1037                  priority,cal_type,is_public, title, location, description, reference ) VALUES ( DEFAULT,:hostbanco, :nome, :category_id, :DT_START, :MOD, :DT_END, :prioridade, :tipo, :public, :titulo, :cidade, :descricao,0)",array( ':hostbanco' => $hostbanco, ':nome' => $nome, ':category_id' =>  $category_id, ':DT_START' => $DT_START, ':MOD' => $MOD, ':DT_END' => $DT_END, ':prioridade' => $prioridade, ':tipo' => $tipo, ':public' => $public, ':titulo' => $titulo, ':cidade' => $cidade, ':descricao' => $descricao));
1038
1039                if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1040                $qryid = new AwlQuery("SELECT max(cal_id) FROM phpgw_cal WHERE owner = :nome", array(':nome' => $nome));             
1041                $qryid->Exec("PUT");                                                                         
1042                $cal = $qryid->Fetch();                                                                       
1043
1044
1045                if ($DT_START != $alarme) {
1046                        $id = "cal:{$cal->max}:0";
1047                        $next = $alarme;         
1048                        $time = "i:{$alarme}";   
1049                        $method = "calendar.bocalendar.send_alarm";
1050                        $data = "a:5:{s:4:\"time\";{$time};s:6:\"offset\";i:{$reducao};s:5:\"owner\";i:{$nome};s:7:\"enabled\";i:1;s:6:\"cal_id\";s:5:\"{$cal->max}\";}";
1051                        $account_id = $nome;                                                                                                                             
1052                        $qry = new AwlQuery("INSERT INTO phpgw_async ( id, next, times, method, data, account_id) VALUES ( :id, :next, :time, :method, :data, :account_id)", array(':id' => $id,':next' => $next, ':time' => $time,':method' => $method, ':data' =>  $data, ':account_id' => $account_id));
1053                        if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                   
1054                        if (isset($alarme_descarta)) {                                                                                                                                   
1055                                $qryusr = new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal,'X-MOZ-LASTACK',:alarme)", array(':cal' => $cal->max, ':alarme' => $alarme_descarta));
1056                                if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                         
1057                        }                                                                                                                                                                 
1058
1059                }
1060                if ($tipo == 'M') {
1061                        $total = preg_split("[;]", $RECUR, -1, PREG_SPLIT_NO_EMPTY);
1062                        $numero = count($total);                                   
1063                        $recur_enddate = 0;                                         
1064                        $recur_data = 0;                                           
1065                        $intervalo = 1;                                             
1066                        foreach($total as $valor) {                                 
1067                                list($ARG, $val) = split('[=]', $valor);           
1068                                switch ($ARG) {                                     
1069                                        case "FREQ":                               
1070                                                switch ($val) {                     
1071                                                        case "DAILY":               
1072                                                                $tipo = 1;         
1073                                                                break;             
1074                                                        case "WEEKLY":             
1075                                                                $tipo = 2;         
1076                                                                break;             
1077                                                        case "MONTHLY":             
1078                                                                $tipo = 3;         
1079                                                                break;             
1080                                                        case "YEARLY":             
1081                                                                $tipo = 5;         
1082                                                                break;             
1083                                                }                                   
1084                                                break;                             
1085                                                        case "UNTIL":               
1086                                                                $dateTime_until = date_create($val);
1087                                                                $recur_enddate = $dateTime_until->format("U");
1088
1089                                                                break;
1090                                                        case "COUNT":
1091                                                                switch ($tipo) {
1092                                                                        case 1:
1093                                                                                $dias = $intervalo * ($val - 1) * 86400;
1094                                                                                $recur_enddate = $DT_END + $dias;       
1095                                                                                break;                                 
1096                                                                        case 2:                                         
1097                                                                                $dias = $intervalo * ($val - 1) * 86400 * 7;
1098                                                                                $recur_enddate = $DT_END + $dias;           
1099                                                                                break;                                     
1100                                                                        case 3:                                             
1101                                                                                $dias = $intervalo * ($val - 1) * 86400 * 31;
1102                                                                                $recur_enddate = $DT_END + $dias;           
1103                                                                                break;                                       
1104                                                                        case 5:                                             
1105                                                                                $dias = $intervalo * ($val - 1) * 86400 * 365;
1106                                                                                $recur_enddate = $DT_END + $dias;             
1107                                                                                break;                                       
1108                                                                }                                                             
1109                                                                break;                                                       
1110                                                        case "INTERVAL":                                                     
1111                                                                $intervalo = $val;                                           
1112                                                                break;                                                       
1113                                                        case "BYDAY":                                                         
1114                                                                                //$semana = preg_split("[,]", $val, -1, PREG_SPLIT_NO_EMPTY);
1115                                                                                dbg_error_log("PUT", "diaVAL : '%s' ", $val);               
1116                                                                                $semana = explode(",",$val);                                 
1117                                                                                if (count($semana , 1) == 1){                               
1118                                                                                        array_push($semana , strtoupper(substr(date("D",$DT_START) ,0,2)));
1119                                                                                }                                                                         
1120                                                                                $recur_data = 0;                                                           
1121                                                                                foreach($semana as $dia) {                                                 
1122                                                                                        switch ($dia) {                                                   
1123                                                                                                case "SU":                                                 
1124                                                                                                        $recur_data = $recur_data + 1;                     
1125                                                                                                        break;                                             
1126                                                                                                case "MO":                                                 
1127                                                                                                        $recur_data = $recur_data + 2;                     
1128                                                                                                        break;                                             
1129                                                                                                case "TU":                                                 
1130                                                                                                        $recur_data = $recur_data + 4;                     
1131                                                                                                        break;                                             
1132                                                                                                case "WE":                                                 
1133                                                                                                        $recur_data = $recur_data + 8;                     
1134                                                                                                        break;                                             
1135                                                                                                case "TH":                                                 
1136                                                                                                        $recur_data = $recur_data + 16;                   
1137                                                                                                        break;                                             
1138                                                                                                case "FR":                                                 
1139                                                                                                        $recur_data = $recur_data + 32;                   
1140                                                                                                        break;                                             
1141                                                                                                case "SA":                                                 
1142                                                                                                        $recur_data = $recur_data + 64;                   
1143                                                                                                        break;                                             
1144                                                                                        }                                                                 
1145                                                                                }                                                                         
1146                                                                break;                                                                                     
1147                                                        default:                                                                                           
1148                                                                continue;                                                                                 
1149                                }                                                                                                                         
1150                                if ($recur_data == 62)                                                                                                     
1151                                $tipo = 2;                                                                                                                 
1152                        }                                                                                                                                 
1153                        $qryrepet = new AwlQuery("INSERT INTO phpgw_cal_repeats ( cal_id,recur_type, recur_use_end, recur_enddate, recur_interval,recur_data, recur_exception ) VALUES ( :cal,:tipo,0,:recur,:intervalo,:data,:exec)", array( ':cal' => $cal->max,':tipo' => $tipo, ':recur' => $recur_enddate, ':intervalo' => $intervalo, ':data' => $recur_data, ':exec' => $EXEC));                                                                                                                                                                                                               
1154                        if (!$qryrepet->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                 
1155                }                                                                                                                                                                                                                           
1156                $qryusr = new AwlQuery("INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal,:nome,'A','u')", array(':cal' => $cal->max, ':nome' => $nome));                                                                                     
1157                if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                           
1158                if (is_array($part)) {                                                                                                                                                                                                       
1159                        foreach($part AS $k => $v) {
1160                                $qrypart = new AwlQuery("INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal,:part,'U','u')", array(':cal' => $cal->max, ':part' => $part[$k]));                                                                 
1161                                if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                           
1162                        }                                                                                                                                                                                                                   
1163                }                                                                                                                                                                                                                           
1164                if (isset($mails)) {                                                                                                                                                                                                         
1165                        $qrypart_ex = new AwlQuery("UPDATE phpgw_cal SET ex_participants=:expart WHERE owner=:nome AND cal_id=:cal", array(':expart' => $mails, ':nome' => $nome, ':cal' => $cal->max));                                                                                           
1166                        if (!$qrypart_ex->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                               
1167                }                                                                                                                                                                                                                           
1168
1169                if ( $first->GetPValue('X-MOZ-SEND-INVITATIONS') == 'TRUE' ){
1170                        $qrypart = new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal,'X-MOZ-SEND-INVITATIONS','true')", array(':cal' => $cal->max));
1171                        if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                         
1172                }                                                                                                                                                                 
1173        } elseif ($put_action_type == 'UPDATE') {                                                                                                                                 
1174                if ( $recur_id != null) {                                                                                                                                                                 
1175                                $reference = substr( $UID ,0, strpos( $UID ,'@'));                                                                                                                                 
1176                                $tipo = "E";                                                                                                                                                                       
1177                                $qry = new AwlQuery("INSERT INTO phpgw_cal                                                                                                                                         
1178                                        ( cal_id, uid, owner, category, datetime, mdatetime, edatetime,  priority,                                                                                                 
1179                                        cal_type , is_public , title, location, description, reference )                                                                                                           
1180                                        VALUES ( DEFAULT,:hostbanco,:nome,:category_id,:DTSTART,:MOD,:DTEND,:prioridade,:tipo,:public,:titulo,:cidade,:descricao,:ref)",array(':hostbanco' => $hostbanco, ':nome' => $nome,':category_id' => $category_id,':DTSTART' => $DT_START, ':MOD' => $MOD, ':DTEND' => $DT_END, ':prioridade' => $prioridade, ':tipo' => $tipo, ':public' => $public, ':titulo' => $titulo, ':cidade' => $cidade, ':descricao' => $descricao,':ref' => $reference));                                                                                                                                                                                                                                         
1181                                if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                                 
1182                                $qryid = new AwlQuery("SELECT max(cal_id) FROM phpgw_cal WHERE owner = :nome", array(':nome' => $nome));                                                                                                     
1183                                $qryid->Exec("PUT");                                                                                                                                                                                         
1184                                $call = $qryid->Fetch();                                                                                                                                                                                     
1185                                $CALID = $call->max;
1186                                $qry = new AwlQuery("INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal,:nome,'A','u');",array(':cal' => $call->max,':nome' => $nome));                                     
1187                                if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                                 
1188                                $id_cal = "cal:$reference:0";                                                                                                                                                                               
1189                                $qryid = new Awlquery("SELECT * FROM phpgw_async WHERE id = :id_cal", array(':id_cal' => $id_cal));                                                                                                         
1190                                dbg_error_log("PUT", "argumento : '%s' igual '%s' ", $DT_START, $alarme);                                                                                                                                   
1191                                if ( $qryid->Exec("PUT",__LINE__,__FILE__) && $qryid->rows() > 0 && $DT_START != $alarme)                                                                                                                   
1192                                   {  $alarmew = $qryid->Fetch();                                                                                                                                                                           
1193                                      $data_seg = dataTParaSegundos($recur_id["DTSTART"]);                                                                                                                                                   
1194                                      $tempo_ant = $data_seg - $reducao;                                                                                                                                                                     
1195                                      $id_cal_novo = "cal:$call->max:0";                                                                                                                                                                     
1196                                      $timess = "i:$tempo_ant";                                                                                                                                                                             
1197                                      $dados_alarme= "a:5:{s:4:\"time\";i:$tempo_ant;s:6:\"offset\";i:$reducao;s:5:\"owner\";i:$nome;s:7:\"enabled\";i:1;s:6:\"cal_id\";s:5:\"$call->max\";}";                                               
1198                                      $qrysy = new PgQuery("INSERT INTO phpgw_async ( id, next, times, method, data, account_id) VALUES ( :id,:next,:times,'calendar.bocalendar.send_alarm',:data,:account);", array(':id' => $id_cal_novo,':next' => $tempo_ant,':times' => $timess,':data' => $dados_alarme,':account' => $nome));                                                                                                                                                                                                                                                                                                                                                                                                   
1199                                      if (!$qrysy->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                         
1200                                                                                                                                                                                                                                             
1201                                }
1202                               /*
1203                               if (is_array($part)) {
1204                                      foreach($part AS $k => $v) {
1205                                             if ($estado[$k] != 'U'){
1206                                                       $qryuppart = new AwlQuery("DELETE from phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID,':part' => $part[$k]));
1207                                                       if (!$qryuppart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1208                                                       $qryslt = new AwlQuery("SELECT * FROM phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID,':part' => $part[$k]));                                                $
1209                                                       $result=$qryslt->Exec("PUT");
1210                                                       if ($result->rows < 1){
1211                                                                     $consulta = "INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id ,:part,:estado,'u')";
1212                                                                     $qrypart = new AwlQuery($consulta, array(':cal_id' => $CALID,':part' => $part[$k],':estado' => $estado[$k]));                                                                               $
1213                                                                     if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1214                                                                  }
1215                                                       else{
1216                                                               $consulta  = "UPDATE phpgw_cal_user SET ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id ,:part,:estado,'u') WHERE cal_id = $CALID AND cal_login = :par";                        $
1217                                                               $qrypart = new AwlQuery($consulta, array(':cal_id' => $CALID,':part' => $part[$k],':estado' => $estado[$k],':par' => $part[$k]));                                                           $
1218                                                               if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1219                                                       }
1220                                             }
1221                                      }
1222                                }
1223                               if (isset($mails)) {
1224                                             $qrypart_ex = new AwlQuery("UPDATE phpgw_cal SET ex_participants=:expart WHERE owner=:nome AND cal_id=:cal_id", array(':expart' => $mails,':nome' =>  $nome,':cal_id' => $call->max));
1225                                             if (!$qrypart_ex->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1226                               }
1227                              */                                                                                                                                                                                                           
1228                 }
1229              else
1230                 {
1231              //if( isset($alarme_descarta) || isset($adia_alarme))
1232              //   { }
1233              // else
1234              //  { 
1235                 $qry = new AwlQuery("UPDATE phpgw_cal SET cal_id=:cal ,uid=:hostbanco ,owner=:nome ,category=:category_id , datetime=:DT_START, mdatetime=:MOD, edatetime=:DT_END, priority=:prioridade, cal_type=:tipo, is_public=:public, title=:titulo , description=:descricao, location=:location, ex_participants=:expart  WHERE owner=:nome AND cal_id=:cal_id", array( ':cal' => $CALID  ,':hostbanco' => $hostbanco, ':nome' => $nome, ':category_id' =>  $category_id, ':DT_START' => $DT_START, ':MOD' => $MOD, ':DT_END' => $DT_END, ':prioridade' => $prioridade, ':tipo' => $tipo, ':public' => $public, ':titulo' => $titulo,':descricao' => $descricao,':location' => $cidade,':expart' => $mails,':nome' => $nome,':cal_id' => $CALID ));                                                               
1236                 if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1237              //  }                                                                                                                               
1238                if ($DT_START != $alarme) {                                                                                                                                                                                                 
1239                        $id = "cal:$CALID:0";                                                                                                                                                                                               
1240                        $next = "$alarme";                                                                                                                                                                                                   
1241                        $time = "i:$alarme";                                                                                                                                                                                                 
1242                        $method = "calendar.bocalendar.send_alarm";                                                                                                                                                                         
1243                        $data = "a:5:{s:4:\"time\";$time;s:6:\"offset\";i:$reducao;s:5:\"owner\";i:$nome;s:7:\"enabled\";i:1;s:6:\"cal_id\";s:5:\"$CALID\";}";                                                                               
1244                        $account_id = "$nome";                                                                                                                                                                                               
1245                        $qry = new AwlQuery("UPDATE  phpgw_async set next=:next,  times=:time,  data=:data,  account_id=:account WHERE id=:id", array(':next' => $next,':time' => $time, ':data' => $data, ':account' => $account_id, ':id' => $id));                                                                           
1246                        $qry->Exec("PUT");                                                                                                                                                                                                   
1247                        $qry = new AwlQuery("select * from phpgw_cal_extra WHERE cal_id=:cal_id", array(':cal_id' => $CALID));                                                                                                                                         
1248                        $qry->Exec("PUT");                                                                                                                                                                                                   
1249                        dbg_error_log("PUT", "argumento : '%s' valor : '%s' ", $alarme_descarta);                                                                                                                             
1250                        if ($qry->rows() != 0) {                                                                                                                                                                                               
1251                                if (isset($alarme_descarta)) {                                                                                                                                                                               
1252                                        $qryusr = new AwlQuery("UPDATE phpgw_cal_extra set cal_extra_value=:alarme WHERE cal_id=:cal_id AND cal_extra_name = 'X-MOZ-LASTACK'",array(':alarme' =>  $alarme_descarta, ':cal_id' => $CALID));                                                 
1253                                        $qryusr->Exec("PUT");                                                                                                                                                                               
1254                                }                                                                                                                                                                                                           
1255                                if (isset($adia_alarme)) {                                                                                                                                                                                   
1256                                        $qryusr = new AwlQuery("UPDATE phpgw_cal_extra set cal_extra_value=:calextravalue WHERE cal_id=:cal AND cal_extra_name =:cal_extra ", array(':calextravalue' => $adia_alarme ,':cal' => $CALID, ':cal_extra' => $snooze));                                                         
1257                                        $qryusr->Exec("PUT");                                                                                                                                                                               
1258                                }                                                                                                                                                                                                           
1259
1260                        } else {
1261                                 
1262                                if (isset($alarme_descarta)) {
1263                                        $qryusr = new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal,'X-MOZ-LASTACK',:alarme)", array(':cal' => $CALID,':alarme' =>  $alarme_descarta));
1264                                        if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                       
1265                                }                                                                                                                                                               
1266                                if (isset($adia_alarme)) {                                                                                                                                     
1267                                        $qryusr = new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal,:snooze,:adia)", array(':cal' => $CALID,':snooze' =>  $snooze, ':adia' => $adia_alarme));         
1268                                        if (!$qryusr->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                       
1269                                }                                                                                                                                                               
1270                                                                                                                                                                                               
1271                        }                                                                                                                                                                       
1272                                                                                                                                                                                               
1273                        $qry = new AwlQuery("select id from phpgw_async WHERE id=:id", array(':id' => $id));                                                                                                       
1274                        $qry->Exec("PUT");                                                                                                                                                     
1275                        if ($qry->rows() == 0) {                                                                                                                                                 
1276                                $qry = new AwlQuery("INSERT INTO phpgw_async ( id, next, times, method, data, account_id) VALUES (:id, :next, :time, :method, :data, :account_id)",array(':id' => $id,':next' => $next,':time' => $time,':method' => $method, ':data' => $data, ':account_id' => $account_id));
1277                                if (!$qry->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                   
1278                        }                                                                                                                                                                       
1279                }                                                                                                                                                                               
1280
1281                if ((strlen($alarme_time) == 0) && ($tipo == 'E')) {                                                                                                                             
1282                        $id = "cal:$CALID:0";                                                                                                                                                   
1283                        $qry = new AwlQuery("DELETE FROM phpgw_async WHERE id=:id", array(':id' => $id));                                                                                                           
1284                        $qry->Exec("PUT");                                                                                                                                                       
1285                }                                                                                                                                                                               
1286                if ($tipo == 'M') {                                                                                                                                                             
1287                        $total = preg_split("[;]", $RECUR, -1, PREG_SPLIT_NO_EMPTY);                                                                                                                                                         
1288                        $numero = count($total);                                                                                                                                                                                             
1289                        $recur_enddate = 0;                                                                                                                                                                                                 
1290                        $recur_data = 0;                                                                                                                                                                                                     
1291                        foreach($total as $valor) {                                                                                                                                                                                         
1292                                list($ARG, $val) = split('[=]', $valor);                                                                                                                                                                     
1293                                dbg_error_log("PUT", "argumento : '%s' valor : '%s' ", $ARG, $val);                                                                                                                                         
1294                                switch ($ARG) {                                                                                                                                                                                             
1295                                        case "FREQ":                                                                                                                                                                                         
1296                                                switch ($val) {                                                                                                                                                                             
1297                                                        case "DAILY":                                                                                                                                                                       
1298                                                                $tipo = 1;                                                                                                                                                                   
1299                                                                break;                                                                                                                                                                       
1300                                                        case "WEEKLY":                                                                                                                                                                       
1301                                                                $tipo = 2;                                                                                                                                                                   
1302                                                                break;                                                                                                                                                                       
1303                                                        case "MONTHLY":                                                                                                                                                                     
1304                                                                $tipo = 3;                                                                                                                                                                   
1305                                                                break;                                                                                                                                                                       
1306                                                        case "YEARLY":                                                                                                                                                                       
1307                                                                $tipo = 5;                                                                                                                                                                   
1308                                                                break;                                                                                                                                                                       
1309                                                }                                                                                                                                                                                           
1310                                                break;                                                                                                                                                                                       
1311                                                        case "UNTIL":                                                                                                                                                                       
1312                                                                //$recur_enddate = dataTDiaSeguinteSegundos($val ,1);                                                                                                                       
1313                                                                $dateTime_until = date_create($val);                                                                                                                                         
1314                                                                $recur_enddate = $dateTime_until->format("U");                                                                                                                               
1315                                                                break;                                                                                                                                                                       
1316                                                        case "COUNT":                                                                                                                                                                       
1317                                                                switch ($tipo) {                                                                                                                                                             
1318                                                                        case 1:                                                                                                                                                             
1319                                                                                $dias = $intervalo * $val * 86400;                                                                                                                           
1320                                                                                $recur_enddate = $DT_END + $dias;                                                                                                                           
1321                                                                                break;                                                                                                                                                       
1322                                                                        case 2:                                                                                                                                                             
1323                                                                                $dias = $intervalo * $val * 86400 * 7;                                                                                                                       
1324                                                                                $recur_enddate = $DT_END + $dias;                                                                                                                           
1325                                                                                break;                                                                                                                                                       
1326                                                                        case 3:                                                                                                                                                             
1327                                                                                $dias = $intervalo * $val * 86400 * 31;                                                                                                                     
1328                                                                                $recur_enddate = $DT_END + $dias;                                                                                                                           
1329                                                                                break;                                                                                                                                                       
1330                                                                        case 5:                                                                                                                                                             
1331                                                                                $dias = $intervalo * $val * 86400 * 365;                                                                                                                     
1332                                                                                $recur_enddate = $DT_END + $dias;                                                                                                                           
1333                                                                                break;                                                                                                                                                       
1334                                                                }                                                                                                                                                                           
1335                                                                break;                                                                                                                                                                       
1336                                                                        case "INTERVAL":                                                                                                                                                     
1337                                                                                $intervalo = $val;                                                                                                                                           
1338                                                                        case "BYDAY":                                                                                                                                                       
1339                                                                                $semana = preg_split("[,]", $val, -1, PREG_SPLIT_NO_EMPTY);                                                                                                 
1340                                                                                if (count($semana , 1) == 1){                                                                                                                               
1341                                                                                        dbg_error_log("PUT", "dia1 : '%s' ", count($semana));                                                                                               
1342                                                                                        array_push($semana , strtoupper(substr(date("D",$DT_START) ,0,2)));                                                                                 
1343                                                                                }                                                                                                                                                           
1344                                                                                $recur_data=0;                                                                                                                                               
1345                                                                                foreach($semana as $dia) {                                                                                                                                   
1346                                                                                        dbg_error_log("PUT", "dia 2 : '%s' ", $dia);                                                                                                         
1347                                                                                        switch ($dia) {                                                                                                                                     
1348                                                                                                case "SU":                                                                                                                                   
1349                                                                                                        $recur_data = $recur_data + 1;                                                                                                       
1350                                                                                                        break;                                                                                                                               
1351                                                                                                case "MO":                                                                                                                                   
1352                                                                                                        $recur_data = $recur_data + 2;                                                                                                       
1353                                                                                                        break;                                                                                                                               
1354                                                                                                case "TU":                                                                                                                                   
1355                                                                                                        $recur_data = $recur_data + 4;                                                                                                       
1356                                                                                                        break;                                                                                                                               
1357                                                                                                case "WE":                                                                                                                                   
1358                                                                                                        $recur_data = $recur_data + 8;                                                                                                       
1359                                                                                                        break;                                                                                                                               
1360                                                                                                case "TH":                                                                                                                                   
1361                                                                                                        $recur_data = $recur_data + 16;                                                                                                     
1362                                                                                                        break;                                                                                                                               
1363                                                                                                case "FR":                                                                                                                                   
1364                                                                                                        $recur_data = $recur_data + 32;                                                                                                     
1365                                                                                                        break;                                                                                                                               
1366                                                                                                case "SA":                                                                                                                                   
1367                                                                                                        $recur_data = $recur_data + 64;                                                                                                     
1368                                                                                                        break;                                                                                                                               
1369                                                                                        }                                                                                                                                                   
1370                                                                                }                                                                                                                                                           
1371                                                                                break;                                                                                                                                                       
1372                                                                                                default:                                                                                                                                     
1373                                                                                                        continue;                                                                                                                           
1374                                }                                                                                                                                                                                                           
1375                                if ($recur_data == 62)                                                                                                                                                                                       
1376                                $tipo = 2;                                                                                                                                                                                                   
1377                        }                                                                                                                                                                                                                   
1378                        $qryrepet = new AwlQuery("UPDATE  phpgw_cal_repeats set  cal_id=:cal,recur_type=:recur , recur_enddate=:data, recur_interval=:intervalo, recur_data=:recurdata , recur_exception=:exception where cal_id = :cal_id", array(':cal' => $CALID,':recur' => $tipo, ':data' => $recur_enddate, ':intervalo' =>  $intervalo,':recurdata' =>  $recur_data, ':exception' => $EXEC, ':cal_id' => $CALID));                                                                                                                                                                                                                     
1379                        if (!$qryrepet->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                 
1380                }
1381                //$qryuppart = new PgQuery("DELETE from phpgw_cal_user WHERE cal_id = ? AND cal_status = 'U' AND cal_login = ?",$CALID,$nome);                                                                                               
1382                //if (!$qryuppart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                                       
1383                if (is_array($part)) {                                                                                                                                                                                                       
1384                        foreach($part AS $k => $v) {                                                                                                                                                                                         
1385                                if ($estado[$k] != 'R'){                                                                                                                                                                                     
1386                                        $qryuppart = new AwlQuery("DELETE from phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID,':part' => $part[$k]));                                                                                         
1387                                        if (!$qryuppart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                                 
1388                                        $qryslt = new AwlQuery("SELECT * FROM phpgw_cal_user WHERE cal_id = :cal_id AND cal_login = :part",array(':cal_id' => $CALID,':part' => $part[$k]));                                                                                           
1389                                        $result=$qryslt->Exec("PUT");                                                                                                                                                                       
1390                                        if ($result->rows < 1){                                                                                                                                                                             
1391                                                $consulta = "INSERT INTO phpgw_cal_user ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id ,:part,:estado,'u')";                                                           
1392                                                $qrypart = new AwlQuery($consulta, array(':cal_id' => $CALID,':part' => $part[$k],':estado' => $estado[$k]));                                                                                                                                                           
1393                                                if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                                                                                           
1394                                        }                                                                                                                                                                                                   
1395                                        else{                                                                                                                                                                                               
1396                                                $consulta  = "UPDATE phpgw_cal_user SET ( cal_id, cal_login, cal_status, cal_type) VALUES ( :cal_id ,:part,:estado,'u') WHERE cal_id = $CALID AND cal_login = :par";                           
1397                                                $qrypart = new AwlQuery($consulta, array(':cal_id' => $CALID,':part' => $part[$k],':estado' => $estado[$k],':par' => $part[$k]));                                                                                                                                                           
1398
1399                                                        if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1400                                        }                                                                                                                 
1401                                }                                                                                                                         
1402                        }                                                                                                                                 
1403                }                                                                                                                                         
1404                if (isset($mails)) {                                                                                                                     
1405                        $qrypart_ex = new AwlQuery("UPDATE phpgw_cal SET ex_participants=:expart WHERE owner=:nome AND cal_id=:cal_id", array(':expart' => $mails,':nome' =>  $nome,':cal_id' => $CALID));         
1406                        if (!$qrypart_ex->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);                             
1407                }
1408                if ( $first->GetPValue('X-MOZ-SEND-INVITATIONS') == 'TRUE' ){
1409                        $qrypart = new AwlQuery("INSERT INTO phpgw_cal_extra ( cal_id, cal_extra_name, cal_extra_value) VALUES ( :cal,'X-MOZ-SEND-INVITATIONS','true')", array(':cal' => $CALID));
1410                        if (!$qrypart->Exec("PUT")) rollback_on_error($caldav_context, $user_no, $path);
1411                }
1412              }                                                                                                                                           
1413            }
1414        }
1415        return true;
1416
1417}
1418function write_resource_old( $user_no, $path, $caldav_data, $collection_id, $author, $etag, $ic, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
1419  global $tz_regex;
1420
1421  $resources = $ic->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
1422  if ( !isset($resources[0]) ) {
1423    $resource_type = 'Unknown';
1424    /** @TODO: Handle writing non-calendar resources, like address book entries or random file data */
1425    rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
1426    return false;
1427  }
1428  else {
1429    $first = $resources[0];
1430    $resource_type = $first->GetType();
1431  }
1432  dbg_log_array('PUT','VTIMEZONE',$first,true);
1433  $qry = new AwlQuery();
1434  $qry->Begin();
1435  $params = array(
1436      ':dav_name' => $path,
1437      ':user_no' => $user_no,
1438      ':etag' => $etag,
1439      ':dav_data' => $caldav_data,
1440      ':caldav_type' => $resource_type,
1441      ':session_user' => $author,
1442      ':weak_etag' => $weak_etag
1443  );
1444  if ( $put_action_type == 'INSERT' ) {
1445    create_scheduling_requests($vcal);
1446    $sql = 'INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id, weak_etag )
1447            VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, current_timestamp, current_timestamp, :collection_id, :weak_etag )';
1448    $params[':collection_id'] = $collection_id;
1449  }
1450  else {
1451    update_scheduling_requests($vcal);
1452    $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
1453            modified=current_timestamp, weak_etag=:weak_etag WHERE user_no=:user_no AND dav_name=:dav_name';
1454  }
1455  if ( !$qry->QDo($sql,$params) ) {
1456    rollback_on_error( $caldav_context, $user_no, $path);
1457    return false;
1458  }
1459
1460  $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $path));
1461  if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
1462    $dav_id = $row->dav_id;
1463  }
1464
1465   
1466  $calitem_params = array(
1467      ':dav_name' => $path,
1468      ':user_no' => $user_no,
1469      ':etag' => $etag
1470  );
1471  $dtstart = $first->GetPValue('DTSTART');
1472  $calitem_params[':dtstart'] = $dtstart;
1473  if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
1474    $dtstart = $first->GetPValue('DUE');
1475  }
1476
1477  $dtend = $first->GetPValue('DTEND');
1478  if ( isset($dtend) && $dtend != '' ) {
1479    dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
1480    $calitem_params[':dtend'] = $dtend;
1481    $dtend = ':dtend';
1482  }
1483  else {
1484    $dtend = 'NULL';
1485    if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
1486      $duration = preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') );
1487      $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
1488      $calitem_params[':duration'] = $duration;
1489    }
1490    elseif ( $first->GetType() == 'VEVENT' ) {
1491      /**
1492      * From RFC2445 4.6.1:
1493      * For cases where a "VEVENT" calendar component specifies a "DTSTART"
1494      * property with a DATE data type but no "DTEND" property, the events
1495      * non-inclusive end is the end of the calendar date specified by the
1496      * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
1497      * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
1498      * the event ends on the same calendar date and time of day specified by the
1499      * "DTSTART" property.
1500      *
1501      * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
1502      *
1503      */
1504     
1505      $value_type = $first->GetPParamValue('DTSTART','VALUE');
1506      dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
1507      if ( isset($value_type) && $value_type == 'DATE' )
1508        $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1509      else
1510        $dtend = ':dtstart';
1511    }
1512  }
1513
1514  $last_modified = $first->GetPValue('LAST-MODIFIED');
1515  if ( !isset($last_modified) || $last_modified == '' ) {
1516    $last_modified = gmdate( 'Ymd\THis\Z' );
1517  }
1518  $calitem_params[':modified'] = $last_modified;
1519
1520  $dtstamp = $first->GetPValue('DTSTAMP');
1521  if ( !isset($dtstamp) || $dtstamp == '' ) {
1522    $dtstamp = $last_modified;
1523  }
1524  $calitem_params[':dtstamp'] = $dtstamp;
1525
1526  $class = $first->GetPValue('CLASS');
1527  /* Check and see if we should over ride the class. */
1528  /** @TODO: is there some way we can move this out of this function? Or at least get rid of the need for the SQL query here. */
1529  if ( public_events_only($user_no, $path) ) {
1530    $class = 'PUBLIC';
1531  }
1532
1533  /*
1534   * It seems that some calendar clients don't set a class...
1535   * RFC2445, 4.8.1.3:
1536   * Default is PUBLIC
1537   */
1538  if ( !isset($class) || $class == '' ) {
1539    $class = 'PUBLIC';
1540  }
1541  $calitem_params[':class'] = $class;
1542
1543
1544  /** Calculate what timezone to set, first, if possible */
1545  $last_tz_locn = 'Turkmenikikamukau';  // I really hope this location doesn't exist!
1546  $tzid = $first->GetPParamValue('DTSTART','TZID');
1547  if ( !isset($tzid) || $tzid == '' ) $tzid = $first->GetPParamValue('DUE','TZID');
1548  $timezones = $ic->GetComponents('VTIMEZONE');
1549  foreach( $timezones AS $k => $tz ) {
1550    if ( $tz->GetPValue('TZID') != $tzid ) {
1551      /**
1552      * We'll pretend they didn't forget to give us a TZID and that they
1553      * really hope the server is running in the timezone they supplied... but be noisy about it.
1554      */
1555      dbg_error_log( 'ERROR', ' Event includes TZID[%s] but uses TZID[%s]!', $tz->GetPValue('TZID'), $tzid );
1556      $tzid = $tz->GetPValue('TZID');
1557    }
1558    // This is the one
1559    $tz_locn = $tz->GetPValue('X-LIC-LOCATION');
1560    if ( ! isset($tz_locn) ) {
1561      if ( preg_match( '#([^/]+/[^/]+)$#', $tzid, $matches ) )
1562        $tz_locn = $matches[1];
1563      else if ( isset($tzid) && $tzid != '' ) {
1564        dbg_error_log( 'ERROR', ' Couldn\'t guess Olsen TZ from TZID[%s].  This may end in tears...', $tzid );
1565      }
1566    }
1567    else {
1568      if ( ! preg_match( $tz_regex, $tz_locn ) ) {
1569        if ( preg_match( '#([^/]+/[^/]+)$#', $tzid, $matches ) ) $tz_locn = $matches[1];
1570      }
1571    }
1572
1573    dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($tz_locn) ? $tz_locn : '') );
1574    if ( isset($tz_locn) && ($tz_locn != $last_tz_locn) && preg_match( $tz_regex, $tz_locn ) ) {
1575      dbg_error_log( 'PUT', ' Setting timezone to %s', $tz_locn );
1576      if ( $tz_locn != '' ) {
1577        $qry->QDo('SET TIMEZONE TO \''.$tz_locn."'" );
1578      }
1579      $last_tz_locn = $tz_locn;
1580    }
1581    $params = array( ':tzid' => $tzid);
1582    $qry = new AwlQuery('SELECT tz_locn FROM time_zone WHERE tz_id = :tzid', $params );
1583    if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1584      $params[':tzlocn'] = $tz_locn;
1585      $params[':tzspec'] = (isset($tz) ? $tz->Render() : null );
1586      $qry->QDo('INSERT INTO time_zone (tz_id, tz_locn, tz_spec) VALUES(:tzid,:tzlocn,:tzspec)', $params );
1587    }
1588    if ( !isset($tz_locn) || $tz_locn == '' ) $tz_locn = $tzid;
1589
1590  }
1591
1592  $created = $first->GetPValue('CREATED');
1593  if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1594  $calitem_params[':created'] = $created;
1595
1596  $calitem_params[':tzid'] = $tzid;
1597  $calitem_params[':uid'] = $first->GetPValue('UID');
1598  $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1599  $calitem_params[':location'] = $first->GetPValue('LOCATION');
1600  $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1601  $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1602  $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1603  $calitem_params[':url'] = $first->GetPValue('URL');
1604  $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1605  $calitem_params[':due'] = $first->GetPValue('DUE');
1606  $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1607  $calitem_params[':status'] = $first->GetPValue('STATUS');
1608  if ( $put_action_type == 'INSERT' ) {
1609    $sql = <<<EOSQL
1610INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp,
1611                dtstart, dtend, summary, location, class, transp,
1612                description, rrule, tz_id, last_modified, url, priority,
1613                created, due, percent_complete, status, collection_id )
1614   VALUES ( :user_no, :dav_name, currval('dav_id_seq'), :etag, :uid, :dtstamp,
1615                :dtstart, $dtend, :summary, :location, :class, :transp,
1616                :description, :rrule, :tzid, :modified, :url, :priority,
1617                :created, :due, :percent_complete, :status, $collection_id )
1618EOSQL;
1619    $sync_change = 201;
1620  }
1621  else {
1622    $sql = <<<EOSQL
1623UPDATE calendar_item SET dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
1624                dtstart=:dtstart, dtend=$dtend, summary=:summary, location=:location, class=:class, transp=:transp,
1625                description=:description, rrule=:rrule, tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
1626                created=:created, due=:due, percent_complete=:percent_complete, status=:status
1627       WHERE user_no=:user_no AND dav_name=:dav_name
1628EOSQL;
1629    $sync_change = 200;
1630  }
1631
1632  write_alarms($dav_id, $first);
1633  write_attendees($dav_id, $first);
1634
1635  if ( $log_action && function_exists('log_caldav_action') ) {
1636    log_caldav_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1637  }
1638  else if ( $log_action  ) {
1639    dbg_error_log( 'PUT', 'No log_caldav_action( %s, %s, %s, %s, %s) can be called.',
1640            $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1641  }
1642 
1643  $qry = new AwlQuery( $sql, $calitem_params );
1644  if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1645    rollback_on_error( $caldav_context, $user_no, $path);
1646    return false;
1647  }
1648  $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $path ) );
1649  $qry->Commit();
1650
1651  dbg_error_log( 'PUT', 'User: %d, ETag: %s, Path: %s', $author, $etag, $path);
1652
1653  return true;  // Success!
1654}
1655
1656
1657
1658/**
1659* A slightly simpler version of write_resource which will make more sense for calling from
1660* an external program.  This makes assumptions that the collection and user do exist
1661* and bypasses all checks for whether it is reasonable to write this here.
1662* @param string $path The path to the resource being written
1663* @param string $caldav_data The actual resource to be written
1664* @param string $put_action_type INSERT or UPDATE depending on what we are to do
1665* @return boolean True for success, false for failure.
1666*/
1667function simple_write_resource( $path, $caldav_data, $put_action_type, $write_action_log = false ) {
1668
1669  $etag = md5($caldav_data);
1670  $ic = new iCalComponent( $caldav_data );
1671
1672  /**
1673  * We pull the user_no & collection_id out of the collection table, based on the resource path
1674  */
1675  $collection_path = preg_replace( '#/[^/]*$#', '/', $path );
1676  $qry = new AwlQuery( 'SELECT user_no, collection_id FROM collection WHERE dav_name = :dav_name ', array( ':dav_name' => $collection_path ) );
1677  if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 1 ) {
1678    $collection = $qry->Fetch();
1679    $user_no = $collection->user_no;
1680
1681    return write_resource( $user_no, $path, $caldav_data, $collection->collection_id, $user_no, $etag, $ic, $put_action_type, false, $write_action_log );
1682  }
1683  return false;
1684}
1685function dataTParaSegundos($datatz){
1686        $HorarioTimeZone = new DateTimeZone(date_default_timezone_get());
1687        $HorarioTime = new DateTime("now", $HorarioTimeZone);
1688        return mktime(  substr("$datatz", 9,2),//hora
1689        substr("$datatz", 11,2),//min
1690        substr("$datatz", 13,2),//segundos
1691        substr("$datatz", 4,2),//mes
1692        substr("$datatz", 6,2),//dia
1693        substr("$datatz", 0,4));//ano
1694}
1695
1696function dataTzParaSegundos($datatz){
1697        $HorarioTimeZone = new DateTimeZone(date_default_timezone_get());
1698        $HorarioTime = new DateTime("now", $HorarioTimeZone);
1699        return mktime(  substr("$datatz", 9,2),//hora
1700        substr("$datatz", 11,2),//min
1701        substr("$datatz", 13,2),//segundos
1702        substr("$datatz", 4,2),//mes
1703        substr("$datatz", 6,2),//dia
1704        substr("$datatz", 0,4)) + $HorarioTimeZone->getoffset($HorarioTime);//ano
1705}
1706
1707function dataSegundosParaTZ($dataseg){
1708        $HorarioTimeZone = new DateTimeZone(date_default_timezone_get());
1709        $HorarioTime = new DateTime("now", $HorarioTimeZone);
1710        $teste = getdate($dataseg - $HorarioTimeZone->getoffset($HorarioTime));
1711        return date("Ymd\THis\Z",$teste[0]);
1712}
1713
1714function dataTDiaSeguinteSegundos($datatz , $data_inicio){
1715        if ((int)substr("$data_inicio", 9,2) < 5){
1716                $ajuste_dia=86400;
1717        }
1718        elseif((int)substr("$data_inicio", 9,2) > 16){
1719                $ajuste_dia=-86400;
1720        }
1721        $teste = (int)mktime(0,0,0,
1722        substr("$datatz", 4,2),//mes
1723        substr("$datatz", 6,2),
1724        substr("$datatz", 0,4)) + $ajuste_dia;//ano
1725        return $teste;
1726
1727}
1728
Note: See TracBrowser for help on using the repository browser.