Adding a yii2 view when sending a html email - yii2

I have this code in my yii2 application that i am using to send emails with sendgrid. It connects well to sendgrid but does not include images
public function actionApi()
{
echo Yii::$app->formatter->asTimestamp(date('Y-d-m h:i:s'));
//$collection = Yii::$app->mongodb->getCollection('rooms');
//$collection->insert(['name' => 'John Smith', 'status' => 1]);
$mailer = Yii::$app->mailer;
$message = $mailer->compose()
->setTo('rod#yahoo.mx')
->setFrom(['info#google.mx' => 'Mexico City])
->setReplyTo('info#google.mx')
->setSubject('Your package is here')
->setHtmlBody('Your package is here')
->setHtmlBody($this->render('app_launch'))
->send();
if ($message === true) {
echo 'Success!';
echo '<pre>' . print_r($mailer->getRawResponses(), true) . '</pre>';
} else {
echo 'Error!<br>';
echo '<pre>' . print_r($mailer->getErrors(), true) . '</pre>';
}
}
of the template attached. How can i display the images when sending html emails? Is there a way i can reference the view file absolutely here
->setHtmlBody($this->render('app_launch'))
to be able to send the emails?

You need to do this https://www.yiiframework.com/doc/guide/2.0/en/tutorial-mailing#embedding-images. End to get html text without view template you can use $this->renderPartial("your_view_file");
And I think you only need one html body.

Related

Get Facebook page posts to Wordpress with JS SDK or PHP SDK

I want to get the posts from a Facebook page and show them on a Wordpress site.
Firstly, I tried with the JavaScript SDK and succeeded, but couldn't figure out how to call the access token from server-side.
Secondly, I've been trying with the PHP SDK, but can not get it to work no matter what I try.
I've been over the documentation so many times I've lost count. It just doesn't make sense to me.
This is the PHP where I'm currently at:
require_once( 'out-fb/src/Facebook/autoload.php' );
$app_id = "{app-id}";
$secret = "{app-secret}";
$access_token = "{access-token}";
$fb = new Facebook([
'app_id' => $app_id,
'app_secret' => $secret,
'default_graph_version' => 'v5.0',
'default_access_token' => $access_token
]);
try {
// $response = $fb->getClient()->sendRequest($request);
$response = $fb->get('/{page-id}}/posts?fields=message,full_picture,created_time&limit=5');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
I don't exactly know how to translate the JSON and get the code to my front-end, but even now I get an error from WP saying "The site is experiencing technical difficulties."
If someone could guide me through the PHP SDK or maybe show me how to place the access_token server-side with the JS SDK, I'd be so damn grateful!
Thanks in advance.
So I figured it out.
I still don't know exactly how I did it, but you can see here what eventually worked for me.
I think what broke it was using $fb = new Facebook([ instead of $fb = new Facebook\Facebook([
<?php
require_once 'out-fb/src/Facebook/autoload.php';
$app_id = "{app-id}";
$app_secret = "{app-secret}";
$access_token = "{access_token}";
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v5.0',
]);
$response = $fb->get('/{page-id}/posts?fields=message,full_picture,created_time&limit=5', $access_token);
$node = $response->getGraphEdge();
echo $node->getField('3')[message];

How to retrive the parameters in URL + laravel

for web services , how to retrieve the data json format using Laravel, can anybody help
https://test.com/admin/users/apiLogin?Login={"email":test#test.com,"pwd":testing}
in Controller
public function apiLogin(Request $request)
{
//$data = $request->json()->all();
$data=json_decode($request['Login']);
echo $data['email'];
echo "<pre>";
print_r($data);
echo "</pre>";
echo "testsetet";
exit;
}
To get the URL parameter use this:
$login = $request->input('login'); // or $request['Login']
The goal is to turn login (which is a string) into appropriate JSON format so that you can use json_decode.
I'll break it down in steps:
Remove all \n characters:
$login = str_replace('\n', '', $login);
Remove last comma
$login = rtrim($login, ',');
Add brackets
$login = "[" . trim($login) . "]";
Turn it into a PHP array:
$json = json_decode($login, true);
The issue here is that your url parameter 'Login' isn't properly formatted json. I would revisit your front-end code persisting this data and ensure it is formatting properly. True json should look like:
{"email":"test#test.com","pwd":"testing"}
As a BIG aside, never persist passwords in the URL. It is dangerously foolish. Use a POST request to do this. On the plus side, the back-end code will be virtually the same with your json_decode() logic.

cakephp : getting pagination link in json format

I am developing a REST API using CakePHP and want to implement the Instagram API pagination style which looks something like this:
{
...
"pagination": {
"next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
"next_max_id": "13872296"
}
}
I have not used any authorization or whatever, so the access_token part can be ignored. My main motive is to get the pagination links (jump links preferably) as JSON data, so I can use it in my JSON serialized view. Because the usual code:
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
doesn't work and simply displays the equivalent HTML code.
Is there any way I can get it like the Instagram API?
Thanks to noslone, i have got the answer. here is the final edited code:
$url = 'http://yourapp.com/pages/index/limit:7';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$temp = intval($this->Paginator->current())+1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
if($this->Paginator->hasPrev()) {
$temp = intval($this->Paginator->current())-1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
echo json_encode($returnArray);
just two changes : first don't forget to add limit:value" to your url and secondly use intval with the Paginator->current.
Try something as follow
$url = 'http://yourapp.com/pages/index';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$returnArray['pagination']['next_url'] = $url.'/page:'. ($this->Paginator->current()+1);
}
if($this->Paginator->hasPrev()) {
$returnArray['pagination']['prev_url'] = $url.'/page:'. ($this->Paginator->current()-1);
}
echo json_encode($returnArray);
If you want, you can add more named params to the url:
$params['pagination']['next_url'] = $url.'/page:'.$this->Paginator->current()+1.'/order:name/direction:asc';
As far as I know, Paginator helper generates the front-end link, and when you click on it, it will generate next link.
I do not think you can use it directly to form the Instagram alike API.

cakephp Image escape false not working

I am making a Image link to user profile, but it is not working as it should be
this is my code.with this i want to add contoroller,function and id. How i can do it.
<?php
$pic = $User['User']['url'];
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), array('alt'=>$User['User']['handle'],'title' => $User['User']['handle']),array('escape'=>false) ,array('class'=>'inner_image'));
}else{
echo $this->Html->link($this->Html->image($User['User']['url']),array('alt' => $User['User']['handle']),array('escape'=>false),array('class'=>'inner_image'));
}
?>
This code is making image a link but i can't define a link and it is not accepting the class
.I want to pass this url
$this->Html->link('', array('controller'=>'User','action'=>'view','id'=>$User['User']['id']));
This is how I did it
echo $this->Html->link($this->Html->image($pic, array('class'=>'inner_image')), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false));
What cake version are you using? You don't seem to be following the documentation for Html::link.
HtmlHelper::link(string $title, mixed $url = null, array $options =
array(), string $confirmMessage = false)
alt, escape and class should be indexes in the options array, but you're not defininf the url parameter anywhere.
It should be something like this
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), $url_array, array('alt'=>$User['User']['handle'],'title' => $User['User']['handle'],'escape'=>false,'class'=>'inner_image'));
} else {
echo $this->Html->link($this->Html->image($User['User']['url']), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false, 'class'=>'inner_image'));
(don't know what url you want to point this at, so replace $url_array to your convenience.

updating multiple rows with codeigniter

Im having some trouble getting on with my first codeigniter project, and i have a feeling the answer is really near...
Im populating a form of inputfields from a database, and when the user submits the form, it should run through the rows of the database, and update the content based on the 'id' of each row.
My form (in the view 'admin.php') looks something like this:
<?php echo form_open('admin/update'); ?>
<?php foreach($content as $row) : ?>
<?php echo form_input('id['. $row->id .'][id]', $row->id); ?>
<?php echo form_input('id['. $row->id .'][order]', $row->order); ?>
<?php echo form_input('id['. $row->id .'][title_text]', $row->title_text); ?>
<?php echo form_textarea('id['. $row->id .'][body_text]', $row->body_text); ?>
<?php
if ($row->visibility == 'visible') {
echo form_checkbox('id['. $row->id .'][visibility]', 'visibility', TRUE);
} else {
echo form_checkbox('id['. $row->id .'][visibility]', 'visibility', FALSE);
}
?>
<?php endforeach;?>
<?php echo form_submit('Save Changes', 'Save Changes'); ?>
<?php echo form_close(); ?>
Now, most of this is based on a mix of tutorials and help documents. Here's the code from the controller 'admin', that i call when people click 'Save changes':
function update()
{
$this->load->model('admin_model');
$this->admin_model->updateRecords($_POST['id']);
$this->index();
}
The data is then passed on to the model, wherein the function looks like this:
function updateRecords($data)
{
$this->db->insert_batch('content', $data);
}
This is the only way i have gotten it to somehow work. It inserts the data fine, but adds it in new rows instead of updating the ones already there, according to their unique 'id's.
For good orders sake, here's the columns i have in my mySQL database:
id (PRIMARY and AUTOINCREMENT)
order
title_text
body_text
visibility
origin_date
Thanks alot in advance :)
Here's how I might do it, I added in some basic error handling; Hope this explains itself:
Model
function updateRecords($records)
{
// Method 1
// If you want to proceed if there is an error
$errors = array();
// Method 2
// If you want to rollback if there is an error
$this->db->trans_start();
foreach ($records as $id => $values):
// Your form fields conveniently match the column names
// No need to create the data array, we already have it
// If you want to update `origin_date` just do this:
// $values['origin_date'] = time();
// See if checkbox values were sent
// Assumes visibility is integer
if (empty($values['visibility']))
{
$values['visibility'] = 0;
}
else
{
$values['visibility'] = 1;
}
// Using method 1, store the error id in an array
$this->db
->where('id', $id)
->update('content', $values) OR $errors[] = $id;
// If using method 2, stop the loop
$this->db
->where('id', $id)
->update('content', $values) OR break;
endforeach;
// Method 1
// Return the array of failed updates
// Controller will check if the array is empty
// You can tell the user which updates failed or just how many
return $errors;
// Method 2
// This will return TRUE or FALSE
$this->db->trans_complete();
return $this->db->trans_status();
}
Controller
function update()
{
$records = $this->input->post('id');
$this->load->model('admin_model');
// Make sure to return errors here if they occur
// Using method 1
$errors = $this->admin_model->updateRecords($records);
$num_errors = count($errors);
if ($num_errors > 0)
{
echo "There were {$num_errors} errors!";
// You can optionally print which records had errors
echo "There were errors updating these rows: ".implode(', ', $errors);
}
// Using method 2
$success = $this->admin_model->updateRecords($records);
if ( ! $success)
{
echo "Error performing update, no records were saved.";
}
$this->index();
}
Don't just echo the errors of course, use some kind of message library, session data, or send variables to the view. Some references:
http://codeigniter.com/user_guide/database/transactions.html
http://codeigniter.com/user_guide/database/active_record.html#update