How can I get rid of the /* I see at the end of every PDF I generate? - mpdf

I'm using mPDF to generate PDFs of webpage content. I've noticed that at the end of every PDF I generate I am seeing a /*. Pretty Weird. I am using mPDF with Wordpress. I suspect that maybe there is something with my template possibly that is causing the issue.
I tried the example first pdf code and that did not produce the /*.
My settings for mPDF look like this:
$url = urldecode($_REQUEST['url']);
$title = urldecode($_REQUEST['title']);
// For $_POST i.e. forms with fields
if (count($_POST) > 0) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
foreach($_POST as $name => $post) {
$formvars = array($name => $post . " \n");
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);
$html = curl_exec($ch);
curl_close($ch);
} elseif (ini_get('allow_url_fopen')) {
$html = file_get_contents($url);
} else {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 1 );
$html = curl_exec($ch);
curl_close($ch);
}
/* for debug */
var_dump($html); die;
$mpdf = new \Mpdf\Mpdf([
'format' => 'Letter',
'margin_left' => 0,
'margin_right' => 0,
'margin_top' => 6,
'margin_bottom' => 6,
'margin_header' => 5,
'margin_footer' => 5
]);
$mpdf->useSubstitutions = false; // optional - just as an example
$mpdf->simpleTables = true;
// $mpdf->SetHeader($url . "\n\n"); // optional - just as an example
$mpdf->CSSselectMedia='mpdf'; // assuming you used this in the document header
$mpdf->SetAuthor("author");
$mpdf->SetDisplayMode('fullpage');
$mpdf->setBasePath($url);
$mpdf->WriteHTML($html);
$mpdf->Output($title . ".pdf", 'D');
I am submitting a page URL from a form to my createPDF.php page and using curl to get the content of the page. Is there something special I need to do here to clean the content?

Related

Replace links on post save/update in Wordpress

I would like use short urls in wordpress post content (not the post permalink). So when I setup a new link in my post content, I would like if this url will be shortened with a service. I have an url shorten tool with yourls api, it works fine. My problem is, I unable change all long url in post to the new shortened url.
My function looks like this:
add_action( 'save_post', 'save_book_meta', 10, 3 );
function save_book_meta( $post_id, $post, $update ) {
global $wpdb;
preg_match_all('|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i', $post->post_content, $match);
$new_content = $post->post_content;
foreach($match[1] as $link){
$yapikey = '********';
$api_url = 'https://yourdomain.com/yourls-api.php';
$longUrl = $link;
// Init the CURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HEADER, 0); // No header in the result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
curl_setopt($ch, CURLOPT_POST, 1); // This is a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, array( // Data to POST
'url' => $longUrl,
'format' => 'json',
'action' => 'shorturl',
'signature' => $yapikey
));
// Fetch and return content
$data = curl_exec($ch);
curl_close($ch);
// Do something with the result. Here, we echo the long URL
$data = json_decode( $data );
if($data->shorturl) {
str_replace($link, $data->shorturl, $new_content);
}
}
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'save_book_meta' );
$post_new = array(
'ID' => $post_id,
'post_content' => $new_content
);
$post_id = wp_update_post( $post_new, true );
add_action( 'save_post', 'save_book_meta' );
}
How can I replace all long url with the new shortened urls and save the updated content?
I think it would be easiest to use the filter
add_filter( 'wp_insert_post_data' , 'save_book_meta' , '99', 2 );
function save_book_meta( $data , $postarr ) {
// find your urls and do the replacements on $data['post_content'] here
return $data;
}
EDIT: It looks like another viable filter option to use is https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre which may work even better as there has been no sanitation performed on the content yet.

Integrating SMS api with woocommerce , Not sending messages

I'm integrating SMS API with WooCommerce to send automatic order updates to customers mobiles whenever the make any purchase on site.
below is my code for the same
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($billing_phone)
{
$username = "my username";
$hash = "d761fbd7bd31c5eeec2a5b2556d6b9d3b1a1ae51";
//Multiple mobiles numbers separated by comma
$mobileNumber = "$billing_phone";
$senderId = "ORNGMT";
$message = urlencode("Dear Customer");
$postData = array(
'hash' => $hash,
'mobiles' => $$billing_phone,
'message' => $message,
'sender' => $senderId,
);
$url='http://api.textlocal.in/send/?';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo $output;
}
is it correct ?
I've added this code to functions.php page
my sms gateway provider has sent me below example code to send sms with PHP
<?php
// Authorisation details.
$username = "your login id";
$hash = "your hash key";
// Configuration variables. Consult http://api.textlocal.in/docs for more info.
$test = "0";
// Data for text message. This is the text message data.
$sender = "API Test"; // This is who the message appears to be from.
$numbers = "44777000000"; // A single number or a comma-seperated list of numbers
$message = "This is a test message from the PHP API script.";
// 612 chars or less
// A single number or a comma-seperated list of numbers
$message = urlencode($message);
$data = "username=".$username."&hash=".$hash."&message=".$message."&sender=".$sender."&numbers=".$numbers."&test=".$test;
$ch = curl_init('http://api.textlocal.in/send/?');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); // This is the result from the API
curl_close($ch);
?>
Integrating message API for each event will be difficult and you need to customize the at the code level.
You can use a popular SMSplugin for wordpress woocommerce
https://wordpress.org/plugins/woocommerce-apg-sms-notifications/
Just you need to configure this plugin from woocommerce Admin login and it will send sms notifications automatically. We are using it with Spring Edge sms gateway.. Working Good.
Tested and working
Custom api Integration with Woocommerce wordpress
Ufone pakistan sms integration with woocommerce wordpress
if you are looking for integration with ufone pakistan sms api bsms ufone pakistan service provider with woocommerce wordpress then use the following code in your functions file
sms api integration ufone bsms with wordpress woocommerce thanks to the author on this page Integrating custom SMS API with woocommerce
//add this line for calling your function on creation of order in woocommerce
add_action('woocommerce_order_status_processing', 'custom_func', 10, 3);
function custom_func ($order_id) {
$order_details = new WC_Order($order_id);
//fetch all required fields
$billing_phone = $order_details->get_billing_phone();
$billing_name = $order_details->get_billing_first_name();
$billing_last_name = $order_details->get_billing_last_name();
$total_bill = $order_details->get_total();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call Total Bill = $total_bill");
// Now put HTTP ufone BSMS API URL
$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=msisdn&message=$textmessage&shortcode=SHORTCODE&lang=English&mobilenum=$billing_phone&password=password&messagetype=Nontransactional";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
$billingphone in your function is ID. Try this below code. It works
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
//Now will fetch customer/buyer id here
$customer_id = $order->user_id;
//now finally we fetch phone number
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
// Now put your HTTP SMS API URL . I PUT WHICH WE ARE USING
$jsonurl = "http://tsms.thirdeyegoa.com/api/sendmsg.php?user=USERNAME&pass=PASSWORD&sender=MYSENDERID&phone=".$billing_phone."&priority=ndnd&stype=normal&text=MY MESSAGE TO CUSTOMER.";
// NOW WILL CALL FUNCTION CURL
$json = curl($jsonurl);
return $order_id;
}
Same you can do for Order Completed too with respective hook.
i write this piece of code and it is working.
add_action('woocommerce_order_status_completed','payment_complete');
function payment_complete($order_id)
{
$order=new Wc_order($order_id);
$order_meta = get_post_meta($order_id);
$shipping_first_name = $order_meta['_shipping_first_name'][0];
$phone=$order_meta['_billing_phone'][0];
$first_name=$order->billing_first_name;
$last_name=$order->billing_last_name;
$name=$first_name."".$last_name;
$mobile=$order->billing_mobile;
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
$time=$item['timings'];
$slot=$item['time_slot'];
$qty= $item['qty'];
$date=$item['tour_date'];
}
$text="your message here";
$data="user=username&pass=password&sender=sendername&phone=".$phone."&priority=ndnd&stype=normal&text=".$text;
$ch = curl_init('http://bhashsms.com/api/sendmsg.php?');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
I am from Textlocal. Let me help you out with the code.
Firstly the error that you are getting - 'Unexpected Token' is generally due to an invalid JSON response. If you are unaware of the source of the issue, I would suggest you to look in the Javascript console in the Dev section (triggering the error). For reference, you can check Mike's blog out here.
In the code you have shared, Textlocal API is not receiving the parameters that are mandatory for a successful POST call. You can rephrase your function like this:
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
$order = new WC_Order( $order_id );
$customer_id = $order->user_id;
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
$data="username=USERNAME&hash=hash&sender=ORNGMT&numbers=".$billing_phone."&message=MY MESSAGE TO CUSTOMER.";
$jsonurl = curl_init('https://api.textlocal.in/send?');
$json = curl($jsonurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($json);
echo $result;
curl_close($json);
return $order_id;
}
If you need any further assistance, please reach out to our support team (support#textlocal.in)

LinkedIn API - how to post company update using Oauth2 & PHP

I am trying to modify LinkedIn's sample authorization code to post a company update.
Have the original code example working, meaning I can login to my user profile. So the next step would be posting the update.
Have found some info on the Internet and here at stackoverflow.com, and the result is the function PostUpdate() found in the code below. The rest of the code pretty much comes straight from the Linkedin code sample.
So this code seems to run, I get no errors reported, but I also get no update on the company page. There is one issue I notice, after successfully logging-in, the code prints "Hello $user->firstName $user->lastName." but my name does NOT show up on the screen. The "Hello" does, so perhaps this indicates where a problem might be found.
<?php
//config.php contains the API KEY, SECRET, AND COMPANY ID
//define('API_KEY', 'your key');
//define('API_SECRET', 'your secret');
//define('COMPANY_ID', 'your company id');
require_once('config.php');
// You must pre-register your redirect_uri at https://www.linkedin.com/secure/developer
define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile r_emailaddress w_share rw_company_admin');
// You'll probably use a database
session_name('linkedin');
session_start();
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');
print "Hello $user->firstName $user->lastName.";
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>Testing a full company share!!!!!</comment>
<content>
<submitted­-url>https://www.example.com/test-2.html</submitted-­url>
<title>Test Share with Content</title>
<description>content description</description>
<submitted-image-­url>https://www.example.com/img/internet.jpg</submitted­-image-­url>
</content>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print $_SESSION['access_token'];
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $this->access_token));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo $http_status;
}
function getAuthorizationCode() {
$params = array(
'response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
function getAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
function fetch($method, $resource, $body = '') {
print $_SESSION['access_token'];
$opts = array(
'http'=>array(
'method' => $method,
'header' => "Authorization: Bearer " . $_SESSION['access_token'] . "\r\n" . "x-li-format: json\r\n"
)
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource;
// Append query parameters (if there are any)
if (count($params)) { $url .= '?' . http_build_query($params); }
// Tell streams to make a (GET, POST, PUT, or DELETE) request
// And use OAuth 2 access token as Authorization
$context = stream_context_create($opts);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
Finally posted a company update (share) successfully.
One issue that made the LinkedIn code sample (https://developer-programs.linkedin.com/documents/code-samples) non-functional was that file_get_contents() was not working, and this was because allow_url_fopen was not enabled in PHP.ini. I believe allow_url_fopen is not enabled by default, as it is a security issue. I found a work-around online use cUrl. See the code below.
//First, in getAccessToken() replace:
$response = file_get_contents($url, false, $context)
with
$response = curl_get_contents($url);
And here is the code added to the LinkedIn code sample, after the
'print "Hello $user->firstName $user->lastName.";'
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>There are a lot of great career opportunities here!</comment>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print 'here in PostUpdate <br />';
print '$message = ' . $message .' <br />';
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $_SESSION['access_token']));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo '$http_status = '. $http_status;
}
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Maybe it aint pretty, but after a couple of days struggling with it, I feel surprisingly elated. And thank you LinkedIn for providing a lets-all-reinvent the-wheel code sample with a built-in "issue". If you folks wipe your tail-ends the same half-arsed way you provide code samples, yer walking around with three inches of dried skidmarks in yer undies. Crusty, you know whut I'm sayin.

Rcurl not working with redirect [duplicate]

I'm using curl to fill a form. After completion of the post the other script which handles the form is redirecting to another URL. I want to get this redirect URL into a variable.
Easy way to find the redirected url (if you don't want to know in advance)
$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
You would use
curl_setopt($CURL, CURLOPT_HEADER, TRUE);
And parse the headers for the location header
Here I get the resource http headers then I parse the headers out into an array $retVal. I got the code for parsing the headers from here (http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/) You could also use http://php.net/manual/en/function.http-parse-headers.php if you have (PECL pecl_http >= 0.10.0)
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
// Getting binary data
$header = curl_exec($ch);
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
//here is the header info parsed out
echo '<pre>';
print_r($retVal);
echo '</pre>';
//here is the redirect
if (isset($retVal['Location'])){
echo $retVal['Location'];
} else {
//keep in mind that if it is a direct link to the image the location header will be missing
echo $_GET[$urlKey];
}
curl_close($ch);
You may want to set the CURLOPT_FOLLOWLOCATION to true.
Or set the CURLOPT_HEADER to true and then use regexp to get the Location header.

Encoding issues when posting custom fields via wordpress xmlrpc api

I've a problem with wordpress xml-rpc api. My code gets some data from an xml and posts to a blog. Page title posted well, there is no problem on blog but custom fields are broken.
Code file, xml, blog settings and database tables they are all utf-8 encoded.
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$thumbnail,$cfields,$category,$keywords='',$encoding='UTF-8') {
$title = html_entity_decode(htmlentities($title,ENT_NOQUOTES,$encoding));
$body = html_entity_decode(htmlentities($body,ENT_NOQUOTES,$encoding));
$keywords = html_entity_decode(htmlentities($keywords,ENT_NOQUOTES,$encoding));
array_walk($cfields,arr_encoding); // this function does the same thing with above
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => $cfields
);
$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_ENCODING, "UTF-8" );
$results = curl_exec($ch);
if(curl_errno($ch))
echo '<hr>curl error:'.curl_error($ch)."<hr>";
curl_close($ch);
return $results;}
and this is arr encoding function:
function arr_encoding($cfields){
if(is_array($cfields))
array_walk($cfields, 'arr_encoding');
else if(is_string($cfields))
$cfields = html_entity_decode(htmlentities($cfields,ENT_NOQUOTES,"UTF-8"));}
Do you have any idea?
OK, here it is:
Don't use
xmlrpc_encode_request('blogger.newPost',$params);
and use:
xmlrpc_encode_request('blogger.newPost',$params,
array('encoding'=>'UTF-8','escaping'=>'markup'));

Resources