How to use Auth component of Cakephp 3 in Event - cakephp

I'm using CakePHP 3.2 and proffer plugin for image uploading.
I want to rewrite the default path of proffer plugin to upload image and change image name before save.
As per the documentation of proffer from github. I have created an event in /src/Event
Now I want to rename the file like
$this->Auth->user('id').'-'.$row('id').date('dmyhis').ext
this is what I have done
$newFilename = $this->Auth->user('id').'-'.$event->subject()->get('id') . '_' . Inflector::slug($event->subject()->get('name')) . date('ymdhis') . $ext;
But this is giving error that Auth can not be used here. Is there any way to use Auth Component outside controller ?

You can access the logged in user id by loading the session.
use Cake\Network\Session;
$session = new Session();
$userData = $session->read('Auth.User.id');
Use this as a reference: Reading & Writing Session Data

With cake 3.x and after, you should using this:
$this->request->session()->read('Auth');
When debug it
debug( $this->request->session()->read('Auth') );
[
'id' => (int) 2,
'username' => 'admin',
'nice_name' => 'Tommy Do',
'first_name' => 'Huy',
'last_name' => 'Đỗ',
...//and more info in UserTable
]
And access to each element.
$this->request->session()->read('Auth.nice_name');
Print:
Tommy Do
Hope it will help you :D

Related

Google App Engine Send Grid PHP attachment

I am trying to add attachments as shown on https://github.com/sendgrid/sendgrid-google-php. But its not working by this way. I think I tried every possible solution but cant make this work. Here is my code.
<?php
require 'SendGrid_loader.php';
// Connect to your SendGrid account
$sendgrid = new SendGrid\SendGrid('myusername', 'mypassword');
// Make a message object
$mail = new SendGrid\Mail();
// Mail arrayi
$emails = array("mailadress1#test.com","mailadress2#test.com");
$names = array("name1", "name2");
// Add recipients and other message details
$mail->setTos($emails)->
setFrom('testsender#test.com')->
setFromName('Test Sender')->
setReplyTo('testemail#test.com')->
setSubject('Test')->
addAttachment("test.jpg")->
addCategory("TEST-GONDERIM")->
addUniqueArgument("BASIN", "YEREL-BASIN")->
addSubstitution("%name%", $names)->
setText('TEXT BODY MESSAGE')->
setHtml('<strong>%name% MERHABA,</br>BODY MESSAGE</strong>');
// Use the Web API to send your message
$sendgrid->send($mail);
?>
I tried to put test.jpg file on the same folder with this php file. Also tried to add like gs://bucket_name/test.jpg but not working. Any ideas. Thanks in advance
Solved with using web api v2 Curl version like this
$fileName = 'filename.pdf';
$image_data = file_get_contents('gs://my-bucket/filename.pdf');
sending part
$params = array(
'api_user' => $user,
'api_key' => $pass,
'x-smtpapi' => json_encode($json_string),
'to' => 'email#yourdomain.com',
'subject' => 'your subject',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'yourmail#yourdomain.com',
'files['.$fileName.']' => $image_data
);
$request = $url.'api/mail.send.json';

how to rander .html file using cakephp : CakePHP

I am working on CakePHP and I have a URL http://admin.example.com/Pages .
How can I create http://admin.example.com/Pages.html ? Is there any solution or component to solve this issue?
According to CakeBook , You can define extensions you want to parse in routes
E.g. Write the code below in app/Config/routes.php
Router::parseExtensions('html');
This will allow you to send .html extenstion in routes(url)
Not create a link
E.g:
$this->Html->link('Link title', array(
'controller' => 'pages',
'action' => 'index',
'ext' => 'html'
));
When you click that link you will get url in browser something like this
http://admin.example.com/pages/index.html
Do you really need this? CakePHP is automatically render view files from View folder
You can create (if its PagesController and index methond) index.ctp in app/View/Pages folder and it will be automatically render.
You can use file_get_contents function to read files. Something like this:
// in controller
function index() {
$content = file_get_contents('path/to/file.html');
echo $content;
die();
}

cakephp How to change the X-Mailer

Using cakePHP version 2.3.8,
I am trying to change the X-Mailer: CakePHP Email into X-Mailer: PHP mail.
I have tried this in the controller and in the /app/Config/email.php in my 'default' settings.
'X-Mailer' => 'PHP mail',
But not able to get it changed, really frustrating.
You need to use addHeaders() to change it prior to sending the email.
As done here, for example:
https://github.com/dereuromark/tools/blob/master/Lib/EmailLib.php#L638
In this case - extending the core class - one can use Configure to automatically populate the X-Mailer via configs. But you can also do it inline for each email sending functionality.
Basically, on your CakeEmail object:
$CakeEmail = new CakeEmail();
$CakeEmail->addHeaders(array('X-Mailer' => 'My custom X-Mailer'));
If set manually Cake will not add his default value 'CakePHP Email'.
CakePHP 2,
Instead of setting it every time from a controller as suggested by #mark,
you can set in the EmailConfig class, located in Config/email.php:
public $default = array(
'transport' => '...',
'from' => '...',
'emailFormat' => 'both',
'charset' => 'utf-8',
'headerCharset' => 'utf-8',
'headers'=>array('X-Mailer'=>'Your App Name'),
);
Will send an email with these headers:
To: .....
X-Mailer: Your App Name
Date: ....

Render view to variable in CakePHP 1.3 (to generate pdf and download file)

I'm trying to render a view to a variable.
This variable will then be used to generate a pdf.
Then that pdf should be downloaded with the Media view.
Here's my controller code:
$dir = ROOT . '/app/tmp/evaluationpdf/';
$path = $dir . $evaluationid . '.pdf';
$evaluation = $this->SelfEvaluation->find('first', array(
'conditions' => array('SelfEvaluation.id' => $evaluationid),
'contain' => array('Submission' => array('Application'), 'Applicant', 'Member')));
$this->set(compact('evaluation'));
$this->output = '';
$this->layout = false;
$html = $this->render('/elements/self_evaluation_pdf');
$this->_generate_pdf($html, $path);
$this->view = 'Media';
$params = array(
'id' => $evaluationid . '.pdf',
'name' => $evaluationid,
'download' => true,
'extension' => 'pdf',
'path' => $dir,
);
$this->set($params);
The file is created as it should, but the first '$this->render' output is also sent to the browser.
The file is never downloaded.
Any idea on how to fix this?
The simple fix is to just set $this->output to '' after your first render() call.
The more correct way is to use requestAction() instead of render().
In CakePHP 2.x I did the following in order to use a view to generate a barcode label format:
$response = $this->render('/Labels/' . $printer['Printer']['model'] . '/manifest', 'ajax');
$body = $response->body();
$response->body('');
Which gave me the view data as $body. Then I could just redirect or if the request was ajax just set autoRender to false and return ''.
It kind of muddies the MVC waters but it is simple.
You just have to write the code below in self_evaluation_pdf.ctp
header("Content-Disposition: attachment; filename='downloaded.pdf'");
header('Content-type: application/pdf');
The dynamic content in this view will be downloaded as a PDF file on the client side.

How to check session when downloading uploaded file in cakephp?

I have created a feature to upload and download file in my site. But I want to validate the download feature. I want to allow a user to download file if user is already logged in to my site and given permission to download.
Help me. How to check whether session is present there or not?
I am uploading files in /app/webroot/documents/users/ path.
Download link generated is like this : http://localhost/my_project/documents/users/TGlnaHRob3VzZS5qcGcxMjc3ODIzMTAx.jpg
Thank you all.
The easiest way to deal with this is to use the AuthComponent for your authentication and the MediaView for handling the download prompt from a "download this file" link on the page.
An Example.
class SomeController extends AppController {
...
public $components = array(
'Auth' => array(
... auth settings ...
),
...
);
public function download( ){
$this->view = 'Media';
$this->set( array(
'id' => 'TGlnaHRob3VzZS5qcGcxMjc3ODIzMTAx.jpg',
'name' => 'TGlnaHRob3VzZS5qcGcxMjc3ODIzMTAx',
'download' => true,
'extension' => 'jpg',
'path' => join( DS, array(
APP, 'webroot', 'documents', 'users', ''
))
));
}
This assumes you have the download action as a restricted action with regards to the AuthComponent. If you have the download action allowed you can wrap the MediaView code in an Auth->user( ) check like so..
public function download( ){
if( $this->Auth->user( )){
$this->view = 'Media';
$this->set( array(
'id' => 'TGlnaHRob3VzZS5qcGcxMjc3ODIzMTAx.jpg',
'name' => 'TGlnaHRob3VzZS5qcGcxMjc3ODIzMTAx',
'download' => true,
'extension' => 'jpg',
'path' => join( DS, array(
APP, 'webroot', 'documents', 'users', ''
))
));
} else {
... do something else here ...
}
}
This just checks that Auth has a valid User object saved to the session. This should only occur when there is a User logged in.
A couple of notes:
I use a blank array entry at the end of the join( DS, array( 'path', 'parts', '' ) call to get the trailing slash required for the path. Do that however you want - I am partial to join myself when building repetitive strings or paths.
http://book.cakephp.org/view/489/Media-Views
http://book.cakephp.org/view/563/Setting-Auth-Component-Variables
I would probably set something up so you're not giving them a direct download link. I usually set up an AttachmentsController, with a download() method. Then you can run all the permissions checks you want (and keep stats on the files, etc.)
In that case you can have your controller check the session variable before enabling the download.
If you're using the Session component, you can check the user's status in your users action using something like this:
if($this->Session->read('Auth.User.id'))
{
//download file
}
How you serve your files is up to you though, but that session check should work inside whatever you use to serve the file, such as Travis Leleu's AttachmentsController.

Resources