<commit_before><?php

// According to RFC2445 we should always end with CRLF, but the CalDAV spec says
// that normalising XML parses often muck with it and may remove the CR.
$icalendar = preg_replace('/\r?\n /', '', $request->raw_post );
$fh = fopen('/tmp/PUT-2.txt','w');
fwrite($fh,$icalendar);
fclose($fh);

$lines = preg_split('/\r?\n/', $icalendar );

$events = array();
$timezones = array();

$current = "";
$state = "";
$tzid = 'unknown';
foreach( $lines AS $lno => $line ) {
  dbg_error_log( "PUT", "CalendarLine[%04d] - %s: %s", $lno, $state, $line );
  if ( $state == "" ) {
    if ( preg_match( '/^BEGIN:(VEVENT|VTIMEZONE)$/', $line, $matches ) ) {
      $current .= $line."\n";
      $state = $matches[1];
    }
  }
  else {
    $current .= $line."\n";
    if ( $line == "END:$state" ) {
      switch ( $state ) {
        case 'VEVENT':
          $events[] = array( 'data' => $current, 'tzid' => $tzid );
          break;
        case 'VTIMEZONE':
          $timezones[$tzid] = $current;
          break;
      }
      $state = "";
      $current = "";
      $tzid = 'unknown';
    }
    else if ( preg_match( '/TZID=([^:]+)(:|$)/', $line, $matches ) ) {
      $tzid = $matches[1];
    }
  }
}

function rollback_on_error() {
  global $request;
  $qry = new PgQuery("ROLLBACK;"); $qry->Exec("PUT");
  $request->DoResponse( 500, translate("Database error") );
}

$qry = new PgQuery("BEGIN; DELETE FROM calendar_item WHERE user_no=? AND dav_name ~ ?; DELETE FROM caldav_data WHERE user_no=? AND dav_name ~ ?;", $request->user_no, $request->path.'[^/]+$', $request->user_no, $request->path.'[^/]+$');
if ( !$qry->Exec("PUT") ) rollback_on_error();

foreach( $events AS $k => $event ) {
  dbg_error_log( "PUT", "Putting event %d with data: %s", $k, $event['data'] );
  $icalendar = iCalendar::iCalHeader() . $event['data'] . $timezones[$event['tzid']] . iCalendar::iCalFooter();
  $ic = new iCalendar( array( 'icalendar' => $icalendar ) );
  $etag = md5($icalendar);
  $event_path = sprintf( "%s%d.ics", $request->path, $k);
  $qry = new PgQuery( "INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified ) VALUES( ?, ?, ?, ?, ?, ?, current_timestamp, current_timestamp )",
                        $request->user_no, $event_path, $etag, $icalendar, $ic->type, $session->user_no );
  if ( !$qry->Exec("PUT") ) rollback_on_error();

  $sql = ( $ic->tz_locn == '' ? '' : "SET TIMEZONE TO ".qpg($ic->tz_locn).";" );

  $dtstart = $ic->Get('dtstart');<commit_msg>A somewhat unsatisfactory hack, so that I can import a calendar from Evolution.  It does work, but it is not the final answer.<commit_after><?php

// According to RFC2445 we should always end with CRLF, but the CalDAV spec says
// that normalising XML parses often muck with it and may remove the CR.
$icalendar = preg_replace('/\r?\n /', '', $request->raw_post );
$fh = fopen('/tmp/PUT-2.txt','w');
fwrite($fh,$icalendar);
fclose($fh);

$lines = preg_split('/\r?\n/', $icalendar );

$events = array();
$timezones = array();

$current = "";
$state = "";
$tzid = 'unknown';
foreach( $lines AS $lno => $line ) {
  dbg_error_log( "PUT", "CalendarLine[%04d] - %s: %s", $lno, $state, $line );
  if ( $state == "" ) {
    if ( preg_match( '/^BEGIN:(VEVENT|VTIMEZONE)$/', $line, $matches ) ) {
      $current .= $line."\n";
      $state = $matches[1];
    }
  }
  else {
    $current .= $line."\n";
    if ( $line == "END:$state" ) {
      switch ( $state ) {
        case 'VEVENT':
          $events[] = array( 'data' => $current, 'tzid' => $tzid );
          break;
        case 'VTIMEZONE':
          $timezones[$tzid] = $current;
          break;
      }
      $state = "";
      $current = "";
      $tzid = 'unknown';
    }
    else if ( preg_match( '/TZID=([^:]+)(:|$)/', $line, $matches ) ) {
      $tzid = $matches[1];
    }
  }
}

function rollback_on_error() {
  global $request;
  $qry = new PgQuery("ROLLBACK;"); $qry->Exec("PUT");
  $request->DoResponse( 500, translate("Database error") );
}

$qry = new PgQuery("BEGIN; DELETE FROM calendar_item WHERE user_no=? AND dav_name ~ ?; DELETE FROM caldav_data WHERE user_no=? AND dav_name ~ ?;", $request->user_no, $request->path.'[^/]+$', $request->user_no, $request->path.'[^/]+$');
if ( !$qry->Exec("PUT") ) rollback_on_error();

foreach( $events AS $k => $event ) {
  dbg_error_log( "PUT", "Putting event %d with data: %s", $k, $event['data'] );
  $icalendar = iCalendar::iCalHeader() . $event['data'] . $timezones[$event['tzid']] . iCalendar::iCalFooter();
  $ic = new iCalendar( array( 'icalendar' => $icalendar ) );
  $etag = md5($icalendar);
  $event_path = sprintf( "%s%d.ics", $request->path, $k);
  $qry = new PgQuery( "INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified ) VALUES( ?, ?, ?, ?, ?, ?, current_timestamp, current_timestamp )",
                        $request->user_no, $event_path, $etag, $icalendar, $ic->type, $session->user_no );
  if ( !$qry->Exec("PUT") ) rollback_on_error();

  $sql = "";
  if ( preg_match(':^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Brazil|Canada|Chile|Etc|Europe|Indian|Mexico|Mideast|Pacific|US)/[a-z]+$:i', $ic->tz_locn ) ) {
    // We only set the timezone if it looks reasonable enough for us
    $sql = ( $ic->tz_locn == '' ? '' : "SET TIMEZONE TO ".qpg($ic->tz_locn).";" );
  }

  $dtstart = $ic->Get('dtstart');
{'fraction_non_alphanumeric': 0.21615639985245297, 'fraction_numerical': 0.004795278495020288, 'mean_word_length': 3.500414937759336, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 46, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6318288', 'n_tokens_mistral': 2087, 'n_tokens_neox': 2006, 'n_words': 451}