Adding a tag to existing Note? - php

I'm trying to update a note(s) that are returned from an Evernote search using PHP. The search part works just fine, but once I find the list of notes I can't seem to add a tag to the note. I can confirm that tag GUIDs are correct in both cases.
use EDAM\NoteStore\NoteFilter;
$client = new Client(array(
'token' => $authToken,
'sandbox' => true
));
$filter = new NoteFilter();
$filter->words = "HIGH";
$filter->tagGuids = array("ababe33d-75e6-4a50-b2ba-61889bb2b8a6");
$notes_result = $client->getNoteStore()->findNotes($filter, 0, 10);
$notes = $notes_result->notes;
foreach ($notes as $note) {
echo $note->title . "\n";
// **** ERROR HERE ****
$note->updateTag($authToken, "b3b290fa-4ca0-493e-8dd1-5cf1bff28b92");
}

The error you get is because updateTag must be called on NoteStore, not the note object. But: NoteStore.updateTag updates the tag object itself. To add tag to a note one needs NoteStore.updateNote instead. Your API token must also support write permission on notes.

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

Cannot read data from Patreon JSON API

Using the code given from Packagist (https://packagist.org/packages/patreon/patreon?q=&p=6), I am unable to get the expected results. My code now logs the user in, and returns their data (which I can view via var_dump), but I'm having issues actually reading it.
According to the Patreon API documentation, the data received from the API is automatically set as an array, unless specified otherwise. I'm running the exact code from their website but their API is returning an object, and I'm not sure how to read the user's data and pledge information from it. I've tried setting the return data as an array or json without any luck. I'm just getting this jumbled mess when I convert the API response into an array.
Screenshot - https://i.gyazo.com/3d19f9422c971ce6e082486cd01b0b92.png
require_once __DIR__.'/vendor/autoload.php';
use Patreon\API;
use Patreon\OAuth;
$client_id = 'removed';
$client_secret = 'removed';
$redirect_uri = "https://s.com/redirect";
$href = 'https://www.patreon.com/oauth2/authorize?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode($redirect_uri);
$state = array();
$state['final_page'] = 'http://s.com/thanks.php?item=gold';
$state_parameters = '&state=' . urlencode( base64_encode( json_encode( $state ) ) );
$href .= $state_parameters;
$scope_parameters = '&scope=identity%20identity'.urlencode('[email]');
$href .= $scope_parameters;
echo 'Click here to login via Patreon';
if (isset($_GET['code']))
{
$oauth_client = new OAuth($client_id, $client_secret);
$tokens = $oauth_client->get_tokens($_GET['code'], $redirect_uri);
$access_token = $tokens['access_token'];
$refresh_token = $tokens['refresh_token'];
$api_client = new API($access_token);
$campaign_response = $api_client->fetch_campaign();
$patron = $api_client->fetch_user();
$patron = (array)$patron;
die(var_dump($patron));
}
I want to be able to view the user's data and pledge information. I've tried things such as $patron->data->first_name, $patron['data']['first_name'], etc. which have all thrown errors about the index of the array not being found.
You've probably already figured something out but I ran into the same thing and thought I'd share a solution here.
The JSONAPIResource object that the patreon library returns has a few specific methods that can return the individual pieces of data in a readable format.
import patreon
from pprint import pprint
access_token = <YOUR TOKEN HERE> # Replace with your creator access token
api_client = patreon.API(access_token)
campaign_response = api_client.fetch_campaign()
campaign = campaign_response.data()[0]
pprint(campaign.id()) # The campaign ID (or whatever object you are retrieving)
pprint(campaign.type()) # Campaign, in this case
pprint(campaign.attributes()) # This is most of the data you want
pprint(campaign.attribute('patron_count')) # get a specific attribute
pprint(campaign.relationships()) # related entities like 'creator' 'goals' and 'rewards'
pprint(campaign.relationship('goals'))
pprint(campaign.relationship_info())
# This last one one ends up returning another JSONAPIResource object with it's own method: .resource() that returns a list of more objects
# for example, to print the campaign's first goal you could use:
pprint( campaign.relationship_info('goals').resource()[0].attributes() )
Hope that helps someone!

is there an API for PHP_CodeSniffer?

Does PHP_CodeSniffer have an API I can use, rather than run the command line?
So given a string of PHP code, $code, and Composer ensuring loading of the PHP_CodeSniffer code, is there something I can do such as:
// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);
rather than go via the command line with something like:
$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));
There is, but you need to write more code than that.
Take a look at the example here: https://gist.github.com/gsherwood/aafd2c16631a8a872f0c4a23916962ac
That example allows you to sniff a piece of code that isn't written to a file yet, and set up things like the standard to use (could also be a ruleset.xml file).
Another example, that uses the JS tokenizer instead of PHP + pulls content from an existing file, is available here: https://gist.github.com/gsherwood/f17cfc90f14a9b29eeb6b2e99e6e7f66
It is shorter because it doesn't use as many options.
Here's what I got working for PHPCS 2:
PHP_CodeSniffer::setConfigData(
'installed_paths',
// The path to the standard I am using.
__DIR__ . '/../../vendor/drupal/coder/coder_sniffer',
TRUE
);
$phpcs = new PHP_CodeSniffer(
// Verbosity.
0,
// Tab width
0,
// Encoding.
'iso-8859-1',
// Interactive.
FALSE
);
$phpcs->initStandard('Drupal');
// Mock a PHP_CodeSniffer_CLI object, as the PHP_CodeSniffer object expects
// to have this and be able to retrieve settings from it.
// (I am using PHPCS within tests, so I have Prophecy available to do this. In another context, just creating a subclass of PHP_CodeSniffer_CLI set to return the right things would work too.)
$prophet = new \Prophecy\Prophet;
$prophecy = $prophet->prophesize();
$prophecy->willExtend(\PHP_CodeSniffer_CLI::class);
// No way to set these on the phpcs object.
$prophecy->getCommandLineValues()->willReturn([
'reports' => [
"full" => NULL,
],
"showSources" => false,
"reportWidth" => null,
"reportFile" => null
]);
$phpcs_cli = $prophecy->reveal();
// Have to set these properties, as they are read directly, e.g. by
// PHP_CodeSniffer_File::_addError()
$phpcs_cli->errorSeverity = 5;
$phpcs_cli->warningSeverity = 5;
// Set the CLI object on the PHP_CodeSniffer object.
$phpcs->setCli($phpcs_cli);
// Process the file with PHPCS.
$phpcsFile = $phpcs->processFile(NULL, $code);
$errors = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();
$total_error_count = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount());
// Get the reporting to process the errors.
$this->reporting = new \PHP_CodeSniffer_Reporting();
$reportClass = $this->reporting->factory('full');
// This gets you an array of all the messages which you can easily work over.
$reportData = $this->reporting->prepareFileReport($phpcsFile);
// This formats the report, but prints it directly.
$reportClass->generateFileReport($reportData, $phpcsFile);

Docusign API PHP TemplatesApi::updateDocument FORMAT_CONVERSION_ERROR

I'm trying to update a template document via PHP API using this: https://github.com/docusign/docusign-php-client/blob/master/src/Api/TemplatesApi.php#L4946
I get one of two errors depending on if I set the apply_document_fields option.
Without it set, I get UNSPECIFIED ERROR Value cannot be null.\r\nParameter name: fileBytes. However, if I view the request body before sending, document_base_64 is set as expected.
With apply_document_fields set 'true' (actual boolean value is not supported), I get FORMAT_CONVERSION_ERROR The data could not be converted.
Either way, it seems like the document data is not getting sent correctly, but I can't figure out how I'm supposed to be sending it. Here's my code:
public static function updateTemplateWithDocument(string $documentId, string $templateId, $documentBody = null)
{
$api = My_Service_Docusign::getInstance();
$templatesApi = new DocuSign\eSign\Api\TemplatesApi($api->getAuth());
$document = new \DocuSign\eSign\Model\Document();
$document->setDocumentBase64(base64_encode($documentBody));
// Got an error reusing $documentId, so I'm incrementing it now
$document->setDocumentId((string) (((int)$documentId) + 1));
$def = new DocuSign\eSign\Model\EnvelopeDefinition();
$def->setDocuments(array($document));
$opts = new \DocuSign\eSign\Api\TemplatesApi\UpdateDocumentOptions();
// Different behavior with this set vs not
$opts->setApplyDocumentFields('true');
$res = $tmpApi->updateDocument($api->getAccountId(), $documentId, $templateId, $def, $opts);
return $res;
}
Unfortunately, DocuSign support doesn't support their API :-(
I figured out I need to use TemplatesApi::updateDocuments (plural) instead, which also allows me to reuse the documentId.

How do I use the twilio-php library to retrieve all calls made between two dates?

Using the following code I am able to get the logs of calls and SMS's. How do I modify this code to only search between certain dates using PHP?
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken, $ApiVersion);
// http://www.twilio.com/docs/quickstart...
try {
// Get Recent Calls
foreach ($client->account->calls as $call) {
echo "Call from $call->sid : $call->from to $call->to at $call->start_time of length $call->duration $call->price <br>";
}
}
catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
You will want to add a code snippet that looks something like this:
$client = new Services_Twilio('AC123', '123');
foreach ($client->account->calls->getIterator(0, 50, array(
'StartTime>' => '2012-04-01',
'StartTime<' => '2012-05-01'
)) as $call) {
echo "From: {$call->from}\nTo: {$call->to}\nSid: {$call->sid}\n\n";
}
If you want to filter the list, you have to construct the iterator yourself with the getIterator command. There's more documentation here: Filtering Twilio Calls with PHP
User search terms StartTime> and StartTime< for this. First one means call start time is greater than and last one means call start time is less than.
To find every calls that started between 4th and 6th July of 2009 add search term
array(
'StartTime>' => '2009-07-04',
'StartTime<' => '2009-07-06'
)
See example 4 on the twilio doc.
Also note you can always ask twilio support. They usually help gladly.

Categories