Create recurring CalendarItem with php-ews - php

Trying to implement MS Exchange api CalendarItem creation useng jamesiarmes/php-ews. Was able to create simple events and events with partisipants, but when i tried to add recurrence - nothing works.
Saw similar questions - they are outdated and of no use anymore.
This is what i have:
public function createCalendarItem(array $eventData) {
$request = new CreateItemType();
$request->Items = new NonEmptyArrayOfAllItemsType();
//Event accembly---------------------------
$event = new CalendarItemType();
$event->Start = $eventData['startTime'];
$event->End = $eventData['endTime'];
$event->Subject = $eventData['subject'];
$event->Location = $eventData['location'];
//In case event is recurring---------------
if ($eventData['isRecurring']) {
$event->CalendarItemType = CalendarItemTypeType::RECURRING_MASTER;
$recurrence = new RecurrenceType();
switch ($eventData['recurrenceDetails']['type']) {
case 'daily':
$recurrence->DailyRecurrence = new DailyRecurrencePatternType();
$event->Recurrence = $recurrence;
break;
case 'weekly':
$weeklyRecurrenceInfo = new WeeklyRecurrencePatternType();
$weeklyRecurrenceInfo->Interval = $eventData['recurrenceDetails']['interval'];
$weeklyRecurrenceInfo->DaysOfWeek = new ArrayOfStringsType();
$weeklyRecurrenceInfo->DaysOfWeek = [DayOfWeekType::THURSDAY];
$recurrence->WeeklyRecurrence = $weeklyRecurrenceInfo;
$event->Recurrence = $recurrence;
break;
case 'monthly':
break;
case 'yearly';
break;
case 'custom':
break;
}
}
//-----------------------------------------
$eventBody = new BodyType();
$eventBody->_ = $eventData['description'];
$eventBody->BodyType = BodyTypeType::TEXT;
$event->Body = $eventBody;
// In case new event should have a list of partisipants
if(!empty($eventData['attendees'])) {
$event->RequiredAttendees = new NonEmptyArrayOfAttendeesType();
$event->RequiredAttendees->Attendee = array();
foreach ($eventData['attendees'] as $guest) {
$attendee = new AttendeeType();
$attendee->Mailbox = new EmailAddressType();
$attendee->Mailbox->EmailAddress = $guest['email'];
$attendee->Mailbox->Name = $guest['name'];
$attendee->Mailbox->RoutingType = RoutingType::SMTP;
$event->RequiredAttendees->Attendee[] = $attendee;
}
}
$request->Items->CalendarItem[] = $event;
//--------------------------------------------
$request->SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType::SEND_TO_NONE;
$response = $this->client->CreateItem($request);
return $response;
}
Can anyone explain me, what am i doing wrong?
'daily' option just causes "Request is invalid":
local.ERROR: The request is invalid. {"userId":11,"exception":"[object] (SoapFault(code: 0 faultcode: a:ErrorInvalidRequest detail: {\"ResponseCode\":\"ErrorInvalidRequest\",\"Message\":\"The request is invalid.\"}): The request is invalid. at /var/www/html/vendor/php-ews/php-ews/src/Client.php:1631)
on line $response = $this->client->CreateItem($request);
But there is not a single property to be set in DailyRecurrencePatternType, so i don't get what could be a cause.
'weekly' option causes response to be:
+CreateItemResponseMessage: array:1 [▼
0 => jamesiarmes\PhpEws\Response\ItemInfoResponseMessageType {#2516 ▼
+DescriptiveLinkKey: 0
+MessageText: "Set action is invalid for property."
+MessageXml: {#2495 ▼
+"any": array:1 [▼
"FieldURI" => jamesiarmes\PhpEws\Type\PathToUnindexedFieldType {#2493 ▼
+FieldURI: "calendar:CalendarItemType"
}
]
}
+ResponseClass: "Error"
+ResponseCode: "ErrorInvalidPropertySet"
+Items: jamesiarmes\PhpEws\ArrayType\ArrayOfRealItemsType {#2517 ▶}
}
]
But if i get it right, it says that event type itself defined wrong. How could that be?

Related

How to post an event directly to another user's calendar

i want To post an event directly to another user's calendar with jamesiarmes/php-ews but in example i have find only how to make it with invitation.
I have admin account so i can write in athers user's post calendar directly.
i don't understant a lot because i'm new in ews so thx for any help.
// Replace this with your desired start/end times and guests.
$start = new DateTime('tomorrow 4:00pm');
$end = new DateTime('tomorrow 5:00pm');
$guests = array(
array(
'name' => 'Homer Simpson',
'email' => 'hsimpson#example.com',
),
array(
'name' => 'Marge Simpson',
'email' => 'msimpson#example.com',
),
);
// Set connection information.
$host = '';
$username = '';
$password = '';
$version = Client::VERSION_2016;
$client = new Client($host, $username, $password, $version);
// Build the request,
$request = new CreateItemType();
$request->SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType::SEND_ONLY_TO_ALL;
$request->Items = new NonEmptyArrayOfAllItemsType();
// Build the event to be added.
$event = new CalendarItemType();
$event->RequiredAttendees = new NonEmptyArrayOfAttendeesType();
$event->Start = $start->format('c');
$event->End = $end->format('c');
$event->Subject = 'EWS Test Event';
// Set the event body.
$event->Body = new BodyType();
$event->Body->_ = 'This is the event body';
$event->Body->BodyType = BodyTypeType::TEXT;
// Iterate over the guests, adding each as an attendee to the request.
foreach ($guests as $guest) {
$attendee = new AttendeeType();
$attendee->Mailbox = new EmailAddressType();
$attendee->Mailbox->EmailAddress = $guest['email'];
$attendee->Mailbox->Name = $guest['name'];
$attendee->Mailbox->RoutingType = RoutingType::SMTP;
$event->RequiredAttendees->Attendee[] = $attendee;
}
// Add the event to the request. You could add multiple events to create more
// than one in a single request.
$request->Items->CalendarItem[] = $event;
$response = $client->CreateItem($request);
// Iterate over the results, printing any error messages or event ids.
$response_messages = $response->ResponseMessages->CreateItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
$code = $response_message->ResponseCode;
$message = $response_message->MessageText;
fwrite(STDERR, "Event failed to create with \"$code: $message\"\n");
continue;
}
// Iterate over the created events, printing the id for each.
foreach ($response_message->Items->CalendarItem as $item) {
$id = $item->ItemId->Id;
fwrite(STDOUT, "Created event $id\n");
}
}
You define the attendees but miss the account where you want to create the event in:add this code before the $response
...
$request->Items->CalendarItem[] = $event;
//following lines are missing
$lsEmail = 'some#email.de';
$request->SavedItemFolderId = new TargetFolderIdType();
$request->SavedItemFolderId->DistinguishedFolderId = new DistinguishedFolderIdType();
$request->SavedItemFolderId->DistinguishedFolderId->Id = self::DISTINGUISHED_FOLDER_ID;
$request->SavedItemFolderId->DistinguishedFolderId->Mailbox = new EmailAddressType();
$request->SavedItemFolderId->DistinguishedFolderId->Mailbox->EmailAddress = $lsEmail;
// here your code continues
$response = $client->CreateItem($request);
...

Twinfield gives error when I tried to create new invoice

I want to create an invoice to third party invoice software i.e. twinfield from API. I give all the param according to its library and doc and call from API but it will give error.
{
"success": false,
"error": "Item code not found., The description of an item line cannot be adjusted." }
The API is php-twinfield.
The code is given below.
public function saveInvoice($values)
{
try
{
$user = $values['user'];
$password = $values['password'];
$organization = $values['organisation'];
$officecode = $values['officecode'];
$connection = new \PhpTwinfield\Secure\WebservicesAuthentication($user, $password, $organization);
$customerApiConnector = new \PhpTwinfield\ApiConnectors\CustomerApiConnector($connection);
$office = Office::fromCode($officecode);
$customer = $customerApiConnector->get('1008',$office);
$InvoiceApiConnector = new \PhpTwinfield\ApiConnectors\InvoiceApiConnector($connection);
//class invoiceline object
$line = new \PhpTwinfield\InvoiceLine();
$line
->setArticle(2)
->setQuantity(2)
->setValueExcl(100)
->setUnits(1)
->setVatCode('VH')
->setUnitsPriceExcl(100)
->setDim1(8020)
->setDescription("Testinvoice anand")
->setAllowDiscountOrPremium(false);
//class invoice object
$invoice = new \PhpTwinfield\Invoice();
$invoice
->setCustomer($customer)
->setBank('BNK')
->setDueDate(\Carbon\Carbon::now()->addMonth())
->setPeriod('2018/12')
->setCurrency('EUR')
->setStatus('concept')
->setInvoiceDate('20180606')
->addLine($line)
->setPaymentMethod('cash')
->setInvoiceType('FACTUUR');
$result = $InvoiceApiConnector->send($invoice);
print_r($result);
//$jsonResponse = JsonResponse::success($result);
}
catch (SoapFault $e)
{
$jsonResponse = empty($e->getMessage()) ? JsonResponse::error(class_basename($e)) : JsonResponse::error($e->getMessage());
}
//return $jsonResponse;
}
if change in this line $line->setArticle(0) the error is like that.
{
"success": false,
"error": "ResponseException" }

Php soap data send error

When sending data to the SomeMethod() method, the 1 excess parameter returns as an error.
My Code:
$client = new SoapClient('site_url/?wsdl');
$client->soap_defencoding = 'UTF-8';
$loginparam = array('userName'=>'name','password'=>'pass','trace' => 1, 'exceptions' => 0);
$session = $client->OturumAc($loginparam);
$SoapIcHeader = new SoapHeader("http://sanayi.gov.tr","TokenId",$session->OturumAcResult);
$client->__setSoapHeaders($SoapIcHeader);
$OturumUzat = $client->OturumDogrulaVeUzat($session ->OturumAcResult);
$param["BosAgirligi"] = "20";
$param["CalismaBasinci"] = "5";
$param["DoluAgirligi"] = "1";
$param["SonMuayeneTarihi"] = "2017-08-01 10:19:04";
$param["SonMuayeneYapanFirmaMersisNo"] = "123456789";
$param["SuKapasitesi"] = "1";
$param["TestBasinci"] = "10";
$param["DolumBasinci"] = "15";
$param["EtKalinligi"] = "3";
$param["ImalatTarihi"] = "2017-08-01 10:19:04";
$param["SeriNo"] = "123";
$param["TescilEdenTesisId"] = "31fd684c-f97d-48c1-a7fb-60f30f536d8d";
$param["UreticiId"] = "31fd684c-f97d-48c1-a7fb-60f30f536d8d";
// $param["UygunlukIsareti"] = "1";
$date = date('d/m/Y');
$id ="2ad9a9a9-adb9-4fb8-8fae-01e84aa72343";
try
{
$sonuc = $client->TupTescil($id,$date,$param);
print_r($sonuc);
}
catch (Exception $e)
{
echo "Error ! ";
echo $e -> getMessage ();
}
Return Error
Error ! The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'TupTescil'. End element 'Body' from namespace 'http://schemas.xmlsoap.org/soap/envelope/' expected. Found element 'param1' from namespace ''. Line 2, position 281.
This example works with C#
Guid tupKimligi = new Guid("07FAF194-4E80-4359-95D9-011CA1F5A1D4");
DateTime islemSaati = DateTime.Today;
TupTescilBilgisi tescilBilgileri = new TupTescilBilgisi()
{
BosAgirligi = 1,
CalismaBasinci = 1,
DoluAgirligi = 1,
SonMuayeneTarihi = DateTime.Today,
SonMuayeneYapanFirmaMersisNo = "123456789",
SuKapasitesi = 1,
TestBasinci = 1,
DolumBasinci = 1,
EtKalinligi = 1,
ImalatTarihi = DateTime.Today,
SeriNo = "123",
TescilEdenTesisId = tesisId,
UreticiId = ureticiId,
UygunlukIsareti = TupUygunlukIsareti.Pi
};
Tup tescilSonuc = tsc.TupTescil(tupKimligi, DateTime.Today, tescilBilgileri);
You can also look at the wsdl structure here
enter link description here
Thanks for your help

lithium insert entity array into model object property

The following coding sample doesn't work.
$joiner = new Entity();
$joiner->name = $post['name'];
$joiner->address = $post['address'];
$meeting = Meeting::first($_id);
$meeting->joiner[] = $joiner;
$meeting->save();
I hope each time when the form posted success. a new joiner entity should be pushed into the 'joiner' property of meeting object.
How to correct it ? and thanks for all help.
updated
now I have changed it like this .it works fine but still not very good yet.
$joiner = new Entity();
$joiner->name = $post['name'];
$joiner->address = $post['address'];
$meeting = Meeting::first($_id);
if(empty($meeting->joiner)){
$joiners = array($joiner);
}
else{
$joiners = array();
foreach($meeting->joiner as $one){
$joiners[] = $one;
}
$joiners[] = $joiner;
}
$meeting->joiner = $joiners;
$meeting->save();

PHP-EWS 2010, how to set the IsRead flag

I have been able to successfully retrieve the unread emails from an Exchange 2010 inbox using php-ews API. However after I have fetched the emails, I want to set the IsRead property of the email to true, so that these messages do not appear the next time I fetch emails.
Anyone done this before ?
EDIT :
This is how I am trying to set the IsRead flag :
$message_id = ''; //id of message
$change_key = ''; //change key
$response = $ews->GetItem($request);
//print_r($response);exit;
if( $response->ResponseMessages->GetItemResponseMessage->ResponseCode == 'NoError' &&
$response->ResponseMessages->GetItemResponseMessage->ResponseClass == 'Success' ) {
$a = array();
$message = $response->ResponseMessages->GetItemResponseMessage->Items->Message;
$a['message_body'] = $message->Body->_;
$a['sender'] = $message->From->Mailbox->EmailAddress;
$a['subject'] = $message->ConversationTopic;
$data[] = $a;
//process the message data.
$messageType = new EWSType_MessageType();
$messageType->IsRead = true;
$path = new EWSType_PathToUnindexedFieldType();
$path->FieldURI = 'message:IsRead';
$setField = new EWSType_SetItemFieldType();
$setField->Message = $messageType;
$setField->FieldURI = $path;
$u = new EWSType_ItemChangeType();
$u->Updates = new EWSType_NonEmptyArrayOfItemChangeDescriptionsType();
$u->Updates->SetItemField = $setField;
$u->ItemId = new EWSType_ItemIdType();
$u->ItemId->Id = $message_id;
$u->ItemId->ChangeKey = $change_key;
$updatedItems = new EWSType_NonEmptyArrayOfItemChangesType();
$updatedItems->ItemChange = $u;
$updateMessenger = new EWSType_UpdateItemType();
$updateMessenger->ItemChanges = $updatedItems;
$updateMessenger->MessageDisposition = 'SaveOnly';
$updateMessenger->ConflictResolution = 'AutoResolve';
try {
$update_response = $ews->UpdateItem($updateMessenger);
}catch (Exception $e){
echo $e->getMessage();
}
}
When I run the file I get the following error :
An internal server error occurred. The operation failed.
After debugging for some time, I have concluded that the error happens at the curl_exec function in NTLMSoapClient.php file.
I dont know where to go on from here. Please help.
I've faced a similar issue when updating a calendar event and setting the IsAllDayEvent flag. This is the code that worked for me:
$ews = new ExchangeWebServices(...);
$request = new EWSType_UpdateItemType();
$request->ConflictResolution = 'AlwaysOverwrite';
$request->ItemChanges = array();
$change = new EWSType_ItemChangeType();
$change->ItemId = new EWSType_ItemIdType();
$change->ItemId->Id = $id;
$change->ItemId->ChangeKey = $changeKey;
$field = new EWSType_SetItemFieldType();
$field->FieldURI = new EWSType_PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "calendar:IsAllDayEvent";
$field->CalendarItem = new EWSType_CalendarItemType();
$field->CalendarItem->IsAllDayEvent = true;
$change->Updates->SetItemField[] = $field;
$request->ItemChanges[] = $change;
$response = $ews->UpdateItem($request);
The biggest difference I see here is that you do $u->Updates->SetItemField = $setField;, whereas my code uses $u->Updates->SetItemField[] = $setField;.
I hope this helps.
Edit: You might have already seen this, but I based my code on the one from the php-ews wiki.
I tried everything including PathToExtendedFieldType and it doesn't work at the end code below worked for me
$ews = new ExchangeWebServices('red', 'red', 'red',ExchangeWebServices::VERSION_2007_SP1);
$request = new EWSType_UpdateItemType();
$request->SendMeetingInvitationsOrCancellations = 'SendToNone';
$request->MessageDisposition = 'SaveOnly';
$request->ConflictResolution = 'AlwaysOverwrite';
$request->ItemChanges = array();
// Build out item change request.
$change = new EWSType_ItemChangeType();
$change->ItemId = new EWSType_ItemIdType();
$change->ItemId->Id = $contact_id;
$change->ItemId->ChangeKey = $contact_change_key;
#$change->Updates = new EWSType_NonEmptyArrayOfItemChangeDescriptionsType();
#$change->Updates->SetItemField = array();
// Build the set item field object and set the item on it.
$field = new EWSType_SetItemFieldType();
$field->FieldURI = new EWSType_PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "message:IsRead";
$field->Message = new EWSType_MessageType();
$field->Message->IsRead = true;
$change->Updates->SetItemField[] = $field;
$request->ItemChanges[] = $change;
$response = $ews->UpdateItem($request);
var_dump($response);
Well, i dont know how it is in php, but in C# there is another field, that must be set: IsReadSpecified = true.
email.IsRead = true;
email.IsReadSpecified = true;

Categories