I am currently using an imap stream to get emails from an inbox.
Everything is working fine except I am unsure how to get the body text and title of the email. If I do imap_body($connection,$message) the base 64 equivalent of the email attachment is included in the text.
I am currently using this function to get the attachments.
http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/
Well php imap's function are not fun to work with. A user on this page explains the inconsistencies with getting emails: http://php.net/manual/en/function.imap-fetchbody.php#89002
Using his helpful information I created a reliably way to get an email's body text.
$bodyText = imap_fetchbody($connection,$emailnumber,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($connection,$emailnumber,1);
}
$subject = imap_headerinfo($connection,$i);
$subject = $subject->subject;
echo $subject."\n".$bodyText;
My solution (works with all types and charset) :
function format_html($str) {
// Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = str_replace(chr(10), "<br>", $str);
return $str;
}
// Start
$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);
// Recherche de la section contenant le corps du message et extraction du contenu
$obj_section = $obj_structure;
$section = "1";
for ($i = 0 ; $i < 10 ; $i++) {
if ($obj_section->type == 0) {
break;
} else {
$obj_section = $obj_section->parts[0];
$section.= ($i > 0 ? ".1" : "");
}
}
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
// Décodage éventuel
if ($obj_section->encoding == 3) {
$text = imap_base64($text);
} else if ($obj_section->encoding == 4) {
$text = imap_qprint($text);
}
// Encodage éventuel
foreach ($obj_section->parameters as $obj_param) {
if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
$text = utf8_encode($text);
break;
}
}
// End
print format_html($text);
You Can also try these
content-type:text/html
$message = imap_fetchbody($inbox,$email_number, 2);
content-type:plaintext/text
$message = imap_fetchbody($inbox,$email_number, 1);
Related
I want to display all data I want from Matomo API but I can only display them one by one
I don't know if I should do a for loop and where or how.
My code :
<?php
include 'TabMetrique.php';
$token_auth = '*********';
getMetrique($metrique);
$url = "http://localhost/matomo/";
$url .= "?module=API&method=".getMetrique($metrique)."&idSite=1";
$url .= "&period=month&date=2022-05-14";
$url .= "&format=JSON";
$url .= "&token_auth=$token_auth";
$fetched = file_get_contents($url);
$content = json_decode($fetched,true);
// case error
if (!$content) {
print("No data found");
}
else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
?>
My IF condition doesn't work but that's not a problem at the moment
And TabMetrique.php :
<?php
$metrique [0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique [1] = 'UserCountry.getCountry'; // Pays
$metrique [2] = 'UserCountry.getContinent'; //continent
$metrique [3] = 'UserCountry.getRegion'; // Region
$metrique [4] = 'UserCountry.getCity'; // Ville
$metrique [5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique [6] = 'UserLanguage.getLanguage'; // Langue
$metrique [7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique [8] = 'VisitsSummary.get';
$metrique [9] = 'VisitsSummary.getVisits'; //visiteur
$metrique [10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
function getMetrique($metrique){
return $metrique[9];
}
?>
someone can help me ? thx
Well first remove the function it is unnecessary, all you need is an array and then process it with a forech loop.
code TabMetrique.php
<?php
$metrique[0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique[1] = 'UserCountry.getCountry'; // Pays
$metrique[2] = 'UserCountry.getContinent'; //continent
$metrique[3] = 'UserCountry.getRegion'; // Region
$metrique[4] = 'UserCountry.getCity'; // Ville
$metrique[5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique[6] = 'UserLanguage.getLanguage'; // Langue
$metrique[7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique[8] = 'VisitsSummary.get';
$metrique[9] = 'VisitsSummary.getVisits'; //visiteur
$metrique[10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
?>
Now a simple foreach loop to control getting the names from the metrique array
<?php
include 'TabMetrique.php';
$token_auth = '*********';
$url = "http://localhost/matomo/?";
$url .= "period=month&date=2022-05-14";
$url .= "&format=JSON&module=API";
$url .= "&token_auth=$token_auth&idSite=1";
foreach ($metrique as $metric) {
//get static part of the url and add dynamic bit to it
// note i moved the dynamic part to be last, that should not matter to the api
$u = $url . "&method=$metric";
$content = json_decode(file_get_contents($u), true);
// case error
if (!$content) {
print("No data found");
} else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
}
I'm having two errors, can't get this to work...
With the code like this:
<html>
<body>
<?php
/*
Fontes:
- http://blog.clares.com.br/gerando-xml-com-php/
- https://forum.imasters.com.br/topic/482006-resolvido%C2%A0gerar-nomes-aleat%C3%B3rios/
*/
header('Content-type: text/xml; charset=utf-8');
if(empty($_POST["Pergunta"])) {
$pergunta = "";
echo "dar um alert e voltar";
} else {
$pergunta = $_POST["Pergunta"];
}
if(empty($_POST["Resposta"])) {
$resposta = "";
echo "dar um alert e voltar";
} else {
$resposta = $_POST["Resposta"];
$teste = explode("\n",$resposta);
echo '<pre>' . print_r($teste) . '</pre>';
}
/* CHECKBOX
if(isset($_POST['MostrarAIML'])){
//echo "checkbox marcado! <br/>";
//echo "valor: " . $_POST['MostrarAIML'];
$MostrarAIML = true;
}else{
//echo "checkbox não marcado! <br/>";
$MostrarAIML = false;
}
if(isset($_POST['SalvarAIML'])){
//echo "checkbox marcado! <br/>";
//echo "valor: " . $_POST['SalvarAIML'];
$SalvarAIML = true;
}else{
//echo "checkbox não marcado! <br/>";
$SalvarAIML = false;
} */
if(empty($_POST["forma"])) {
$escolhe = "MostrarAIML";
} else if($_POST["forma"]=='MostrarAIML'){
$escolhe = "MostrarAIML";
} else if($_POST["forma"]=='SalvarAIML'){
$escolhe = "SalvarAIML";
}
function nome_aleatorio(){
$tamanho = mt_rand(5,9);
$all_str = "abcdefghijlkmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$nome = "";
for ($i = 0;$i <= $tamanho;$i++){
$nome .= $all_str[mt_rand(0,61)];
}
return $nome;
}
# versao do encoding xml
$dom = new DOMDocument("1.0", "UTF-8");
# retirar os espacos em branco
$dom->preserveWhiteSpace = false;
# gerar o codigo
$dom->formatOutput = true;
# criando o nó principal (root)
$root = $dom->createElement("aiml");
$comentario = $dom->createComment("Copyright ©2017 - FAST.aiml
URL: http://avatar.cinted.ufrgs.br/alunos/fabricio/fastaiml/
Powered by Fabricio Herpich < fabricio_herpich at hotmail.com >
Project coordinator: Liane Margarida Rockenbach Tarouco < liane at penta.ufrgs.br >");
# nó filho (category)
$category = $dom->createElement("category");
# nó filho (pattern) / #setanto a pergunta
$pattern = $dom->createElement("pattern", $pergunta);
# nó filho (template) / #setanto a resposta
$template = array();
for($i = 0; $i < sizeof($teste); $i++){
$template[$i] = $dom->createElement("template", $teste[$i]);
}
# adiciona os nós em aiml
$category->appendChild($comentario);
$category->appendChild($pattern);
for($i = 0; $i < sizeof($template); $i++){
$category->appendChild($template[$i]);
}
# adiciona o nó contato em (root) agenda
$root->appendChild($category);
$dom->appendChild($root);
# busco um nome aleatório
$nome_arquivo = nome_aleatorio();
$dom->save("backup__/" . $nome_arquivo . ".xml");
if($escolhe == "MostrarAIML"){
# imprime o xml na tela
print $dom->saveXML();
}
if($escolhe == "SalvarAIML"){
# imprime o xml na tela
print $dom->saveXML();
# salva o arquivo AIML.xml
header("Content-Disposition: attachment; filename=fastaiml_" . $nome_arquivo . ".xml");
}
?>
</body>
</html>
I'm getting this error:
This page contains the following errors:
error on line 12 at column 18: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.**
I have other php file that works perfectly, where the header() function is after the $nome_arquivo = nome_aleatorio();
But, In this case I don't have the for loops on the code, 'cause I only have one for the file...and in this case I have to put multiple inside the tag...
If I put the header() like the other file, I get:
This page contains the following errors:
error on line 7 at column 18: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.**
how to work around this?
Can someone explain me why I cannot call a var that is set inside an if? And how to call it? I don't understand why this come empty.
I need the vars $workshop_manha and $workshop_tarde bring the values that comes from the DB.
CODE
$id = implode(",", $id);
$sql_consulta = mysql_query("SELECT * FROM pessoa WHERE id IN($id)")
or die (mysql_error());
$linha = mysql_fetch_array($sql_consulta);
$id = $linha['id'];
$nome = $linha['nome'];
$opcoes = $linha['opcoes'];
$opcoes2 = explode(":", $opcoes);
$opcoes3 = explode("+", $opcoes2[1]);
$opcao_congresso = $opcoes3[0]; // Option Congress
if(!empty($opcoes2[2])){
$opcoes4 = explode("+", $opcoes2[2]);
$pre_workshop_manha = $opcoes4[0]; // Workshop Morning Option
if($pre_workshop_manha == 'Paul Gilbert'){
$workshop_manha = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
}
if($pre_workshop_manha == 'Daniel Rijo'){
$workshop_manha = "Daniel Rijo: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
if($pre_workshop_manha == 'Maria Salvador'){
$workshop_manha = "Maria do Céu Salvador: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
}
if(!empty($opcoes2[3])){
$opcoes5 = explode("+", $opcoes2[3]);
$pre_workshop_tarde = $opcoes5[0]; // Worhshop Afternoon Option
if($pre_workshop_tarde == 'Donna Sudak'){
$workshop_tarde = "Donna Sudak: Quando as coisas ficam difíceis: Aplicações práticas da Terapia Comportamental Dialética";
}
if($pre_workshop_tarde == 'Philipp Kendall'){
$workshop_tarde = "Philipp Kendall: Estratégias dentro de tratamentos empiricamente baseados em evidências para jovens com ansiedade";
}
}
echo "Work manhã: ".$workshop_manha; //is coming empty :(
echo "Work tarde: ".$workshop_tarde; //is coming empty :(
That's because $workshop_manha and $workshop_tarde are not defined before the if statement.
Put this before the if statement:
$workshop_manha = '';
$workshop_tarde = '';
You can use them as an array().
Empty the values at the beginning :
$workshop_manha=array();
$workshop_tarde=array();
Than use the values as :
$workshop_manha[] = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
Display them as below :
if(!empty($workshop_manha)) {
foreach ($workshop_manha as $manha) {
echo "$manha <br />";
}
}
if(!empty($workshop_tarde)) {
foreach ($workshop_tarde as $tarde) {
echo "$tarde <br />";
}
}
I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:
http://www.server.com/en/something/else/to/do
I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.
I use this class to change Language:
class IDIOMAS {
private $UserLng;
private $langSelected;
public $lang = array();
public function __construct($userLanguage){
$this->UserLng = $userLanguage;
}
public function userLanguage(){
switch($this->UserLng){
case "en":
$lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';
// Menu
$lang['MENU_LOGIN'] = 'Login';
$lang['MENU_SIGNUP'] = 'Sign up';
$lang['MENU_LOGOUT'] = 'Logout';
$lang['MENU_SEARCH'] = 'Search';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
$lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
$lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
$lang['SUBSCRIBE_SEND'] = 'SEND';
//LOGIN
$lang['LOGIN_TITLE'] = 'Please Login to your account';
$lang['LOGIN_USER'] = 'User';
$lang['LOGIN_PASSWORD'] = 'Password';
$lang['LOGIN_ERROR'] = '¡User and/or password invalid!';
//REGISTER
$lang['REGISTER_NAME'] = 'Please write your name';
$lang['REGISTER_LAST_NAME'] = 'Please write your last name';
$lang['REGISTER_EMAIL'] = 'Write your E-mail';
$lang['REGISTER_CITY'] = 'Enter your City name';
$lang['REGISTER_COUNTRY'] = '¿Where are you from?';
$lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
$lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';
return $lang;
break;
case "es":
$lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';
// Menu
$lang['MENU_LOGIN'] = 'Entrar';
$lang['MENU_SIGNUP'] = 'Registrarse';
$lang['MENU_LOGOUT'] = 'Salir';
$lang['MENU_SEARCH'] = 'Buscar';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
$lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
$lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
$lang['SUBSCRIBE_SEND'] = 'Enviar';
//LOGIN
$lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
$lang['LOGIN_USER'] = 'Usuario';
$lang['LOGIN_PASSWORD'] = 'Clave';
$lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';
//REGISTRO
$lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
$lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
$lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
$lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
$lang['REGISTRO_PAIS'] = '¿De donde eres?';
$lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
$lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';
return $lang;
break;
}
}
}
I use this class with this code:
$language = new IDIOMAS($lang);
$langArray = array();
$langArray = $language->userLanguage();
And set the language like this:
if (!isset($_SESSION['idioma'])){
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$_SESSION['idioma'] = $lang;
}else{
$lang = $_SESSION['idioma'];
}
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
$_SESSION['idioma'] = $_GET['lang'];
$lang = $_SESSION['idioma'];
}
Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.
I have a function to get the current url for redirections when being logged or register.
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
I was trying to change the lang value inside that function with no success,
Really appreciate any help
Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:
// Find the first forward slash location
$pos1 = strpos($url,'/'); // The whole URL
// You only need this next line if your language codes are different sizes
// If they are always 2 then can alter the code to not use it
$pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
$base = substr($url,0,$pos1); // Get domain name half
$end = substr($url,$pos2); // Get everything after language area
// Now from the function return the result
$val = $base.'/'.$newlang.'/'.$end;
return $val;
You may need to add or subtract 1 on the $pos to get the right values returned, like so:
$pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
$base = substr($url,0,$pos1-1); // In case its returning the slash
$end = substr($url,$pos2+1); // In case its return the slash
Please tweak and test this, it is only the concept in action, I have not tested this snip-it.
Finally i got it by modifying the getUrl function to this:
function getUrl($newlang) {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
$substr = substr($url,27,3);
$base = substr($url,0,28);
$resto = substr($url,31,1000);
$newUrl = $base.$newlang."/".$resto;
return $newUrl;
}
and calling the function like this getUrl("en") or getUrl("es");
Maybe this can be usefull for someone else.
I am trying to read through an email inbox for my application - I'm using the zend framework here. The problem is that I'm unable to retrieve the message body for certain emails. The following is my code as to how I'm doing this:
$mail = new Zend_Mail_Storage_Imap($mail_options);
$all_messages = array();
$page = isset($_GET['page'])?$_GET['page']:1;
$limit = isset($_GET['limit'])?$_GET['limit']:20;
$offset = (($page-1)*$limit)+1;
$end = ($page*$limit)>$c?$c:($page*$limit);
for ($i=$offset;$i<=$end;$i++){
$h2t = new html2text();
$h2t->set_allowed_tags('<a>');
if(!$mail[$i])
break;
else{
$one_message = $mail->getMessage($i);
$one_message->id = $i;
$one_message->UID = $mail->getUniqueId($i);
$one_message->parts = array();
$one_message->body = '';
$count = 1;
foreach (new RecursiveIteratorIterator($mail->getMessage($i)) as $ii=>$part) {
try {
$tpart = $part;
//$tpart->_content = '';
$one_message->parts[$count] = $tpart;
$count++;
// check for html body
if (strtok($part->contentType, ';') == 'text/html') {
$b = $part->getContent();
if($part->contentTransferEncoding == 'quoted-printable')
$b = quoted_printable_decode($b);
$one_message->html_body = $b;
$h2t->set_html($b);
$one_message->body = $h2t->get_text();
}
//check for text body
if (strtok($part->contentType, ';') == 'text/plain') {
$b = $part->getContent();
if($part->contentTransferEncoding == 'quoted-printable')
$b = quoted_printable_decode($b);
$one_message->text_body = $b;
$one_message->body = $b;//$part->getContent();
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
$all_messages[] = $one_message;
}
}
The problem is that randomly some messages don't return even a textbody or an html body. Even though if I check using a webvmail client those emails have a message body as well. WHat am I missing here?
You need to check if the mail is multipart message first, before looping over the parts. If it's not multipart, then the body will be exposed via $mail->getContent() instead of a part. Basic example:
if ($mail->isMultiPart()) {
// Multipart messages handled here
foreach() {
// loop over parts
}
} else {
// Non multipart messages handled here
// default text_body
$one_message->text_body = $mail->getContent();
if (strtok($msg->contentType, ';') == 'text/html') {
// HTML email with no plain text alternative, set both values
$one_message->body = $mail->getContent();
$one_message->text_body = strip_tags($mail->getContent());
}
}