DDEV and D8, httpClient used for internal request fails to connect - drupal

I've a multisite installation of Drupal 8, the "main" website expose some REST webservices, locally i've some troubles on testing them, because there's no way for the various sites to see each other, when i try to do something like that
try {
$response = $this->httpClient->get($this->baseUri . '/myendpoint', [
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/hal+json',
],
'query' => [
'_format' => 'json',
'myparameters' => 'value'
],
]);
$results = $this->serializer->decode($response->getBody(), 'json');
}
catch (RequestException $e) {
$this->logger->warning($e->getMessage());
}
return $results;
I always receive a timeout and there's no way i can make it work, i've my main website with the usual url project.ddev.site (and $this->baseUri is https://myproject.ddev.site ) and all the other websites are in the form subsite.ddev.local
If i ssh in the project and run ping myproject.ddev.site i see 172.19.0.6
I don't understand why they cannot see each other...

Just for other people who can have a similar problem: my issue was with xdebug i have it with the autoconnect, so when the request from the subsite to the main site was made, it get stuck somewhere (phpstorm didn't stop anywhere by the way) so it made the request time out.
By disabling, or configuring only for the subdomain, and avoiding it to accept the external connenction from unconfigured servers (in phpstorm) it started working, still have to do some work as i need to debug "both sides" of the request, but in this way i can work with that...
I've not thought before to try disabling xdebug because actually it didn't came into my mind...

Related

Make an HTTP POST request to upload a file in Wordpress - HTTP POST request get converted to GET

I want to have a HTTP POST link in my Wordpress website that lets another server to post an xml file every hour into the Wordpress server and I save it.
I created an index.php file in folders that map with the route I want, let say I need example.com/jobs/uploadFile, so I created a php file inside the folders /jobs/uploadFile of the root Wordpress directory.
<?php
if( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
header($_SERVER["SERVER_PROTOCOL"]." Method Not Allowed", true, 405);
exit;
}
$postData = trim(file_get_contents('php://input'));
$xml = simplexml_load_string($postData);
if($xml === false) {
header($_SERVER["SERVER_PROTOCOL"]." Bad Request", true, 400);
exit;
}
$xml->asXml('jobs.xml');
http_response_code(200);
1- I send a HTTP POST request via postman, but somehow the server or Wordpress changes it a HTTP GET request, so always the first if condition is executed. I'm using Laravel forge server with Nginx.
2- Appreciate any security advice about this approach, CORS...?
Thanks for your help
Since it may help others, I answer my question. I was doing it the wrong way. The better way to do it is by using actions in a custom Wordpress plugin. Just create a custom plugin and use add_action inside it:
add_action( 'rest_api_init', function() {
register_rest_route(
'myapi/v1', 'myUploadURL',
[
'methods' => 'POST',
'callback' => 'my_upload_function',
'permission_callback' => '__return_true',
]
);
});
And then you can get the $_FILES of the POST request in the my_upload_function() and save it on your server.

How to fix curl_error: SSL: no alternative certificate subject name matches target host name 'api.telegram.org'

I am using telegram.php to connect my bot. When I use sendmessage all of thing is ok in my logs but I do not receive anything from the bot.
When I check my log there is a problem like this:
ok: False
curl_error_code: 51
curl_error: SSL: no alternative certificate subject name matches target host name 'api.telegram.org'
I donit know what to do to fix it.
I don't know this telegram bot, but I see that it uses GuzzleHttp.
During the initialization it doesn't accept any configuration Request::initialize()
public static function initialize(Telegram $telegram)
{
if (!($telegram instanceof Telegram)) {
throw new TelegramException('Invalid Telegram pointer!');
}
self::$telegram = $telegram;
self::setClient(new Client(['base_uri' => self::$api_base_uri]));
}
you should check its documentation. I see that there are a lot of setters which makes you able to overwrite the default settings.
What you need is to set the the \GuzzleHttp\RequestOptions::VERIFY to false in the client config:
$this->client = new \GuzzleHttp\Client([
'base_uri' => 'someAccessPoint',
\GuzzleHttp\RequestOptions::HEADERS => [
'User-Agent' => 'some-special-agent',
],
'defaults' => [
\GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
\GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true,
],
\GuzzleHttp\RequestOptions::VERIFY => false,
]);
For fix this problem copy this Url to browser and set webhook:
https://api.telegram.org/botTOKEN/setWebhook?url=https://yourwebsite.com
Solution 2 of The Error
Let’s follow these simple steps:
Download this bundle of root certificates: https://curl.haxx.se/ca/cacert.pem
Put in any location of your server.
Open php.ini and add this line:
curl.cainfo = "[the_location]\cacert.pem"
Restart your webserver.
That’s it. 🙂

HTTP client Cakephp 3 ignores json body

I'm currently writing a RESTful API in Cakephp 3 whereby I need to test a POST operation through http://host.com/api/pictures. The code for the test:
<?php
namespace App\Test\TestCase\Controller;
use App\Controller\Api\UsersController;
use Cake\TestSuite\IntegrationTestCase;
use Cake\Network\Http\Client;
use Cake\Network\Http\FormData;
class ApiPicturesControllerTest extends IntegrationTestCase{
public $fixtures = [
'app.users',
'app.comments',
'app.albums',
'app.users_albums'
];
public function testAdd(){
// $data = new FormData();
$accessToken ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$http = new Client([
'headers' => ['Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json']
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$result = $http->post('http://vecto.app/api/pictures/add.json', $data, ['type'=>'json']);
// $this->assertResponseOk();
// debug($result);
}
}
When I try to debug the result I get a 'cannot add or update child row' while I'm sure the responding id does exists
(the fixtures does have the id's too). Additionally, the log indicates that it only tries to insert the create/update rows. Therefore, I'm pretty sure the data is ignored but however I can't find a solution. I already tried different combination of headers like only application/json for Accept, application/json for Content-Type etc. I'm using the CRUD plugin for Cakephp to pass the data to an add function.
Postman output
Furthermore, I tried the Postman Chrome plugin to save the data and that actually does work. Does anyone know what I'm doing wrong in the test?
That's not how the integration test case is ment to be used. You are dispatching an external, real request, which will leave the test environment, while you should use the request dispatching tools that the integration test case supplies, that is
IntegrationTestCase::get()
IntegrationTestCase::post()
IntegrationTestCase::put()
etc...
These methods will dispatch simulated requests that do not leave the test environment, which is crucial for things to work properly, as you want to use test connections, inspect possible exceptions, have access to the used session, etc...
ie, you should do something along the lines of
$accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$this->configRequest([
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json'
]
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$this->post('/api/pictures/add.json', json_encode($data));
Note that a content type of application/json will require you to send raw JSON data! If you don't actually need/want to test parsing of raw input, then you could skip that header, and pass the array as data instead.
See also
Cookbook > Testing > Controller Integration Testing
API > \Cake\TestSuite\IntegrationTestCase

External request to Wordpress WP-API - Basic Authentication

I'm trying to hit my Wordpress API using Basic Auth with Guzzle (http tool) from my middleware (Laravel).
$username = 'myAdminUserName';
$password = 'myAdminPassword';
$uri = 'https://example.com/wp-json/mysite-api/cleared-action';
$response = $this->guzzle->put(
$uri,
[
'headers' => [
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
],
'body' => [
'user_id' => $wordpressId //passed into this function
]
]
);
It then hits the route set up in my Wordpress API
$routes['/mysite-api/cleared-action'] = array(
array(array($this, 'automatedClearing'), WP_JSON_Server::ACCEPT_JSON
| WP_JSON_Server::CREATABLE
| WP_JSON_Server::EDITABLE)
);
However that is as far as it gets. It does not hit my automatedClearing endpoint which looks like this
public function automatedClearing() {
global $container;
\Groups_User_Group::create( array('user_id' => 2903, 'group_id' => 13));
$mySiteServices = $container['services'];
$this->$mySiteServices->sendClearedEmail(2903); //2903 = user_id
}
I've used hardcoded values for the users ID.
I keep getting a 200 response from my call, so it definitely hits the route, but does not execute the endpoint. The response is basically just an empty one.
My Wordpress access.log shows the route being hit, but my error.log doesn't show anything. By the way, this is a laravel Homestead (vagrant) box hitting a Wordpress vagrant box.
I'm wondering if this is because the WP-API requires a nonce? But I thought nonce was only needed within Wordpress, whereas this is an external app hitting Wordpress.
I'm pretty stuck on this. Any guidance is greatly appreciated
Try to test it using postman ... if this works via postman then you have the problem with laravel or guzzle

Need to pull fields from an issue in Sitecore

I'm working with SiteCore and I need to pull some data out of the software via either that API or the SQL database using a PHP script. The reason I say both are possible is because even if the database changes later on, that doesn't matter to me.
Anyway...
I'm trying to pull any data fields that I can get from a particular issue. This is my SOAP code so far, and it connects to the service and such, but the return isn't what I need...
try
{
$client = new SoapClient('http://localhost:8083/sitecore/shell/webservice/service.asmx?WSDL');
$credentials = array('Password' => 'mypassword','Username' => 'sitecore\myusername');
$Current_Issue = array(
'id' => '{043B69BA-3175-4184-812F-C925CE80324E}',
//'language' => 'en',
//'version' => '1',
//'allFields' => 'true',
'databaseName' => 'web',
'credentials' => $credentials
);
$response = $client->GetItemMasters($Current_Issue);
print_r($response);
}
catch(SoapFault $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
This is my output:
stdClass Object
(
[GetItemMastersResult] => stdClass Object
(
[any] => <sitecore xmlns=""/>
)
)
ANY help is appreciated. If anybody knows an example SQL query that I can use, that would be just as useful as an alternative method.
Thanks
If you are running Sitecore 6.5 / 6.6 you may want to take a look at the Sitecore Item Web API which was released yesterday (5/11/12).
http://sdn.sitecore.net/Products/Sitecore%20Item%20Web%20API.aspx
This allows you to perform RESTful operations against Sitecore items without the need for the old web service / SOAP interface. Using this module you can receive a JSON representation of a Sitecore item or collection of items and even post back changes. You may find it easier to work with :)
If you have to use the SOAP interface, are you sure that your items are published ? Try changing the databaseName -> 'master' and see if you get any results. Other things to check are the permissions of the user credentials you are using.

Resources