Is there a way to add a post in wordpress via googlescript? - wordpress

I have a form in googlescript where I can add a user to a sheet.
Is there a way to implement some lines in that code so the script adds a post on a wordpress page?
I read that it's possible via wp_insert_post , but I have no idea how that works in my case.
EDIT:
As Spencer suggested I tried to do it via WP REST API.
The following code seems to be working .............
function httpPostTemplate() {
// URL for target web API
var url = 'http://example.de/wp-json/wp/v2/posts';
// For POST method, API parameters will be sent in the
// HTTP message payload.
// Start with an object containing name / value tuples.
var apiParams = {
// Relevant parameters would go here
'param1' : 'value1',
'param2' : 'value2' // etc.
};
// All 'application/json' content goes as a JSON string.
var payload = JSON.stringify(apiParams);
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, params)
// Check return code embedded in response.
var rc = response.getResponseCode();
var responseText = response.getContentText();
if (rc !== 200) {
// Log HTTP Error
Logger.log("Response (%s) %s",
rc,
responseText );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
Logger.log( responseText );
}
}
But I get the error:
[16-09-28 21:24:29:475 CEST] Response (401.0)
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to
create new posts.","data":{"status":401}}
Means: I have to authenticate first.
I installed the plugin: WP REST API - OAuth 1.0a Server
I setup a new user and got a client key and client user.
But from here I have no clue what to do : /

It is possible. Wordpress has a REST API. I can be found at:
http://v2.wp-api.org/
You will use the UrlFetchApp Service to access this api. Documentation can be found at:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Read the docs and try to write some code. It you get stuck post the code that is confusing you here and I'll update this answer.

You should add you authentification in the header :
var headers = {
... ,
'Authorization' : 'Basic ' + Utilities.base64Encode('USERNAME:PASSWORD'),
};
And then add your header in your parameters :
var params = {
'method': 'POST',
'headers': headers,
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
}
And then use UrlfetchApp.fetch
var response = UrlFetchApp.fetch("https://.../wp-json/wp/v2/posts/", params)
Logger.log(response);

You need to pass the basic auth, like this:
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true,
"headers" : {
"Authorization" : "Basic " + Utilities.base64Encode(username + ":" + password)+"",
"cache-control": "no-cache"
}
};

thank you for giving me these important links.
<3
I installed WP REST API and the OAuth plugin.
In the documentation is written:
Once you have WP API and the OAuth server plugins activated on your
server, you’ll need to create a “client”. This is an identifier for
the application, and includes a “key” and “secret”, both needed to
link to your site.
I couldn't find out how to setup a client?
In my GoogleScriptCode according to the WP API I get the error:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}
Edit: I found it - it's under User/Application
I'll try to figure it out and get back to you later.

Related

Sending multipart/form-data using GraphQL API in .NetCore

I'm trying to upload the user avatar of .png/jpeg/.jpg file types from angular client to .netCore server application using GraphQL API.
I managed to send the image to be uploaded in a request of content type multipart/form-data from client-side.
But getting a 400 Error from the API server saying the content-type is not supported.
Error message is as follows:
message: "Invalid 'Content-Type' header: non-supported media type.
Must be of 'application/json', 'application/graphql' or 'application/x-www-form-urlencoded'. See: http://graphql.org/learn/serving-over-http/."
I'm trying to implement the mutation like this.
FieldAsync<StringGraphType>(
"testImageUpload",
arguments: new QueryArguments(
new QueryArgument<StringGraphType> { Name = "testArg" },
new QueryArgument<UploadGraphType> { Name = "file" }
),
resolve: async context =>
{
var testArg = context.GetArgument<string>("testArg");
var file = context.GetArgument<IFormFile>("file");
try
{
return await uploaderService().UploadImage(file);
}
catch (Exception e)
{
context.Errors.Add(new ExecutionError("Something happened!"));
return context.Errors;
}
});
I'm using GraphQL.net and GraphQL.Upload.AspNetCore for supporting multipart files.
Sample mutation will be like this:
mutation testImageUpload($testArg: String, $file: Upload) {
fileUpload{
testImageUpload(testArg: $testArg, file: $file)
}
}
Can anybody suggest to me how to make the .NetCore webAPI application accept multipart/form-data.
Any help will be appreciated. Thanks in advance.
I, too, ran into this issue. The answer lies within your Startup.cs file.
First, the reason for which the "Invalid 'Content-Type' header" appears even while using GraphQL.Upload is because (at the time of this answer) the GraphQL.net middleware only checks for the three different Content-Type headers and errors out if none of those match. See GitHub
As for the solution, you haven't shared any of your Startup.cs file so I'm not sure what yours looks like. I'll share the relevant pieces of mine.
You'll need to add the service and the middleware.
The service:
services.AddGraphQLUpload()
.AddGraphQL((options, provider) =>
{
...
});
If you're using a endpoints to map to a middleware, you'll need to add the UseGraphQLUpload middleware, then map your endpoint.
Example:
app.UseGraphQLUpload<YourSchema>("/api/graphql", new
GraphQLUploadOptions {
UserContextFactory = (ctx) => new GraphQlUserContext(ctx.User)
});
app.UseEndpoints(endpoints =>
{
// map HTTP middleware for YourSchema at path api/graphql
endpoints
.MapGraphQL<YourSchema, GraphQLMiddleware<YourSchema>>("api/graphql")
.RequireAuthorization();
...
// Additional endpoints
...
}
Everything else looks fine to me.

Why Twilio gives error 400 when image-chart is sended

I'm trying to send images to a whatsapp user via Twilio, but I'm always getting 400 error
(400) Bad Request. -> {"code": 21620, "message": "Media urls: https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupaci%C3%B3n%20en%20almac%C3%A9n&chdl=Contratado%7COcupado&chli=100.37%25&chl=10238%7C10200&chdlp=b&chof=.png are invalid. Please use only valid http and https urls", "more_info": "https://www.twilio.com/docs/errors/21620", "status": 400}
The image works fine in browser or when is send directly to the user directly in whatsapp
I'm encoding the image like this (js):
img_url = encodeURI(img_url);
Any ideas or workaround?
thanks
It seems not every parameter was encoded, example: chd=a:10238,10200 should be chd=a%3A10238%2C10200.
encodeURI won't produce URL safe, you will need to rely on encodeURIComponent but it will encode the whole url ('/chart?' included) so it's not an option either.
If you are doing this server-side from NodeJS:
// node v10+
const url = require('url');
const querystring = require('querystring');
function encode_uri(chart_url) {
const parsed_url = url.parse(chart_url);
// parse the querytring and then encode every parameter values
parsed_url.query = querystring.stringify(querystring.parse(parsed_url.query));
// generate the full url
return url.format({
...parsed_url,
href:undefined,
path:undefined,
search:'?' + parsed_url.query,
});
}
let chart_url = 'https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdlp=b&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupación en almacén&chli=100.37%&chl=10238|10200&chdl=Contratado|Ocupado&chof=.png';
console.log(encode_uri(chart_url));
// Fully encoded URL
// https://image-charts.com/chart?cht=pd&chd=a%3A10238%2C10200&chs=400x300&chdlp=b&chdls=9e9e9e%2C10&chco=FFC00C%2C03A9F4&chtt=Ocupaci%C3%B3n%20en%20almac%C3%A9n&chli=100.37%25&chl=10238%7C10200&chdl=Contratado%7COcupado&chof=.png
If you are doing this on the browser side then use:
function encode_uri(chart_url) {
// use https://developer.mozilla.org/en-US/docs/Web/API/URL
// not supported in IE10
const parsed_url = new URL(chart_url);
// encode every parameter values
[...parsed_url.searchParams.keys()].forEach(key => parsed_url.searchParams.set(key, encodeURIComponent(parsed_url.searchParams.get(key))));
// generate back the full url
return parsed_url.toString();
}
let chart_url = 'https://image-charts.com/chart?cht=pd&chd=a:10238,10200&chs=400x300&chdlp=b&chdls=9e9e9e,10&chco=FFC00C,03A9F4&chtt=Ocupación en almacén&chli=100.37%&chl=10238|10200&chdl=Contratado|Ocupado&chof=.png';
console.log(encode_uri(chart_url));
// https://image-charts.com/chart?cht=pd&chd=a%253A10238%252C10200&chs=400x300&chdlp=b&chdls=9e9e9e%252C10&chco=FFC00C%252C03A9F4&chtt=Ocupaci%25C3%25B3n%2520en%2520almac%25C3%25A9n&chli=100.37%2525&chl=10238%257C10200&chdl=Contratado%257COcupado&chof=.png

How to access Response cookies in angular2?

I'm trying to access this cookies (the response ones):
When I open the request in the chrome debug tools in the network section I can clearly see that the cookies are present, but how can I access those values from my code? I've never worked with cookies before and I don't know what to do to "extract" them... I'm working on a Ionic2 project using Http.
I've read that the allowCredentials: true header has to be sent but that didn't work...
Here's the request/response details:
Here's the service:
public callLogin(service_guid: string, pos_guid: string, login_data: Object) {
return this.http.post(
this.url + service_guid + "/" + pos_guid + "/ack",
login_data,
{withCredentials: true}
)
.map(response => response.headers);
}
And the caller:
this.__posService.callLogin(login_data.service_guid, login_data.pos_guid, {"password": data.password})
.subscribe(
res => {
console.log("Success:");
console.log(res.get("apsession"); // this returns undefined
},
err => {
console.log("Error:");
}
);
When I try to access the cookie from the header it returns undefined. What am I doing wrong here?
The name of the response header you are trying to get is actually Set-Cookie not apsession. So if you did something like res.get("set-cookie") it would return the first header that matched that name. Since you have more than 1, you could do:
let headers: Headers = res.headers;
headers.getAll('set-cookie');
which returns a list of all headers with that name. You could find apsession in there probably.
See:
https://angular.io/docs/ts/latest/api/http/index/Headers-class.html
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
https://developer.mozilla.org/en-US/docs/Web/API/Headers

How to fetch a wordpress admin page using google apps script?

I need to fetch a page inside my Wordpress blog admin area. The following script:
function fetchAdminPage() {
var url = "http://www.mydomain.invalid/wp/wp-admin/wp-login.php";
var options = {
"method": "post",
"payload": {
"log": "admin",
"pwd": "password",
"wp-submit": "Login",
"redirect_to":"http://www.mydomain.invalid/wp/wp-admin/edit-comments.php",
"testcookie": 1
}
};
var response = UrlFetchApp.fetch(url, options);
...
}
is executed without errors. Anyway, response.getContentText() returns the login page, and I am not able to access the page http://www.mydomain.invalid/wp/wp-admin/edit-comments.php which is the one I want to fetch.
Any idea on how to do this?
There might be an issue with Google Apps Scripts and post-ing to a URL that gives you back a redirection header.
It seems like it might not be possible to follow the redirect with a post - here's a discussion on the issue -
https://issuetracker.google.com/issues/36754794
Would it be possible, if you modify your code to not follow redirects, capture the cookies and then do a second request to your page? I haven't actually used GAS, but here's my best guess from reading the documentation:
function fetchAdminPage() {
var url = "http://www.mydomain.invalid/wp/wp-admin/wp-login.php";
var options = {
"method": "post",
"payload": {
"log": "admin",
"pwd": "password",
"wp-submit": "Login",
"testcookie": 1
},
"followRedirects": false
};
var response = UrlFetchApp.fetch(url, options);
if ( response.getResponseCode() == 200 ) {
// Incorrect user/pass combo
} else if ( response.getResponseCode() == 302 ) {
// Logged-in
var headers = response.getAllHeaders();
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
// Make sure that we are working with an array of cookies
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
// We only need the cookie's value - it might have path, expiry time, etc here
cookies[i] = cookies[i].split( ';' )[0];
};
url = "http://www.mydomain.invalid/wp/wp-admin/edit-comments.php";
options = {
"method": "get",
// Set the cookies so that we appear logged-in
"headers": {
"Cookie": cookies.join(';')
}
};
response = UrlFetchApp.fetch(url, options);
};
};
...
}
You would obviously need to add some debugging and error handling, but it should get you through.
What happens here is that we first post to the log-in form. Assuming that everything goes correctly, that should give us back a response code of 302(Found). If that's the case, we will then process the headers and look specifically for the "Set-Cookie" header. If it's set, we'll get rid of the un-needed stuff and store the cookies values.
Finally we make a new get request to the desired page on the admin( in this case /wp/wp-admin/edit-comments.php ), but this time we attach the "Cookie" header which contains all of the cookies acquired in the previous step.
If everything works as expected, you should get your admin page :)
I would advise on storing the cookies information(in case you're going to make multiple requests to your page) in order to save time, resources and requests.
Again - I haven't actually tested the code, but in theory it should work. Please test it and come back to me with any findings you make.

Alfresco - submitting dynamic forms to upload.post with javascript

I'm encountering issues with a dashlet that I'm trying to develop for Alfresco. It's a simple drag and drop file upload dashlet using HTML 5's drag and drop and file APIs. For the drop event listener, I call the following function which is seemingly the cause of all the problems:
function handleFileSelect(evt) {
var files = evt.target.files || evt.dataTransfer.files,
tmpForm, tmpDest, tmpMeta, tmpType, tmpName, tmpData;
dropZone.className = "can-drop";
evt.stopPropagation();
evt.preventDefault();
for (var i=0,f;f=files[i];i++) {
tmpForm = document.createElement('form');
tmpDest = document.createElement('input');
tmpDest.setAttribute('type', 'text');
tmpDest.setAttribute('name', 'destination');
tmpDest.setAttribute('value', destination);
tmpForm.appendChild(tmpDest);
tmpMeta = document.createElement('input');
tmpMeta.setAttribute('type', 'text');
tmpMeta.setAttribute('name', 'mandatoryMetadata');
tmpMeta.setAttribute('value', window.metadataButton.value);
tmpForm.appendChild(tmpMeta);
tmpType = document.createElement('input');
tmpType.setAttribute('type', 'text');
tmpType.setAttribute('name', 'contenttype');
tmpType.setAttribute('value', "my:document");
tmpForm.appendChild(tmpType);
tmpName = document.createElement('input');
tmpName.setAttribute('type', 'text');
tmpName.setAttribute('name', 'filename');
tmpName.setAttribute('value', f.name);
tmpForm.appendChild(tmpName);
tmpData = document.createElement('input');
tmpData.setAttribute('type', 'file');
tmpData.setAttribute('name', 'filedata');
tmpData.setAttribute('value', f);
tmpForm.appendChild(tmpData);
Alfresco.util.Ajax.request({
url: Alfresco.constants.PROXY_URI_RELATIVE + "api/upload",
method: 'POST',
dataForm: tmpForm,
successCallback: {
fn: function(response) {
console.log("SUCCESS!!");
console.dir(response);
},
scope: this
},
failureCallback: {
fn: function(response) {
console.log("FAILED!!");
console.dir(response);
},
scope: this
}
});
}
}
The server responds with a 500, and if I turn on debug level logging for web scripts, upload.post returns with:
DEBUG [repo.jscript.ScriptLogger] ReferenceError: "formdata" is not defined.
Which, to me at least, indicates that the form above isn't getting submitted properly (if at all). When digging through it all with Chrome dev tools, I notice that that request payload looks drastically different from something such as a REST client. The above code results in the request using Content-Type: application/x-www-form-urlencoded whereas using a REST client, or Alfresco Share's standard uploader(s) are using Content-Type: multipart/form-data. If I need to submit the form using multipart/form-data, what is the easiest way to write out the request body (with the boundaries, Content-Disposition's, etc...) to include the file being uploaded?
I ditched the idea of creating a form HTML Element through javascript, and assume that if a browser supports the File API, and the Drag and Drop API, that they will likely also support the XMLHttpRequest2 API. As per HTML5 File Upload to Java Servlet, The above code now reads:
function handleFileSelect(evt) {
var files = evt.target.files || evt.dataTransfer.files,
xhr = new XMLHttpRequest();
dropZone.className = "can-drop";
evt.stopPropagation();
evt.preventDefault();
for (var i=0,f;f=files[i];i++) {
formData = new FormData();
formData.append('destination', destination);
formData.append('mandatoryMetadata', window.metadataButton.value);
formData.append('contenttype', "my:document");
formData.append('filename', f.name);
formData.append('filedata', f);
formData.append('overwrite', false);
xhr.open("POST", Alfresco.constants.PROXY_URI_RELATIVE + "api/upload");
xhr.send(formData);
}
}
with the necessary event listeners to be added later. It would seem that the Alfresco AJAX methods that come stock and standard heavily modify the underlying requests being made, making it very difficult for one to simply send a FormData() object.

Resources