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

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);
...

Related

PHP NetSuite - Advanced Search with criterion

I have PHP code for Advanced Search items in NetSuite,
but I don't know how I can combine to my search - filtering by item name.
My code is:
$service = new NetSuiteService($config);
$service->setSearchPreferences(true, $page_size, true);
$savedSearchId = '###';
$searchAdvanced = new ItemSearchAdvanced();
setFields($searchAdvanced, array('savedSearchScriptId'=>$savedSearchId));
$request = new SearchRequest();
$request->searchRecord = $searchAdvanced;
$results = $service->search($request);
I want to combine a criteria
Here's sample code I found to get inventory details using Item internal id as a filter. You can reference Suite Answer 90401, 37585, and 25066.
<?php
require_once '../PHPToolkit/NetSuiteService.php';
$service = new NetSuiteService();
// formulate the criteria
$itemRecord = new RecordRef();
$itemRecord--->internalId = 140;
$itemMultiSelect = new SearchMultiSelectField();
$itemMultiSelect->operator = 'anyOf';
$itemMultiSelect->searchValue = $itemRecord;
$itemSearchBasic = new ItemSearchBasic();
$itemSearchBasic->internalId = $itemMultiSelect;
$criteria = new ItemSearch();
$criteria->basic = $itemSearchBasic;
// formulate the resulting columns
$searchRowBasic = new ItemSearchRowBasic();
$searchRowBasic->itemId = new SearchColumnStringField(); // Item Name/Number in UI
$searchRowBasic->internalId = new SearchColumnSelectField(); // Internal ID in UI
$searchRowBasic->location = new SearchColumnSelectField(); // Location (Main section of Inventory Item) in UI
$searchRowBasic->inventoryLocation = new SearchColumnSelectField(); // Location column in Locations tab (Inventory Item) in UI
$searchRowBasic->locationQuantityOnHand = new SearchColumnDoubleField();// Quantity on Hand column in Locations tab (Inventory Item) in UI
$columns = new ItemSearchRow();
$columns->basic = $searchRowBasic;
// item search advanced
$search = new ItemSearchAdvanced();
$search->criteria = $criteria;
$search->columns = $columns;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $service->search($request);
if (!$searchResponse->searchResult->status->isSuccess) {
echo "SEARCH ERROR";
} else {
echo "SEARCH SUCCESS, records found: " . $searchResponse->searchResult->totalRecords ;
}
?>

Entry in database not being overwritten when looking at ID

I'm currently looking at a script that a previous developer made that is meant to look a table, if the id does not exist then create the new code, if it does exist, overwrite the existing one.
Sounds fairly simple, but I can't get my head around how Yii manages the overwrite and new verification code. It is only adding new records, not over writing.
$invitingUser = User::model()->findByPk(Yii::app()->user->id);
if ($invitingUser->isAttending($eventId)) {
// Event attending
$event = Event::model()->findByPk($eventId);
//
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($guestInviteForm));
if (isset($_POST['GuestInviteForm'])) {
$guestInviteForm->attributes = $_POST['GuestInviteForm'];
// Perform Validation
$valid = $guestInviteForm->validate();
if ($valid) {
// Check if a Verification Code entry for this user already exists
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
The code never seems to enter the else here
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
1st. After form validation:
if ($valid) {
Verification code select done:
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
If you translate it to SQL it will be something like this:
SELECT * FROM verification_code WHERE user_id=x AND type=x
2nd. Check if record exists
if (is_null($existingVerificationCode)) {
If its not - creating new, populating, saving.
Else updating:
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
save(false) means save without validation. Consider model attributes - fields in your database table.
Seems like it ever goes in the ELSE because it never finds $existingVerificationCode.
We don't have the whole code, but from what I see, I suspect you're checking the wrong user, because it's weird to search for an event for $user, and if that doesn't exist, to create one related to $invitingUser.
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
// ...
$verificationCode->user_id = $invitingUser->id;

get Google AdWords API all campaign stats for total impressions and clicks

How to get total impressions and clicks for all campaigns on Google AdWords API?
Right now I am doing this way
// Get the service, which loads the required classes.
$campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields =
array('Id', 'Name', 'Impressions', 'Clicks', 'Cost', 'Ctr');
$selector->predicates[] =
new Predicate('Impressions', 'GREATER_THAN', array(0));
// Set date range to request stats for.
$dateRange = new DateRange();
$dateRange->min = date('Ym01', time());
$dateRange->max = date('Ymd', time());
$selector->dateRange = $dateRange;
// Make the get request.
$page = $campaignService->get($selector);
// get results.
$impressions = 0;
$clicks = 0;
if (isset($page->entries)) {
foreach ($page->entries as $campaign) {
$impressions += $campaign->campaignStats->impressions;
$clicks += $campaign->campaignStats->clicks;
}
} else {
//print "No matching campaigns were found.\n";
}
return array('impressions'=>$impressions, 'clicks'=>$clicks);
I am wondering if I can just get total without using foreach and loop through the campaigns.
To get account-level stats, you can use the AdWords API's ACCOUNT_PERFORMANCE_REPORT. You can download this report in CSV format.
I am a Rubyist, but I believe that this should work for the PHP client library:
// AdWordsUser credentials come from "../auth.ini"
$user = new AdWordsUser();
$filePath = YOUR_FILE_PATH;
$user->LoadService('ReportDefinitionService', ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array('AccountId', 'AccountDescriptiveName', 'Impressions', 'Clicks', 'Cost', 'Ctr');
// no predicate necessary - this report already excludes zero-impression lines;
// plus, there is only one line, because it's the whole account
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = WHATEVER_YOU_WANT_IT_TO_BE_NAMED;
$reportDefinition->dateRangeType = 'LAST_7_DAYS';
$reportDefinition->reportType = 'ACCOUNT_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'CSV';
$options = array('returnMoneyInMicros' => TRUE);
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
$startDate = date('Ymd', strtotime('2018-10-12'));
$endDate = date('Ymd', strtotime('2018-11-13'));
$query = (new ReportQueryBuilder())
->select([
'CampaignId',
'AdGroupId',
'Impressions',
'Clicks',
'Cost'
])
->from(ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT)
->where('Status')->in(['ENABLED', 'PAUSED'])
->during($startDate, $endDate)
->build();

Edit a custom field in netsuite using PHP toolkit

I see a bunch of examples of how to add a new order however I'm trying to update a custom field of an existing order using the PHP toolkit. Could anyone start me out with this? I'm not sure where to start.
This is the code to add a new order
<?php
require_once '../PHPToolkit/NetSuiteService.php';
$service = new NetSuiteService();
$svr = new getSelectValueRequest();
$svr->fieldDescription = new GetSelectValueFieldDescription();
$svr->pageIndex = 1;
$priceFields = array(
'recordType' => RecordType::salesOrder,
'sublist' => 'itemList',
'field' => 'price',
'filterByValueList' => array(
'filterBy' => array(
array(
'field' => 'item',
'sublist' => 'itemList',
'internalId' => '458',
)
)
)
);
if ($id != null) {
echo "Custom price level id is " . $id . "\n";
} else {
echo "Custom price level not found " . $id . "\n";
}
$so = new SalesOrder();
$so->entity = new RecordRef();
$so->entity->internalId = 21;
$so->itemList = new SalesOrderItemList();
$soi = new SalesOrderItem();
$soi->item = new RecordRef();
$soi->item->internalId = 104;
$soi->quantity = 3;
$soi->price = new RecordRef();
$soi->price->internalId = $id;
$soi->amount = 55.3;
$so->itemList->item = array($soi);
$request = new AddRequest();
$request->record = $so;
$addResponse = $service->add($request);
if (!$addResponse->writeResponse->status->isSuccess) {
echo "ADD ERROR";
exit();
} else {
echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
}
?>
You'll need a customFieldList object, which is an array of custom fields. There are different objects for the different data types of custom fields - below would be a string custom field. I utf8_encode to deal with weird characters that you normally don't see.
$customFieldList = new CustomFieldList();
$customField = new StringCustomFieldRef();
$customField->value = utf8_encode("contents of string custom field");
$customField->internalId = 'custbody_whatever_your_field_is';
$customFieldList->customField[] = $customField;
$so->customFieldList = $customFieldList;

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