Below is my code to add headers and footers to generate pdf, I don't know here I'm doing it wrong.Please help!
$html = $this->renderView('CoreBundle:PdfGenerator:generate.html.twig', array(
'userId' => $userId,
));
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'));
$snappy->setOption('footer-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/footer.html'));
//echo $request->getHost().$this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'); die();
echo $html; die();
return new Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
http://www.michaelperrin.fr/2016/02/17/generating-pdf-files-with-symfony/
Follow this, I got my stuff working
$header = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:header.html.twig');
$body = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:body.html.twig', $data);
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $header);
return new Response(
$snappy->getOutputFromHtml($body), 200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename=' . $file2 . '.pdf',
]
);
}
Related
I am having big issues doing a POST request from wordpress backend.
This is the request I try to make. The AppsSCript is a doPost() endpoint echo-ing the request. It gives me a 400 error.
$body = array(
'firstName' => 'WhyWontYouWork'
);
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
//'httpversion' => '1.0',
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => $body
);
$request = wp_remote_post ($url, $args);
$response = wp_remote_retrieve_body( $request );
I found out with insomnia, that having a content-length header in the POST request is making Apps Script go crazy. If I remove it, all works.
Hope this helps,
$url = 'https://example.com/api/endpoint';
$args = array(
'method' => 'POST',
'timeout' => 30,
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => json_encode( array( 'data' => 'value' ) ),
);
// Remove the Content-Length header
unset( $args['headers']['Content-Length'] );
// Or Change it
$args['headers']['Content-Length'] = 20166 // in decimal bytes
// Make the remote post request
$response = wp_remote_post( $url, $args );
// Check for errors
if ( is_wp_error( $response ) ) {
// Handle error
} else {
// Handle success
}
I am trying to update my repeater field from front end-with files. In case with one field file - it works. But when I'm trying to fill repeater with files it doesn't work.
// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
$('.js-new-msg-send').click(function (e) {
e.preventDefault();
var form = document.forms.namedItem("new_theme");
var formData = new FormData(form);
formData.append('user_id', '<?php echo $userID; ?>');
formData.append('action', 'msg_to_acf');
var xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl, true);
xhr.send(formData);
})
I found function to handle files uploading to acf field and modified it to handle multiple files from $_FILES variable:
// FOR MULTIPLE FILES
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$file_list = array();
foreach ($_FILES[$f]['name'] as $key => $value) {
$temp_file = array(
'name' => $_FILES[$f]['name'][$key],
'type' => $_FILES[$f]['type'][$key],
'tmp_name' => $_FILES[$f]['tmp_name'][$key],
'error' => $_FILES[$f]['error'][$key],
'size' => $_FILES[$f]['size'][$key]
);
wp_update_attachment_metadata( $pid, $temp_file );
$file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($temp_file['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
$final_temp_arr = array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
array_push($file_list, $final_temp_arr);
}
}
return $file_list;
}
In final, I using this function to get an array of information with attach-id variable that I inserting to repeater.
$att = my_update_attachment( 'msg-file-list' , $post_id );
$files_final_list = array();
foreach ($att as $key => $val) {
array_push($files_final_list, $val['attach_id']);
}
$value_arr = array(
array(
"msg-author" => $user_name,
"msg-date" => $date,
"msg-read-check" => true,
"msg-cont" => $msg_cont,
'msg-file-list' => $files_final_list
)
);
update_field( 'test_file_list' , $files_final_list , $post_id );
I guess that mistake is in last part , where I trying to upload files to repeater. Can someone show me what I'am doing wrong? Thanks for helping.
I use the api version 2.0 and want to create an image share.
LinkedIn describes your image binary file upload process here:
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context#create-a-text-share
If you follow the instructions you will get a 400 HTTP error.
I add the Content-Type in the header and get a 201 HTTP status with the X-RestLi-Id in the header. So far so good!
If I want to show my created post on LinkedIn (https://www.linkedin.com/in/me/detail/recent-activity/) I can't find the post with image.
How to fix it? Anybody got an idea?
PHP code:
$imageRequestData = array(
"registerUploadRequest" => array(
"recipes" => array(
"urn:li:digitalmediaRecipe:feedshare-image"
),
"owner" => $urn, // Person URN === urn:li:person:XXXX
"serviceRelationships" => array(
array(
"relationshipType" => "OWNER",
"identifier" => "urn:li:userGeneratedContent"
)
)
)
);
$image_request = $this->post('v2/assets?action=registerUpload', $imageRequestData);
$headers = array();
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: ' . mime_content_type($image_path); //ex. image/png
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['message']['value']['uploadMechanism']
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => array("upload-file" => new CURLFile($image_path))
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$content = array(
'author' => $urn, // Person URN === urn:li:person:XXX
'lifecycleState' => 'PUBLISHED',
'specificContent' => array(
"com.linkedin.ugc.ShareContent" => array(
'shareCommentary' => array(
"text" => $comment,
),
'shareMediaCategory' => 'IMAGE',
// NONE - The share does not contain any media, only text.
// ARTICLE - The share contains a URL.
// IMAGE - The Share contains an image.
'media' => array(
"status" => "READY",
"media" => $image_request['message']['value']['asset']
)
)
),
"visibility" => array(
"com.linkedin.ugc.MemberNetworkVisibility" => "PUBLIC"
)
);
$postfields = json_encode($content);
$headers = array();
$headers[] = 'x-li-format: json';
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' . strlen($postfields);
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://api.linkedin.com/v2/ugcPosts',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => $postfields
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
You need to change your request to PUT and keep default for SSL VerifyPeer:
$headers = array();
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: multipart/form-data';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'PUT', //need to set custom request to PUT instead of post
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['message']['value']['uploadMechanism']
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
// CURLOPT_SSL_VERIFYPEER => false, //keep default options
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => array("upload-file" => new CURLFile($image_path))
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Or use GuzzleHttp\Client to simplify the upload:
$client =new \GuzzleHttp\Client();
$client->request('PUT',
$image_request['message']['value']['uploadMechanism'] // ↵
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
[
'headers' => [
'Authorization' => 'Bearer ' . $this->accessToken
],
'body' => fopen($image_path, 'r'),
]
Im trying to post some data to custom api endpoint that i created,
This is what my wordpress custom endpoint code.
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
And for testing I am trying to return the request like this
function create_city_from_data($req) {
return ['req' => $req];
}
but always i receive empty object as response, whatever i send in payload i didn't receive anything.
My payload is something like this
{ name: 'Hello', population: 565656 }
This is what is received from the request
{"req":{}}
By using below code you can view your payload.
add_action('rest_api_init', function () {
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
});
function create_city_from_data($req) {
$response['name'] = $req['name'];
$response['population'] = $req['population'];
$res = new WP_REST_Response($response);
$res->set_status(200);
return ['req' => $res];
}
I have used postman to view the POST parameter
By using this function you can see all post of your custom post type in API...
Get All Post in your API Viewer.
Writer URL on your API viewer (e.g. I used Postman json api view, google chrome adon)
Domain-name/wp-json/showFavorites/v2?post_type=hotel
Here 'hotel' is the custom posttype.
Add this function in your functions.php
add_action( 'rest_api_init', 'wp_api_show_favorites_endpoints' );
function wp_api_show_favorites_endpoints() {
register_rest_route( 'showFavorites', '/v2', array(
'methods' => 'GET',
'callback' => 'showFavorites_callback',
));
}
function showFavorites_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
$parameters = $request_data->get_params();
$post_type = $parameters['post_type'];
if($post_type!=''){
$re_query = "SELECT * FROM $table where post_type='$post_type'";
$pre_results = $wpdb->get_results($re_query,ARRAY_A);
return $pre_results;
}else{
$data['status']=' false ';
return $data;
}
}
And using this you can post your content from API
// POST All Posts using API
add_action( 'rest_api_init', 'wp_api_add_posts_endpoints' );
function wp_api_add_posts_endpoints() {
register_rest_route( 'addPost', '/v2', array(
'methods' => 'POST',
'callback' => 'addPosts_callback',
));
}
function addPosts_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
// Fetching values from API
$parameters = $request_data->get_params();
$user_id = $parameters['user_id'];
$post_type = $parameters['post_type'];
$post_title = $parameters['post_title'];
$the_content = $parameters['the_content'];
$cats = $parameters['cats'];
$the_excerpt = $parameters['the_excerpt'];
$feature_img = $parameters['featured_image'];
// custom meta values
$contact_no = $parameters['contact_no'];
$email = $parameters['email'];
$hotel_url = $parameters['hotel_url'];
if($post_type!='' && $post_title!=''){
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title),
'post_content' => $the_content,
'post_author' => '',
'post_excerpt' => $the_excerpt,
'post_status' => 'publish',
'post_type' => $post_type,
);
$new_post_id = wp_insert_post( $my_post );
function wp_api_encode_acf($data,$post,$context){
$customMeta = (array) get_fields($post['ID']);
$data['meta'] = array_merge($data['meta'], $customMeta );
return $data;
}
if( function_exists('get_fields') ){
add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}
// Set post categories
$catss = explode(',', $cats);
if (!empty($catss)) {
if ($post_type == 'post') {
wp_set_object_terms( $new_post_id, $catss, 'category', false );
}
else{
wp_set_object_terms( $new_post_id, $catss, 'Categories', false ); // Executes if posttype is other
}
}
// Set Custom Metabox
if ($post_type != 'post') {
update_post_meta($new_post_id, 'contact-no', $contact_no);
update_post_meta($new_post_id, 'email', $email);
update_post_meta($new_post_id, 'hotel-url', $hotel_url);
}
// Set featured Image
$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($feature_img);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
if ($new_post_id) {
$data['status']='Post added Successfully.';
}
else{
$data['status']='post failed..';
}
}else{
$data['status']=' Please provide correct post details.';
}
return ($data);
}
The object parameter passed into the callback function is a WP_REST_REQUST object and has a get_body() method on it which returns the payload/post body of the HTTP Post Request.
function create_city_from_data(WP_REST_Request $req) {
$body = $req->get_body()
return ['req' => $body];
}
I learnt about this today whilst reading this article
You can also declare the type of object in the method signature in case you need to search the documentation for it (like i have above).
CURL request :
$url = $your_url; // your url should like: http://host.com/wp-json/v1/'.$key
$post_string = json_encode($post_data);// make json string of post data
$ch = curl_init(); //curl initialisation
curl_setopt($ch, CURLOPT_URL, $url); // add url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get return value
curl_setopt($ch, CURLOPT_POST, true); // false for GET request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // add post data
curl_setopt($crl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post_string))
);// add header
$output = curl_exec($ch);
curl_close($ch); // close curl
$error = curl_error($ch); // get error
if(!$error){
return json_decode($output);
}else{
return $error;
}
For Handle Request in PLUGIN context :
public static function handle_requests(WP_REST_Request $request){
$return_data = [];
//get GET params
$key = $request['key'];
//get POST values
$post_data = json_decode($request->get_body());
//$return_data = $post_data;
if ( empty( $return_data ) ) {
return new WP_Error( 'error', 'Invalid Request', array( 'status' => 404 ) );
}else{
return $return_data;
}
}
Your WP REST API ACTION :
add_action( 'rest_api_init', function () {
register_rest_route( '/v1', '/(?P<key>[\w]+)', array(
'methods' => ['GET', 'POST'],
'callback' => 'YOUR_CLASS::handle_requests',
'permission_callback' => '__return_true'
) );
} );
//permission_callback need to add for wordpress newer versions.
The following code is very straightforward. However, when I execute it, I always get {"error":"Unsupported Media Type"} from Watson-Conversation service. Please help to show me where the issue comes from.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_POST => true,
CURLOPT_URL => "https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/70b056e6-14a0-424f-9631-696272ce666e/message?version=2016-09-20",
CURLOPT_USERPWD => "{MYUSERNAME}:{MYPASSWORD}",
CURLOPT_POSTFIELDS => array('message' => '{ "input": { "text": "Hola" }, "alternate_intents": false }'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
Thank you very much.
I have sorted it out already by adding following option into the call:
CURLOPT_HTTPHEADER => array('Content-Type: application/json')