pycurl PostFields option usage - php

I'm trying to use pycurl to upload a file to Processmaker. app, self.usr, and doc are strings. file is a django file field object. I'm currently just passing the object. I'm fairly sure I'm just passing the incorrect object/type/thing to the ATTACH_FILE field.
The working php POSTFIELDS definition looks like this:
$params = array (
'ATTACH_FILE' => '#/home/test.txt',
'APPLICATION' => $resultCase->caseId,
'INDEX' => 1,
'USR_UID' => $oRandomUser->guid,
'DOC_UID' => '3154812864d55a6e017ff65089604572',
'APP_DOC_TYPE' => 'INPUT',
'TITLE' => "Initial document".date("Y-m-d H:i:s"),
'COMMENT' => "this document was uploaded by the system"
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
And the currently broken python:
c = pycurl.Curl()
data = [
('ATTACH_FILE', (pycurl.READFUNCTION, file.read)),
('APPLICATION', app),
('INDEX' , 1),
('USR_UID', self.usr),
('DOC_UID', doc),
('APP_DOC_TYPE', 'INPUT')
]
post = urllib.urlencode(data)
print post
url = "http://192.168.51.155/sysworkflow/en/green/services/upload"
c.setopt(pycurl.URL, url)
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, post)
c.perform()
c.close()
Any ideas?

I found a way to solve my own issue. Here is what I did, using poster located here: http://atlee.ca/software/poster/ I did the following:
from poster.streaminghttp import register_openers
import poster
register_openers()
url = "http://192.168.51.155/sysworkflow/en/green/services/upload"
params = {
'APPLICATION' : app,
'INDEX' : 1,
'USR_UID' : self.usr,
'DOC_UID' : doc,
'APP_DOC_TYPE' : 'INPUT',
'TITLE' : 'Test',
'ATTACH_FILE' : open(file.path, "rb")
}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(url, datagen, headers)
result = urllib2.urlopen(request)
print result.read()
Much easier to use than pycurl! The problem with my first attempt was that POSTFIELDS can't accept files (without some wrangling) and using an HTTPPOST option would work with the files but was difficult to get working with both file data and field data.

Related

Zendesk API using PHP: dynamic content updateMany gives invalid attribute error

I try to update a dynamic content field via Zendesk API using PHP API client (https://developer.zendesk.com/rest_api/docs/api-clients/php):
// auth and config goes here...
$itemId = 123;
$variantId = 456;
$data = [
'id' => $variantId,
'content' => 'my example content'
];
$zendesk->dynamicContent()->items($itemId)->variants()->updateMany(['variants' => $data]);
I get an UnknownAttributeError ("Invalid attribute: missing variants parameter"). What did I miss? I tried different ways to give the variant parameter but still the same error. Thanks!
must follow the Format as like Ticket -> updateMany()
Refer Ticket Update Many Test File
$itemId = 12345;
$variantIds = [456,787];
$this->assertEndpointCalled(function () use ($itemId, $variantIds) {
$this->client->dynamicContent()->items($itemId)->variants()->updateMany(
[
'ids' => $variantIds
'content' => 'My Example Content'
]
);
}, "dynamic_content/items/$itemId/variants/update_many.json");

Guzzle HTML tags in body

I need to send HTML components in the BODY of a POST throught Guzzle.
These are the HTML TAGS:
$strData = "<p style='background:url(/clear.png?org_id=1snn5n9w&session_id=123456789&m=1)'>< / p >
<img src='/clear.png?org_id=1snn5n9w&session_id=123456789&m=2' alt=''>";
My Guzzle code is:
$client = new GuzzleHttp\Client(['base_uri' => 'https://thirdURL.com/Test.htm', 'http_errors'=>true]);
$resH = $client->post('https://thirdURL . com/Test.htm',[
'form_params' =>['body' => $strData]]);
Is this the correct way to send this kind of objects via Guzzle?
Thanks for your help.
Regards.
If you are not trying to send data as a query parameter (think of a form submission) then there is no need to use "form_params".
If all you want is the body to contain the desired html string you should be able to do the following:
$resH = $client->post('https://thirdURL.com/Test.htm',[
'body' => $strData,
]);
More information can be obtained by reading through the Guzzle Documentation on Post Requests
The 'form_params' request option is essentially a short-cut way of performing:
$response = $client->post($uri, [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'body' => http_build_query($form_params_array),
])
So in essence, for your particular use case the body of your http request would contain the post query and the html content.
The answer to your question of 'will it work?', is simply (and albeit unhelpful) -- "I don't know". At the end of the day, it all depends on what the server will accept.

Simple HTML DOM Parser - Send post variables

I have the Simple HTML DOM Parser for PHP, and I am using the following markup:
$html = file_get_html('http://www.google.com');
However how do I send post variables (like a cURL) to that page and get the response? For example
$html = file_get_html('http://www.google.com', array("Item"=>"Value", "Item2"=>"Value2"));
The documentation doesn't mention it as far as I can see, but after taking a look in the source code I noticed the function you're using accepts a stream context as its third argument. You can create a post request with this PHP feature like this:
$request = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query(array(
'Item' => 'Value',
'Item2' => 'Value2'
)),
)
);
$context = stream_context_create($request);
$html = file_get_html('http://www.google.com', false, $context);
If you don't like contexts or would prefer a different method (like the cURL extension) you could also just fetch the page content using that, then feed it to the parser with str_get_html() or $parser->load(); the class itself does pretty much the same internally with the method you're using right now.

JSON stub string delivered via php

I would like to make a web service stub where I can test my client. I have written down
some JSON like this:
{
"response": {
"success": true,
"meta" : "tags",
"data": [
{
"first_name" : "John",
"last_name" : "Doe",
"age" : 30
},
{
"first_name" : "Jane",
"last_name" : "Doe",
"age" : 25
}
]
}
}
I have no PHP experience to talk about.
How can I make a
webserver.com/get_names.php?first_name=john&last_name=doe&age=30
script that returns the above JSON.
It should not do any evaluation on the parameters, that is just how it will end up being called when implemented against a server, I would just like it to return the JSON string correctly so my JSON parser can run through it as if it was the actual server response.
Hope someone can help me out, thank you in advance.
Save the JSON string as-is and call the file get_names.php. Don't forget to pick UTF-8 in your editor's save as dialogue. Nothing will be parsed as PHP if there isn't a single <?php string in the file.
You may also want to put this on top of the file:
<?php
header('Content-Type: application/json');
?>
This is usually referred to as an API, and can be developed on many levels.
First level would be standard streamline php, where you would have code that follows the general php coding.
$Action = isset($_GET["action"]) ? $_GET["action"] : false;
switch($Action)
{
case 'get_names':
//fetch data and display.
break;
}
The next method and the simplest would be to use an MVC Application Framework, I would recommend Code Igniter for this as tis bigginner friendly and the URI Structure is similar to an API Soap Server.
After copying your CI Files to your /api/ path, you would go threw the guide and configure your database,libraries,helpers etc, you would also use mod_rewrite to set up the URI Convention to get urls such as /api/get/games/API_KEY
your class would look like so:
class Get extends Controller
{
public function __construct()
{
parent::Controller();
}
public function games($Api = false,$limit = 10, $offset = 0)
{
if(!$Api)
{
show_error("API Key require to fetch games");
}
if(your_api_check($api) === true)
{
//Load the games
$games = $this->models->games->get($limit,$offset);
$this->output->send(json_encode($games));
}
}
}
Obviously more extensive checking with the validation of the params but you will get the gist of it.
The next level would be very complex for your self but if you wish to persue the idea then you may want to look into Simple Object Access Protocol but ill leave that for you to decide.
Links:
Codeigniter
RESTful with Codeigniter
Restful with CodeIgniter #2
Codeigniter XMLRPC Services
You could save this as get_names.php on your web server.
<?php
$my_associative_array = array(
'response' => array(
'success' => true,
'meta' => 'tags',
'data' => array(
array(
'first_name' => 'John',
'last-name' => 'Doe',
'age' => 30,
),
array(
'first_name' => 'Jane',
'last_name' => 'Doe',
'age' => 25
),
),
),
);
echo json_encode($my_associative_array);
Alternatively, you could just create a .txt file that looks precisely like your JSON.
You could also just point it to my server, where the above script is operational: http://dorkitude.com/example_4725873.php

How can I programatically add images to a drupal node?

I'm using Drupal 6.x and I'm writing a php class that will grab an RSS feed and insert it as nodes.
The problem I'm having is that the RSS feed comes with images, and I cannot figure out how to insert them properly.
This page has some information but it doesn't work.
I create and save the image to the server, and then I add it to the node object, but when the node object is saved it has no image object.
This creates the image object:
$image = array();
if($first['image'] != '' || $first['image'] != null){
$imgName = urlencode('a' . crypt($first['image'])) . ".jpg";
$fullName = dirname(__FILE__) . '/../../sites/default/files/rssImg/a' . $imgName;
$uri = 'sites/default/files/rssImg/' . $imgName;
save_image($first['image'], $fullName);
$imageNode = array(
"fid" => 'upload',
"uid" => 1,
"filename" => $imgName,
"filepath" => $uri,
"filemime" => "image/jpeg",
"status" => 1,
'filesize' => filesize($fullName),
'timestamp' => time(),
'view' => '<img class="imagefield imagefield-field_images" alt="' . $first['title'] . '" src="/' . $uri . '" /> ',
);
$image = $imageNode;
}
and this adds the image to the node:
$node->field_images[] = $image;
I save the node using
module_load_include('inc', 'node', 'node.pages');
// Finally, save the node
node_save(&$node);
but when I dump the node object, it no longer as the image. I've checked the database, and an image does show up in the table, but it has no fid. How can I do this?
Why not get the Feedapi, along with feedapi mapper, and map the image from the RSS field into an image CCK field you create for whatever kind of node you're using?
It's very easy, and you can even do it with a user interface.
Just enable feedapi, feedapi node (not sure on the exact name of that module), feedapi mapper, and create a feed.
Once you've created the feed, go to map (which you can do for the feed content type in general as well) on the feed node, and select which feed items will go to which node fields.
You'll want to delete your feed items at this point if they've already been created, and then refresh the feed. That should be all you need to do.
Do you need to create a separate module, or would an existing one work for you?
Are you using hook_nodeapi to add the image object to the node object when $op = 'prepare'?
If you read the comments on the site you posted, you'll find:
To attach a file in a "File" field
(i.e. the field type supplied by
FileField module) you have to add a
"description" item to the field array,
like this:
$node->field_file = array(
array(
'fid' => 'upload',
'title' => basename($file_temp),
'filename' => basename($file_temp),
'filepath' => $file_temp,
'filesize' => filesize($file_temp),
'list' => 1, // always list
'filemime' => mimedetect_mime($file_temp),
'description' => basename($file_temp),// <-- add this
), );
maybe that works. You could also try to begin the assignment that way:
$node->field_file = array(0 => array(...
If you are just grabbing content wich has images in, why not just in the body of your nodes change the path of the images to absolute rather than local, then you won't have to worry about CCK at all.
Two other things that you may need to do
"fid" => 'upload', change this to the fid of the file when you save it. If it isn't in the files table then that is something you will need to fix. I think you will need feild_file_save_file()
2.you may need an array "data" under your imageNode array with "title", "description" and "alt" as fields.
To build file information, if you have filefield module, you can also use field_file_load() or field_file_save_file(). See file filefield/field_file.inc for details.
Example:
$node->field_name[] = field_file_load('sites/default/files/filename.gif');

Categories