I'm trying to read mails with Zend_Mail_Storage_Imap. Here is a part of my code :
$mail = new Zend_Mail_Storage_Imap(
array( 'host' =>'imap.gmail.com',
'ssl' =>true,
'port'=>993,
'folder'=>'inbox',
'user' => '***',
'password' => '***'
)
);
foreach ($mail as $k => $message) {
$msg = $mail->getMessage( $k );
echo $msg->getContent();
}
Everthing work's well, except the accent format. I have things like this :
int=C3=A9gration for intégration
S=C3=A0rl* for sàrl
Can somebody help me?
utf8_decode( quoted_printable_decode( $part->getContent() ))
Have a look into the "getText()" method here:
http://wiip.fr/content/zend-mail-storage-imap
The text is in french, but don't bother and only take what you need into this getText method. Basically you need to determine the encoding of the email & decode it.
You can also have a look there : Email decoding doesn't work in zend mail
here it is a possible solution if you use utf-8 internal encoding.
/**
* retrieves message content
* #param Zend_Mail_Message|Zend_Mail_Part $oMessage
* #return string returns message content as utf-8 string from message object
*/
public static function contentDecoder ($oMessage, $bVerbose = false) {
mb_internal_encoding("UTF-8");
echo ($bVerbose)?("\tultimateContentDecode {\n"):('');
if($oMessage->headerExists('content-type')) {
echo ($bVerbose)?("\t\t" . $oMessage->contentType . "\n"):('');
preg_match('/^([a-z\/]+)(?:;\s+format=[a-zA-Z0-9-]+)?(?:;\s+charset=([a-zA-Z0-9-]+))?/i',
str_replace('"', '', $oMessage->contentType), $matches);
list(,$sMimeType,$sEncoding) = $matches;
echo ($bVerbose)?("\t\tType of this part is {$sMimeType}, {$sEncoding}\n"):('');
} else {
$sContent = $oMessage->getContent();
$sMimeType = 'text/plain';
$sEncoding = mb_detect_encoding($sContent, self::$_sEncDetectOrder);
echo ($bVerbose)?("\t\tUnknow content type. text/plain; charset={$sEncoding}\n"):('');
}
$sEncoding = strtoupper($sEncoding);
if($oMessage->headerExists('content-transfer-encoding')) {
$sQuoting = $oMessage->contentTransferEncoding;
echo ($bVerbose)?("\t\tContent-Transfer-Encoding: " . $oMessage->contentTransferEncoding . "\n"):('');
} else {
$sQuoting = '';
}
$sContent = $oMessage->getContent();
switch ($sQuoting) {
case 'quoted-printable':
case '7bit':
$sContent = quoted_printable_decode($sContent);
break;
case 'base64':
$sContent = base64_decode($sContent);
break;
}
if ($sEncoding != 'UTF-8') {
echo ($bVerbose)?("\t\tConvert encoding: {$sEncoding} -> UTF-8 \n"):('');
$sContent = mb_convert_encoding($sContent, 'UTF-8', $sEncoding);
}
$sContent = trim(preg_replace(
array('/^\s+/m', '/\s+$/m', '/[ \t]+/'),
array('', '', ' '), $sContent));
echo ($bVerbose)?("--\n{$sContent}\n--"):('');
echo ($bVerbose)?("\t}\n"):('');
return $sContent;
}
Related
When a new user register, moodle send confirmation email to user, from the language file lang/en/moodle.php with a string "emailconfirmation" by a moodle function:
function send_confirmation_email($user) {
global $CFG;
$site = get_site();
$supportuser = generate_email_supportuser();
$data = new stdClass();
$data->firstname = fullname($user);
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
$username = urlencode($user->username);
$username = str_replace('.', '%2E', $username); // prevent problems with trailing dots
$data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
$message = get_string('emailconfirmation', '', $data);
$messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
return email_to_user($user, $subject, $message, $messagehtml);
}
Moodle redirects to index.php after confirmation. How do I redirect $data->link to a custom page after confirmation:
if (send_confirmation_email($user)) {
if (AUTH_CONFIRM_OK = true) {
$urltogo = new moodle_url($CFG->wwwroot . "/coursestat/view.php", array('id' => $statid));
redirect($urltogo);
}
}
else
print_error('auth_noemail','auth_email');
Just use $data->link assuming its a string?
if (send_confirmation_email($user)) {
// Assuming $data->link is a string?
$urltogo = new moodle_url($data->link);
redirect($urltogo);
}
This line
if (AUTH_CONFIRM_OK = true) {
Doesn't make sense, AUTH_CONFIRM_OK is a constant. Also = is an assignment. I'm guessing you meant something like this:
if ($somevariable == AUTH_CONFIRM_OK) {
Now that I've upgraded to "facebook/php-ads-sdk": "2.8.*" (https://github.com/facebook/facebook-php-ads-sdk), this function of mine doesn't work anymore:
public function addToCustomAudience($entriesArray, $audienceId, $inputType = CustomAudienceTypes::EMAIL) {
$audience = new CustomAudience($audienceId);
$result = $audience->addUsers($entriesArray, $inputType);
return $result;
}
Apparently addUsers is no longer available.
I see a createUser function, but it looks quite different, and there is no documentation online about how to migrate from addUsers to createUser.
What I want to do is simple.
Given an array of email addresses and an ID of an audience, how can I add all of those email addresses to that Facebook Custom Audience?
From what I can see in the code, addUsers is still there, and it's documented on the Developer site.
I just used the latest SDK along with the following code to update an audience:
use FacebookAds\Object\CustomAudience;
use FacebookAds\Object\Values\CustomAudienceTypes;
$emails = array(
'test1#example.com',
'test2#example.com',
'test3#example.com',
);
$audience = new CustomAudience(<CUSTOM_AUDIENCE_ID>);
$audience->addUsers($emails, CustomAudienceTypes::EMAIL);
This seems to work for my purposes.
I copied some code from the facebook-php-ads-sdk as a workaround.
$audience = new CustomAudience($audienceId);
$params = $this->formatParams($entriesArray, $inputType, [], false);
$audience->createUser([], $params, false);
/**
* Copied this from Facebook's https://github.com/facebook/facebook-php-ads-sdk/blob/d51193b19d730ae9274d45540986e1ac311b074d/src/FacebookAds/Object/CustomAudience.php#L363
* Take users and format them correctly for the request
*
* #param array $users
* #param string $type
* #param array $app_ids
* #param bool $is_hashed
* #return array
*/
protected function formatParams(array $users, $type, array $app_ids = array(), $is_hashed = false) {
if ($type == CustomAudienceTypes::EMAIL || $type == CustomAudienceTypes::PHONE) {
$normalizer = new EmailNormalizer();
$hash_normalizer = new HashNormalizer();
foreach ($users as &$user) {
if ($type == CustomAudienceTypes::EMAIL) {
$user = $normalizer->normalize(CustomAudienceTypes::EMAIL, $user);
}
if (!$is_hashed) {
$user = $hash_normalizer->normalize(
CustomAudienceTypes::EMAIL, $user);
}
}
}
$payload = array(
'schema' => $type,
'data' => $users,
);
if ($type === CustomAudienceTypes::ID) {
if (empty($app_ids)) {
throw new \InvalidArgumentException(
"Custom audiences with type " . CustomAudienceTypes::ID . " require"
. "at least one app_id");
}
$payload['app_ids'] = $app_ids;
}
return array('payload' => $payload);
}
I am creating a custom theme for OpenCart 2.3 and I need to show some additional information in page header (header.tpl). So I added some variable to catalog/controller/common/header.php:
$data['some_var'] = 'some_value';
And then I am trying to use this data in the header.tpl:
<?php echo $this->data['some_var']; ?>
But I am always getting this error:
Notice: Undefined index: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
If I try to use this code:
<?php echo $some_var; ?>
Then I am getting another error:
Notice: Undefined variable: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
And even when I do echo print_r($this->data) in header.tpl I don't even see this variable in $data array.
What am I doing wrong? Please help.
EDIT
Here is the full code of my header.php controller file. I added my custom variable at the very end of the file.
class ControllerCommonHeader extends Controller {
public function index() {
// Analytics
$this->load->model('extension/extension');
$data['analytics'] = array();
$analytics = $this->model_extension_extension->getExtensions('analytics');
foreach ($analytics as $analytic) {
if ($this->config->get($analytic['code'] . '_status')) {
$data['analytics'][] = $this->load->controller('extension/analytics/' . $analytic['code'], $this->config->get($analytic['code'] . '_status'));
}
}
if ($this->request->server['HTTPS']) {
$server = $this->config->get('config_ssl');
} else {
$server = $this->config->get('config_url');
}
if (is_file(DIR_IMAGE . $this->config->get('config_icon'))) {
$this->document->addLink($server . 'image/' . $this->config->get('config_icon'), 'icon');
}
$data['title'] = $this->document->getTitle();
$data['base'] = $server;
$data['description'] = $this->document->getDescription();
$data['keywords'] = $this->document->getKeywords();
$data['links'] = $this->document->getLinks();
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['lang'] = $this->language->get('code');
$data['direction'] = $this->language->get('direction');
$data['name'] = $this->config->get('config_name');
if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
$data['logo'] = $server . 'image/' . $this->config->get('config_logo');
} else {
$data['logo'] = '';
}
$this->load->language('common/header');
$data['text_home'] = $this->language->get('text_home');
// Wishlist
if ($this->customer->isLogged()) {
$this->load->model('account/wishlist');
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), $this->model_account_wishlist->getTotalWishlist());
} else {
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
}
$data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
$data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', true), $this->customer->getFirstName(), $this->url->link('account/logout', '', true));
$data['text_account'] = $this->language->get('text_account');
$data['text_register'] = $this->language->get('text_register');
$data['text_login'] = $this->language->get('text_login');
$data['text_order'] = $this->language->get('text_order');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['text_download'] = $this->language->get('text_download');
$data['text_logout'] = $this->language->get('text_logout');
$data['text_checkout'] = $this->language->get('text_checkout');
$data['text_category'] = $this->language->get('text_category');
$data['text_all'] = $this->language->get('text_all');
$data['home'] = $this->url->link('common/home');
$data['wishlist'] = $this->url->link('account/wishlist', '', true);
$data['logged'] = $this->customer->isLogged();
$data['account'] = $this->url->link('account/account', '', true);
$data['register'] = $this->url->link('account/register', '', true);
$data['login'] = $this->url->link('account/login', '', true);
$data['order'] = $this->url->link('account/order', '', true);
$data['transaction'] = $this->url->link('account/transaction', '', true);
$data['download'] = $this->url->link('account/download', '', true);
$data['logout'] = $this->url->link('account/logout', '', true);
$data['shopping_cart'] = $this->url->link('checkout/cart');
$data['checkout'] = $this->url->link('checkout/checkout', '', true);
$data['contact'] = $this->url->link('information/contact');
$data['telephone'] = $this->config->get('config_telephone');
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
// Level 1
$data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$data['language'] = $this->load->controller('common/language');
$data['currency'] = $this->load->controller('common/currency');
$data['search'] = $this->load->controller('common/search');
$data['cart'] = $this->load->controller('common/cart');
// For page specific css
if (isset($this->request->get['route'])) {
if (isset($this->request->get['product_id'])) {
$class = '-' . $this->request->get['product_id'];
} elseif (isset($this->request->get['path'])) {
$class = '-' . $this->request->get['path'];
} elseif (isset($this->request->get['manufacturer_id'])) {
$class = '-' . $this->request->get['manufacturer_id'];
} elseif (isset($this->request->get['information_id'])) {
$class = '-' . $this->request->get['information_id'];
} else {
$class = '';
}
$data['class'] = str_replace('/', '-', $this->request->get['route']) . $class;
} else {
$data['class'] = 'common-home';
}
//CUSTOM THEME VARIABLES BEGIN
$data['some_var'] = 'some_value';
//CUSTOM THEME VARIABLES END
return $this->load->view('common/header', $data);
}
}
I need to see your controller to get the full picture and then i will give you the full answer, but take a look on your controller and make sure that you bind your data like the sample below:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
Thanks
I finally found the solution of my problem, but I am not sure if it is the right way to do this. I found that I need to make changes in system/storage/modification/catalog/controller/common/header.php. It seems like after installing some extension via Vqmod the controller file have been copied to this folder. If I add my variables there then I can access them without any issues.
I'm trying to do searches with the API from last.fm with Zend_Rest_Client.
What am I to do with the response? How do I get the values from the response?
object(Zend_Rest_Client_Result)[226]
protected '_sxml' =>
object(SimpleXMLElement)[228]
public '#attributes' =>
array
'status' => string 'ok' (length=2)
public 'results' =>
object(SimpleXMLElement)[229]
public '#attributes' =>
array
...
public 'trackmatches' =>
object(SimpleXMLElement)[230]
...
protected '_errstr' => null
How do I loop over trackmatches? Everything I try returns null.
$results = $object->getIterator();
foreach($result as $result) {
...
}
Above code will do the magic.
You have to keep dereferencing until you get to something that isn't a SimpleXMLElement object. Trying to print a SimpleXMLElement object doesn't work.
$results = $object->getIterator();
foreach($results->results->trackmatches as $t) {
echo $t->sometagname;
}
I did not manage to be able to do it with Zend. Looks like a useless class like Zend_Http. I had to use the gool 'ol SPL:
$url = $this->host . '?method=track.search';
$url .= '&api_key=' . $this->apikey;
$url .= '&track=' . urlencode($value);
try {
$xmlstr = file_get_contents($url);
$xml = new SimpleXMLElement($xmlstr);
//var_dump($xml->results->trackmatches);
return $xml->results->trackmatches;
} catch (Exception $e) {
echo '<h4>url = ' . $url . '</h4>';
var_dump($e);
}
Is there any class in the Zend Framework that allows me to easily read emails?
The Zend_Mail class does allow me to easy get headers, subject and the content body. But transferring everything to UTF-8 and human-readable format is still a pain.
Or am I doing something wrong? As far as I can tell, Zend Framework does not allow me to easily get UTF-8 strings that I can just use, I still have to do some post-processing. Right?
The key thing is that you need to iterate over the parts within the Message and find the text. Once you have it, then you can use quoted_printable_decode to get the text itself in a useful way.
This is some rough and ready code that reads IMAP email boxes with Zend_Mail:
<?php
$mail = new Zend_Mail_Storage_Imap(array(
'host' => EMAIL_ACCOUNT_HOST,
'user' => EMAIL_ACCOUNT_USERNAME,
'password' => EMAIL_ACCOUNT_PASSWORD,
));
echo (int)$mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
$from = $message->getHeader('from');
$subject = trim($message->subject);
$to = trim($message->to);
$body = getBody($message);
// do something with message here
}
function getBody(Zend_Mail_Message $message)
{
// find body
$part = $message;
$isText = true;
while ($part->isMultipart()) {
$foundPart = false;
$iterator = new RecursiveIteratorIterator($message);
foreach ($iterator as $part) {
// this detection code is a bit rough and ready!
if (!$foundPart) {
if (strtok($part->contentType, ';') == 'text/html') {
$foundPart = $part;
$isText = false;
break;
} else if (strtok($part->contentType, ';') == 'text/plain') {
$foundPart = $part;
$isText = true;
break;
}
}
}
if($foundPart) {
$part = $foundPart;
break;
}
}
$body = quoted_printable_decode($part->getContent());
}