Get image url from Netsuite File Cabinet in PHP - php

Is it possible to grab the url Netsuite uses for an item image using the PHP Toolkit? Using this function:
function getProduct($id) {
$service = new NetSuiteService();
$service->setSearchPreferences(false, 1000);
$itemInfo = new SearchMultiSelectField();
$itemInfo->operator = "anyOf";
$itemInfo->searchValue = array('internalId' => $id);
$search = new ItemSearchBasic();
$search->internalId = $itemInfo;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $service->search($request);
$products = $searchResponse->searchResult->recordList->record;
return $products;
}
I can get the item information. In the information, netsuite gives me this little snippet (the whole thing is truncated for cleanliness):
...
[storeDisplayImage] => RecordRef Object
(
[internalId] => 19876
[externalId] =>
[type] =>
[name] => 4010024.jpg
)
...
This just tells me the name of the file in the Netsuite file cabinet. How do I download that image automatically using the PHP Toolkit?

Try this:
$request2 = new GetRequest();
$request2->baseRef = new RecordRef();
$request2->baseRef->internalId = $product->storeDisplayImage->internalId;
$request2->baseRef->type = "file";
$getResponse2 = $this->service->get($request2);
if (!$getResponse2->readResponse->status->isSuccess) {
echo "GET ERROR";
} else {
$file = $getResponse2->readResponse->record;
echo "GET SUCCESS, File name is " . $file->name;
echo "<img src='".$file->url."'>";
}

I think you will want to look at:
["storeDisplayImage"]=>
object(RecordRef)#20 (4) {
["internalId"]=>
string(6) "758653"
["externalId"]=>
NULL
["type"]=>
NULL
["name"]=>
string(26) "image_name.jpg"
}
I cannot find any way to actually access the image, but if it is possible, the internalId (758653) is what you should be using to search. It is used when accessing the image via URL:
https://system.netsuite.com/core/media/media.nl?id=758653&c=ACCOUNT#&h=31578b297cc0be65db1f&expurl=T
The problem is that random hash at the end of the URL. I can't quite figure out what it is, but if you could, you would be able to construct that URL.
EDIT: nlapiResolveURL might help you. Try passing the internalId to nlapiResolveURL and it could provide that URL dynamically.

Related

Google Drive - Obtaining the FileSize of a File with Just the FileID

I need to obtain a file's meta-data from just using the Google Drive FileID only. The assumption being that I don't have knowledge of the folderID. By just using the FileID the API just returns null for the filesize but the correct values for the other meta-data.
Just to be clear, I can get all the meta data (including filesize) by processing the files within a folder, for example:
<?php
/*
* With this example I have the folderID from a Google Drive shared link
*/
$folderId = "https://drive.google.com/drive/folders/1ggWcacF9qQroZOkhfb3tTEwvBzclccwI?usp=share_link";
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client = $Auth->initializeClient($client);
$drive = new DriveService($client);
$pattern = "/[-\w]{25,}(?!.*[-\w]{25,})/";
if (preg_match($pattern, $folderId, $match)); // grabs folderID from the url
/*
* Now list the folder contents
*/
$responseFiles = $drive->ListFiles($match[0]);
$files = $responseFiles['files'];
foreach ($files as $file) {
$id[] = $file->id;
$name[] = $file->name;
$mimeType[] = $file->mimeType;
$size[] = $file->size; //<- correct file size
};
$drive->DownloadFile($id, $name, $size);
The code below, which I need to work, returns most of the meta-data except that, as stated above, the $file->size is always null. My DownloadFile method needs the file size so that it can better handle large files. Is there anyone who can help me better understand the problem?
<?php
/*
* With this example I have the only the fileID from a Google Drive shared link
*/
$fileId = "https://drive.google.com/file/d/1EjNk1ijPLKJMwXfzkEIG487HFzx0v80v/view?usp=share_link";
$Auth = new Oauth2Authentication();
$client = $Auth->GetClient();
$client = $Auth->initializeClient($client);
$drive = new DriveService($client);
$pattern = "/[-\w]{25,}(?!.*[-\w]{25,})/";
if (preg_match($pattern, $fileId, $match)); // grabs fileID from the url
/*
* Now get the file meta data and download the file
*/
$fileId = $match[0];
$service = new Google_Service_Drive($client);
$file = $service->files->get($fileId);
$drive->DownloadFile($file->id, $file->name, $file->size); //$file->size is always null
Update: Thanks to #DaImTo I was pointed in the right direction. The full fileID's details can be obtained by adding
array('fields' =>'*')
to the argument list of the $service->files->get method, i.e.
$file = $service->files->get($fileId,array('fields' =>'*'));
Files.list retuns a list of files with limited response.
files": [
{
"kind": "drive#file",
"mimeType": "application/vnd.google-apps.spreadsheet",
"id": "1x8-vD-X2wltablGF22Lpwup8VtxNY",
"name": "Experts Activity Dump go/ExpertsActivities"
},
To get the file size either tweek the optimal parameter fields or just use .
Fileds=*
or
$responseFiles = $drive->ListFiles($match[0],array('fields' =>'*'))

Square up php create card using php sdk api - card nonce error

I have tried to fix this issue but unable to do so. Field 'card_nonce' is not found on the server although it is recently created. I have used npm and node to generate a card_nonce.
Code Used:
$billing_address = new Address();
$billing_address->setAddressLine1('500 Electric Ave');
$billing_address->setAddressLine2('Suite 600');
$billing_address->setLocality('New York');
$billing_address->setAdministrativeDistrictLevel1('NY');
$billing_address->setPostalCode('10003');
$billing_address->setCountry('AU');
// $body = new CreateCustomerCardRequest($_POST['nonce']);
$body = new CreateCustomerCardRequest('CBASECw9ri-7s1THlCWDoSVsVY8');
$body->setBillingAddress($billing_address);
$body->setCardholderName('Gaurav Gulati');
$api_response = $customersApi->createCustomerCard($customer_id, $body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$customer_card = $api_response->getCard();
$customer_card_id = $customer_card->getId();
} else {
$errors = $api_response->getErrors();
}
Response:
[0] => Square\Models\Error Object
(
[category:Square\Models\Error:private] => INVALID_REQUEST_ERROR
[code:Square\Models\Error:private] => NOT_FOUND
[detail:Square\Models\Error:private] => Resource not found.
[field:Square\Models\Error:private] => card_nonce
)
Anyone has idea how to resolve this error.
You've removed the "cnon:" from the parameter. "CBASECw9ri-7s1THlCWDoSVsVY8" should be cnon:CBASECw9ri-7s1THlCWDoSVsVY8.

How to MODIFY a Google Docs document via API using search-and-replace?

I need an example of how to modify an existing document with existing text in Google Docs via API. The documentation only shows how to insert and delete text, but not how to update. Have been looking frantically on the web to find examples or a direction on how to do it but without luck.
Finally figured it out myself.
First, follow this video to prepare authentication to the Google Docs API (even though it's about Google Sheets but the process is basically the same). Basically it consists of these steps:
create project in Google Developer Console
enable Google Docs API
create credentials, including a service account for programmatic access
share your document with the service account client email address
install Google API's PHP client: composer require google/apiclient
Then create a script like the following:
require_once(__DIR__ .'/vendor/autoload.php');
$client = new \Google_Client();
$client->setApplicationName('Some name'); //this name doesn't matter
$client->setScopes([\Google_Service_Docs::DOCUMENTS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ .'/googleapi-credentials.json'); //see https://www.youtube.com/watch?v=iTZyuszEkxI for how to create this file
$service = new \Google_Service_Docs($client);
$documentId = 'YOUR-DOCUMENT-ID-GOES-HERE'; //set your document ID here, eg. "j4i1m57GDYthXKqlGce9WKs4tpiFvzl1FXKmNRsTAAlH"
$doc = $service->documents->get($documentId);
// Collect all pieces of text (see https://developers.google.com/docs/api/concepts/structure to understand the structure)
$allText = [];
foreach ($doc->body->content as $structuralElement) {
if ($structuralElement->paragraph) {
foreach ($structuralElement->paragraph->elements as $paragraphElement) {
if ($paragraphElement->textRun) {
$allText[] = $paragraphElement->textRun->content;
}
}
}
}
// Go through and create search/replace requests
$requests = $textsAlreadyDone = $forEasyCompare = [];
foreach ($allText as $currText) {
if (in_array($currText, $textsAlreadyDone, true)) {
// If two identical pieces of text are found only search-and-replace it once - no reason to do it multiple times
continue;
}
if (preg_match_all("/(.*?)(dogs)(.*?)/", $currText, $matches, PREG_SET_ORDER)) {
//NOTE: for simple static text searching you could of course just use strpos()
// - and then loop on $matches wouldn't be necessary, and str_replace() would be simplified
$modifiedText = $currText;
foreach ($matches as $match) {
$modifiedText = str_replace($match[0], $match[1] .'cats'. $match[3], $modifiedText);
}
$forEasyCompare[] = ['old' => $currText, 'new' => $modifiedText];
$replaceAllTextRequest = [
'replaceAllText' => [
'replaceText' => $modifiedText,
'containsText' => [
'text' => $currText,
'matchCase' => true,
],
],
];
$requests[] = new \Google_Service_Docs_Request($replaceAllTextRequest);
}
$textsAlreadyDone[] = $currText;
}
// you could dump out $forEasyCompare to see the changes that would be made
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
This is my way - easy one
public function replaceText($search, $replace)
{
$client = $this->getClient();
$service = new \Google_Service_Docs($client);
$documentId = ''; // Put your document ID here
$e = new \Google_Service_Docs_SubstringMatchCriteria();
$e->text = "{{".$search."}}";
$e->setMatchCase(false);
$requests[] = new \Google_Service_Docs_Request(array(
'replaceAllText' => array(
'replaceText' => $replace,
'containsText' => $e
),
));
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $requests
));
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
}

how to parse returned value from asmx

I want to send some values from php to an asmx webservce.
my code work's fine, but the return value is like this :
object(stdClass)#4 (1) { ["any"]=> string(963) "123" }
now, how to get 123 value ?
require_once('lib/nusoap.php');
$client = new SoapClient("http://****/service.asmx?WSDL");
$params->UserName = '1';
$params->PassWord = '1!';
$params->Ip = '1!';
$params->MacMain = '1!';
$params->PcName = '1!';
$result = $client->GetPassPort($params)->GetPassPortResult;
var_dump($result);
while getting data from object you need to use -> operator.Just use below code to get 123 as :
$result->any

Cannot instantiate a Note object using Evernote API in PHP

I am trying to develop a script (using the PHP example app as a basis) that will post a note to Evernote based on GET values.
When I insert this to the end of functions.php's listNotebooks()
$note_obj = new Note(array(
'contents' => $note_contents,
'title' => $title
));
It throws a 500 error. (In my code, $title & $note_contents are defined earlier. I have spent a lot of time trying to find proper documentation for the PHP API but it just seems non-existent. Any information on this topic would be greatly appreciated
Update: I did not realize the API was using PHP Namespaces: This fixed the issue:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
My code to add a note still does not work but I'll post it here once I figure it out.
These classes need to be imported:
//import Note class
use EDAM\Types\Note;
use EDAM\Types\NoteAttributes;
use EDAM\NoteStore\NoteStoreClient;
This will define our new note:
$noteAttr = new NoteAttributes();
$noteAttr->sourceURL = "http://www.example.com";
$note = new Note();
$note->guid = null;
$note->title = "My Title";
$note->content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd"><en-note>My Content</en-note>';
$note->contentHash = null;
$note->contentLength = null;
$note->created = time()*1000;
$note->updated = time()*1000;
$note->deleted = null;
$note->active = null;
$note->updateSequenceNum = null;
$note->notebookGuid = null;
$note->tagGuids = null;
$note->resources = null;
$note->attributes = $noteAttr;
$note->tagNames = null;
addNote($note);
This function will add a new note:
function addNote($newnote) {
global $noteRet;
if (empty($noteRet)) {
define("noteStoreHost", "sandbox.evernote.com");
define("noteStorePort", "80");
define("noteStoreProto", "https");
define("noteStoreUrl", "edam/note/");
$noteStoreTrans = new THttpClient(noteStoreHost, noteStorePort, noteStoreUrl . $_SESSION['shardId'], noteStoreProto);
$noteStoreProt = new TBinaryProtocol($noteStoreTrans);
$noteStore = new NoteStoreClient($noteStoreProt, $noteStoreProt);
$noteRet = $noteStore->createNote($_SESSION['accessToken'], $newnote);
return $noteRet;
}
}

Categories