make emoji view-able in the message-box - php

Screenshot of issue
I am creating a messaging application and want to make emoji images viewable rather than showing their codes in the messages.
I have used an emoji picker js file for entering them in the text area but in sent messages the emoji icon is not showing.
I use the following function :
function loadMessages($token){
// this function is loads all the messages from the database
$db = connect();
$me = $_SESSION['id'];
$query = $db->prepare("SELECT * FROM messages WHERE (fromm=:fromm1 AND too=:too1) OR (fromm=:too2 AND too=:fromm2) ");
$query->bindParam(':fromm1',$me);
$query->bindParam(':too1',$token);
$query->bindParam(':too2',$token);
$query->bindParam(':fromm2',$me);
$query->execute();
$found = $query->rowCount();
if($found){
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$from = $row['fromm'];
$to = $row['fromm'];
$message = $row['message'];
$text = $row['message'];
$html = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $message);
if($from == $me){
$realMessage = "<div class='me'> $html <br /><br /></div>";
} else {
$realMessage = "<div><div class='you'>$html<br /><br /></div></div>";
}
echo $realMessage;
}
The main index.php includes this:
<div class="display-message" style="position: absolute; width: 100%; padding: 10px; background: inherit; bottom: 0;">
</div>

Hi and welcome to Stack Overflow.
There is an encoding issue. You are seeing the Latin output of the characters rather than Unicode (is your database encoding set to something other than UTF-8?).
Get PHP to output the following header before any other output:
header('Content-type: text/html; charset=utf-8');
Add the following meta tag in your <head> section:
<meta charset="utf-8">
And in your loop:
...
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$from=$row['fromm'];
$to=$row['fromm'];
$message=preg_replace("/\\\u([0-9A-F]{2,5})/i","&#x$1;",$row['message']);
$message=mb_convert_encoding($message,'UTF-16','HTML-ENTITIES');
$html=mb_convert_encoding($message,'UTF-8','UTF-16');
...

Related

Mpdf giving fault and not outputting pdf

I am using Mpdf which is working fine locally, the trouble I am having is that the pdf wont output and just get a blank screen
Here is the error
Fatal error: Uncaught Mpdf\MpdfException: Data has already been sent to output (/customers/3/c/2/includes/header.php at line 14), unable to output PDF file in /customers/3/c/2/pdf/vendor/mpdf/mpdf/src/Mpdf.php:9510 Stack trace: #0 /customers/3/c/2: Mpdf\Mpdf->Output('sold.pdf', 'I') #1 /customers/3/c/2/include('/customers/3/c/...') #2 {main} thrown in /customers/3/c/2/pdf/vendor/mpdf/mpdf/src/Mpdf.php on line 9510
Couple of things I have tried, encoding is correct at UTF and NOT DOM, I have no white space, and everything seems to be ok
This is the header code
<?php
session_start();
if(empty($_SESSION['user_id']))
{
header("Location: https://www.home.co.uk");
}
require '../dbcon/database.php';
$db = DB();
require '../lib/library.php';
$app = new WIDGET();
require '../lib/carbon.php';
$user = $app->UserDetails($_SESSION['user_id']);
?>
I have also tried
<?php
session_start();
require '../dbcon/database.php';
$db = DB();
require '../lib/library.php';
$app = new WIDGET();
require '../lib/carbon.php';
$user = $app->UserDetails($_SESSION['user_id']);
?>
Which has made no difference.
And this is the code in line 9510 of Mdpf.php
case Destination::INLINE:
if (headers_sent($filename, $line)) {
throw new \Mpdf\MpdfException(
sprintf('Data has already been sent to output (%s at line %s), unable to output PDF file', $filename, $line)
);
}
Like mentioned all I am getting is a blank page, if I output to an iframe it works ok.
Works fine on 127.0.0.1
Any help much appreciated and thanks in advance for any help
Update:
Sorry forgot to mention or show the code calling the pdf.
I have already tried ob_clean() and still no go
require_once 'pdf/vendor/autoload.php';
if(ob_get_length() > 0) {
ob_clean();
}
$mpdf = new \Mpdf\Mpdf();
$html ='<html>
<body>
<h2 style="font-size: 120px; text-align:center;">SOLD</h2>
<h2 style="font-size: 50px; text-transform: uppercase; text-align:center;">'. $row->widget_model .'</h2>
<h2 style="font-size: 50px; text-transform: uppercase; text-align:center;">'. $row->widget_serial .'</h2><br>
<h2 style="font-size: 30px; text-transform: uppercase; text-align:center;">Delivery Date: '. (new DateTime($_POST['expdelivery']))->format('d-m-Y') .'</h2>
<br>
<h2 style="font-size: 20px; text-align:center;">Contact: '. $_POST['name'] .'</h2>
</body>
</html>';
$mpdf->WriteHTML($html);
$mpdf->Output('sold.pdf','I');
ob_end_flush();
}
EDIT 2:-
Looking at the network Tab it is just showing all the js calls and favicon.ico
It also shows this page updatewidget.php?id=2178
<?php
$page_title = "Widget Tracker - Amend Widget";
$page = '';
include "includes/header.php";
include "includes/sidebar.php";
$id = isset($_GET['id']) ? $_GET['id'] : NULL;
$sth = $db->prepare("SELECT * FROM `widgettracker` WHERE `id` = :id");
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->setFetchMode(PDO::FETCH_OBJ);
$sth->execute();
$row = $sth->fetch();
?>
<section class="content">
<div class="container-fluid">
<?php
if($row->widgetstatus == "Sold")
{include "sold.php";}
else
{include "widgetdetails.php";}
?>
</div>
</section>
<?php
include "includes/footer.php";
include "includes/customjs.php";
?>
And the page that has the Mpdf on is "widgetdetails.php" I need to insert a Sold date and update and generate the pdf. Then the error
You might have a blank line or newline after the closing ?> in your header file. Try removing the closing ?> from your php files that are not actually outputting anything.
You will want to check the network tab in your developer console. You should be able to see the raw data returned by the server, which should show you whatever data it is sending before it reaches the mpdf code.

Embedding tweets using URL received from Twitter API: some are returning errors

I am using the TwitteroAuth API.
I am searching for Tweets using the search API: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Embedding via this method (as you will see from code): https://developer.twitter.com/en/docs/twitter-for-websites/embedded-tweets/guides/embedded-tweet-parameter-reference
Here is my PHP (having already gotten the json object from twitter):
<?php
$tweet_array = json_decode(json_encode($tweets), true);
// Turn each item into tweet
foreach ($tweet_array['statuses'] as $tweet ) {
// Variables
$tweet_text = $tweet['text'];
$twitter_username = $tweet['user']['name'];
$twitter_handle = $tweet['user']['screen_name'];
$output = "";
// Blockquote wrapper
$output .= "<blockquote class='twitter-tweet' data-lang='en'>";
// Text
$output .= "<p lang='en' dir='ltr'>$tweet_text</p>";
// User name and Handle
$output .= "— $twitter_username (#$twitter_handle)";
// Link to tweet
foreach ($tweet['entities'] as $key) {
// So don't break search
if (empty($key)) {
// Do nothing
} else {
// Check for extended_url key
if (array_key_exists("expanded_url",($key[0]))) {
// Boolean to confirm retrieval of URL
$url = true;
// URL output
$url_string = $key[0]['expanded_url'];
$output .= "<a href='$url_string'>$url_string</a>";
}
}
}
$output .= "</blockquote>";
// if URL present, output code
if ($url == true) {
echo $output;
}
}
That code outputs this, a mix of working and not working tweets:
The code being output looks like this (working and not working examples):
Working!
<twitterwidget class="twitter-tweet twitter-tweet-rendered" id="twitter-widget-1" style="position: static; visibility: visible; display: block; transform: rotate(0deg); max-width: 100%; width: 500px; min-width: 220px; margin-top: 10px; margin-bottom: 10px;" data-tweet-id="1057283419007143936"></twitterwidget>
Not working!
<blockquote class="twitter-tweet twitter-tweet-error" data-lang="en" data-twitter-extracted-i1540936951520207597="true"><p lang="en" dir="ltr">He’ll say anything before the election. Don’t take the bait. Focus on ending the hate. Hug a kid. Be nice to someon… <!-- SHORTENED LINK TAKEN OUT FOR STACK OVERFLOW --></p>— Amy Klobuchar (#amyklobuchar)https://twitter.com/i/web/status/1057234049587167232</blockquote>
Any help would be appreciated immensely
I found an answer. Rather than using the vague blockquote conversion method, I instead used PHP to print a JS script for each container with a unique twitter ID. 100% success rate:
<?php /* OUTPUT */
// Count tweets for debug
$number_tweets = count($tweet_array['statuses']);
echo "<div class='cols'>";
// Loop through each tweet
foreach ($tweet_array['statuses'] as $tweet ) {
// Get tweet ID
$id = $tweet["id"];
// Create grid item to be targeted by Twitter's widgets.js
echo "<div class='grid-item'><div id='container-$id'></div></div>";
// Add to array for JS objet
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
// Begin Javascript
echo '<script>';
// Print out JS to convert items to Tweets
$t = 1;
foreach ($js_array as $js ) {
echo $js;
$t++;
}
echo '</script>';

Dynamic CSS with PHP based on database

found a couple answers here on StackOverflow and used them as my models, but I must be missing something. I'm trying to set a couple of background colors dynamically in CSS based on what is in my database, but it's not working - when I check Inspect Element in Chrome, background-color has a line through it and a warning mark for 'Invalid property value'.
Here's my code; it's in two separate files - the first is in the header include file, and the second is in the linked .php / css-esque file.
Header include: [Edited 4/29 to include session code]
session_start();
// check if $_SESSION was set before
if (!isset($_SESSION['email'])) {
header("Location: bad_login.php");
exit();
}
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
PHP/CSS file:
<?php header("Content-type: text/css");
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
EDIT 4/29:
This is the CSS generated:
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: ;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: ;
}
I also echoed the variable back in the html so I know that there should be something in the variable. Should I be opening the database and assigning the variable inside the css.php file?
CSS/PHP is linked this way in header:
<link type="text/css" rel="stylesheet" href="../css/carrier.php">
Instead of using the .css file extension, use .php
in the html file: is it linked to .php?
<link rel='stylesheet' type='text/css' href='css/style.php' />
in the style.php add
<?php
header("Content-type: text/css; charset: UTF-8");
?>
Now you can set up variables for whatever you like:
source
Edit:
Don't forget about session_start(); since you're using sessions (I don't understand how, since nothing gets posted to css/carrier.php you should rather have it in session from a different file & then just use the $companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];).
is this the way your code looks?
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
The answer of yesitsme is correct. Other thing you can do is that each storage changes in the database, run the process of creating this "new" CSS file with the appropriate .css extension.
What if with every request you create a new CSS file?
I mean, you have two paths, when creating the first call to the Web and update it from time to time, either, at the time you keep the data in the database associating it to a script.
With this new CSS and stored is generated through fwrite () and other functions that PHP has to manage files, keep the name of the CSS created in the BDD and then in your place the link as appropriate.

Parsed HTML e-mail section wont display in browser

When a client receives a review on the web from a specific service, that service sends and e-mail that notifies of the new review. The content of the e-mail includes the review itself, and source information, the content comes as (e-mail header, e-mail body PART 1(plain text) and e-mail body PART 2 (HTML). I need to parse the HTML section of those e-mails and push them out to a new flatfile for PHP include on the clients testimonials page.
I am successfully able to connect to my mail service, and parse section 2 of the test e-mail i am using to test with. the problem is that when the output is viewed in the browser it's simply blank. But when I view source - all of the content inclusive of HTML code/structure/css is there. I'm at a loss as to why I see nothing (plaint text or HTML) on the front end of the browser but see everything in source view.
Here is my code:
$login="*email user name*";
$password="*email password*";
$connection = imap_open('{pop.secureserver.net:995/novalidate-cert/pop3/ssl}', $login, $password);
$count = imap_num_msg($connection); /* get number of messages on server */
$i = 46; /* message 46 is the message being used to test this */
$header = imap_header($connection, $i);
$body = imap_fetchbody($connection,$i,"2"); /* grab section 2 of e-mail (HTML) */
$prettydate = date("F jS Y", $header->udate); /* not necessary just part of testing response */
if (isset($header->from[0]->personal)) {
$personal = $header->from[0]->personal;
} else {
$personal = $header->from[0]->mailbox;
}
$email = "$personal <{$header->from[0]->mailbox}#{$header->from[0]->host}>";
echo "On $prettydate, $email said <hr>";
echo $body;
echo "<hr>";
imap_close($connection);
First 15 lines of "view source" after PHP response from within chrome.
On August 3rd 2014, New Review Notifications <pl-no-reply#reviews.com> said <hr><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.=
w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns=3D"http://www.w3=
.org/1999/xhtml"> <head> <meta http-equiv=3D"Content-Type" content=3D"text/=
html; charset=3Dutf-8" /> <title></title> <style type=3D"text/css"> .Extern=
alClass{display:block !important;} .yshortcuts, .yshortcuts a, .yshortcuts =
a:link, .yshortcuts a:visited, .yshortcuts a:hover, .yshortcuts a span{ col=
or:#008ec5; text-decoration:none !important; border-bottom:none !important;=
background:none !important; } body{margin:0;} p{margin:0 !important;} </st=
yle> </head> <body marginheight=3D"0" marginwidth=3D"0" leftmargin=3D"0" to=
pmargin=3D"0" bgcolor=3D"#ffffff"> <table width=3D"100%" cellpadding=3D"0" =
cellspacing=3D"0" bgcolor=3D"#ffffff"> <tr> <td height=3D"25" style=3D"back=
ground-color: #88939B" colspan=3D"3"></td> </tr> <tr> <td width=3D"50%" val=
ign=3D"top"> <table width=3D"100%" cellpadding=3D"0" cellspacing=3D"0" styl=
e=3D"height: 232px;"> <tr> <td style=3D"background-color: #88939B; height: =
232px; display: block"> </td> </tr> </table> </td> <td width=3D"632"> =
PS - can someone with higher rep add imap-fetchbody to tag list if applicable, it wont let me.
Two problems here: a. encoding, b. content display.
Encoding
Somewhere in header (or body) is a property encoding.
This tell's you how your mail content is encoded.
You can then use these pieces of information to revert the encoding.
It might be $body->encoding, instead of $header->encoding.
$body = imap_fetchbody($connection,$i,"2");
if ($header->encoding == 4) {
$body = quoted_printable_decode($body);
}
if ($header->encoding == 3) {
$body = base64_decode($body);
}
echo $body; // now body should have the correct encoding
Give this a try, too:
$body = imap_fetchbody($connection,$i, 1.2); <-- instead of 2
Content Display
As Marc B already pointed out, it's not possible to render a complete HTML page inside a HTML page, without an iframe. An iframe is the easiest way to display this.
But you have several options here, from tag-removal over body-extraction.
If you remove the "important" tags, you get the content.
preg_matching for <body>.*</body> should work, too.
$body = str_replace('<html>', '', $body);
$body = str_replace('<head>', '', $body);
$body = str_replace('<title>', '', $body);
$body = str_replace('<body>', '', $body);
$body = str_replace('</body>', '', $body);
$body = str_replace('</html>', '', $body);

PHP Creating a file to send, output buffer already sent?

Hey I guys I wrote a function to force out a json file, but it seems that the buffer concatenating the file somehow. Normally it should just be a JSON object, but it looks
like the page itself is being inserted into the file?
[{"key":"16","role":null,"region":"Great White North","inspection_type":"citrus","inspection_number":"996","customer_number":"206-420-9564","report_date":"2012-10-21","status":"1","order_date":"2012-02-23 15:24:34","customer":"Jd Daniel","customer_division":"Field worker","memo":null,"billing_key":null,"report_key":"996","shipper":"Hanjin","po":"33215","location":"Boulder, CO","inspector":"Newman","commodity":"Apples","count":"32","size":"medium","label":"Granny Smith","variety":"Golden","pack_date":"0000-00-00","grower_lot":"Lots to grow","color1":"4","color2":"15","texture1":"","texture2":"","puff1":"","puff2":"","scar1":"","scar2":"","solidity1":"","solidity2":"","green1":"","green2":"","sugar_brix1":"","sugar_brix2":"","rating":"0","comments":"Comments 1"},{"key":"17","role":null,"region":"Great White North","inspection_type":"citrus","inspection_number":"996","customer_number":"206-420-9564","report_date":"2012-10-21","status":"0","order_date":"2012-02-23 15:24:34","customer":"Jd Daniel","customer_division":"Field worker","memo":null,"billing_key":null,"report_key":"996","shipper":"Jiun Ming","po":"4215","location":"South Holywood","inspector":"Gadget","commodity":"Grapes","count":"29","size":"46","label":"sweet","variety":"green","pack_date":"0000-00-00","grower_lot":"","color1":"","color2":"","texture1":"","texture2":"","puff1":"","puff2":"","scar1":"","scar2":"","solidity1":"","solidity2":"","green1":"","green2":"","sugar_brix1":"","sugar_brix2":"","rating":"0","comments":"Comments 2"}]
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<style type="text/css">
body {font-family: arial;}
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
input {width:121px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
Weird right? I can't get the buffers to flush right to remove this and am hoping for a better way to get this working. Here's my function.
function getReportDown($array) {
unset($array['select']);
$cleanArray = filter_var_array($array ,FILTER_SANITIZE_STRING);
$array=array(); // needs to be secured -jd
foreach($cleanArray as $k=>$v) {
if(strpos($k,'find_') === false) {
$array[] = explode(':',$k); }
}
require('perms.php.inc');
require('dbconnect.class.inc');
$dbc = Database::obtain(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$dbc->connect();
$form=array();
foreach($array as $key=>$val) {
$form[] = array_pop($dbc->fetch_array("SELECT * FROM reports JOIN ( SELECT * FROM `{$val[0]}` WHERE `key` = {$val[1]}) fruits ON inspection_number = fruits.report_key ORDER BY report_date DESC"));
}
$dbc->close();
$rand = randomAlphaNum(10).'.json';
header("Content-type: application/json");
header("Content-disposition: attachment; filename=$rand");
header('Content-Transfer-Encoding: binary');
echo json_encode($form);
//unlink($rand);
}
exit or die after you echo the JSON.

Categories