<?php
/**
* CalDAV Server - handle PUT method on VCARD content-types
*
* @package   davical
* @subpackage   caldav
* @author    Andrew McMillan <andrew@morphoss.com>
* @copyright Morphoss Ltd
* @license   http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
*/
dbg_error_log("PUT", "method handler");

require_once('DAVResource.php');

if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || (isset($c->dbg['put']) && $c->dbg['put'])) ) {
  $fh = fopen('/tmp/PUT.txt','w');
  if ( $fh ) {
    fwrite($fh,$request->raw_post);
    fclose($fh);
  }
}

$lock_opener = $request->FailIfLocked();

$dest = new DAVResource($request->path);

$container = $dest->GetParentContainer();
if ( ! $dest->Exists() ) {
  if ( $container->IsPrincipal() ) {
    $request->PreconditionFailed(405,'method-not-allowed',translate('A DAViCal principal collection may only contain collections'));
  }
  if ( ! $container->Exists() ) {
    $request->PreconditionFailed( 409, 'collection-must-exist',translate('The destination collection does not exist') );
  }
  $container->NeedPrivilege('DAV::bind');
}
else {
  if ( $dest->IsCollection() ) {
    if ( ! isset($c->readonly_webdav_collections) || $c->readonly_webdav_collections ) {
      $request->PreconditionFailed(405,'method-not-allowed',translate('You may not PUT to a collection URL'));
    }
    $request->DoResponse(403,translate('PUT on a collection is only allowed for text/vcard content against an addressbook collection'));
  }
  $dest->NeedPrivilege('DAV::write-content');
}

if ( isset($request->etag_none_match) && $request->etag_none_match != '*' && $dest->Exists() ) {
  $request->PreconditionFailed(412,'if-none-match', translate('A resource already exists at the destination.'));
}

if ( isset($request->etag_if_match) && $request->etag_if_match != $dest->unique_tag() ) {
  $request->PreconditionFailed(412,'if-match',sprintf('Existing resource ETag of "%s" does not match "%s"', $dest->unique_tag(), $request->etag_if_match) );
}

$collection_id = $container->GetProperty('collection_id');

$original_etag = md5($request->raw_post);

require_once('vcard.php');
$vcard = new vCard( $request->raw_post );

$qry = new AwlQuery();
$qry->Begin();

$uid = $vcard->GetPValue('UID');
if ( empty($uid) ) {
  $uid = uuid();
  $vcard->AddProperty('UID',$uid);
}

$last_modified = $vcard->GetPValue('REV');
if ( empty($last_modified) ) {
  $last_modified = gmdate( 'Ymd\THis\Z' );
  $vcard->AddProperty('REV',$last_modified);
}
elseif ( stripos($last_modified, 'TZ') ) {
  // At least one of my examples has this crap.
  $last_modified = str_replace('TZ','T000000Z',$last_modified);
  $vcard->ClearProperties('REV');
  $vcard->AddProperty('REV',$last_modified);
}
elseif( preg_match('{^(\d{8})(\d{6})Z?}', $last_modified, $matches) ) {
  $last_modified = $matches[1] . 'T' . $matches[2] . 'Z';
  $vcard->ClearProperties('REV');
  $vcard->AddProperty('REV',$last_modified);
}

$rendered_card = $vcard->Render(); 
$etag = md5($rendered_card);
$params = array(
    ':user_no' => $dest->GetProperty('user_no'),
    ':dav_name' => $dest->bound_from(),
    ':etag' => $etag,
    ':dav_data' => $rendered_card,
    ':session_user' => $session->user_no,
    ':modified' => $last_modified
);
if ( $dest->Exists() ) {
  $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, logged_user=:session_user,
          modified=:modified, user_no=:user_no, caldav_type=\'VCARD\' WHERE dav_name=:dav_name';
  $response_code = 200;
  $qry->QDo( $sql, $params );

  $qry->QDo("SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ", array(':dav_name' => $params[':dav_name']) );
}
else {
  $sql = 'INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
          VALUES( :user_no, :dav_name, :etag, :dav_data, \'VCARD\', :session_user, current_timestamp, :modified, :collection_id )';
  $params[':collection_id'] = $collection_id;
  $response_code = 201;
  $qry->QDo( $sql, $params );

  $qry->QDo("SELECT currval('dav_id_seq') AS dav_id" );
}
$row = $qry->Fetch();

$vcard->Write( $row->dav_id, $dest->Exists() );

$qry->QDo("SELECT write_sync_change( $collection_id, $response_code, :dav_name)", array(':dav_name' => $dest->bound_from() ) );

if ( !$qry->Commit() ) {
   $qry->Rollback();
   $request->DoResponse( 500, "A database error occurred" );
}

// Uncache anything to do with the collection
$cache = getCacheInstance();
$cache->delete( 'collection-'.$container->dav_name(), null );

if ( $etag == $original_etag ) header('ETag: "'. $etag . '"' ); // Only send the ETag if we didn't change what they gave us.
if ( $response_code == 200 ) $response_code = 204;
$request->DoResponse( $response_code );
