Download function not working CakePHP - cakephp

I read the documentation regarding file downloads, however I can't seem to get this to work.
I have read through questions here as well, and have had no luck.
My function looks as follows:
public function generate($id) {
$this->layout = 'ajax';
$this->Magazine->recursive = 2;
$DistributionLists = $this->Magazine->DistributionList->find('all',
array(
'conditions' => array(
'Magazine.id' => $id
),
'order' => array(
'DistributionList.priority ASC'
)
)
);
$this->set('magazine',$DistributionLists[0]['Magazine']['magazine_name']);
$this->set(compact('DistributionLists'));
}
public function download() {
$this->viewClass = 'Media';
$params = array(
'id' => "Magazine Distribution List.doc",
'name' => "Magazine Distribution List",
'download' => true,
'extension' => 'doc',
'path' => APP . "tmp" . DS
);
$this->set($params);
unlink(APP."tmp".DS);
$this->redirect(array('action'=>'index'));
}
public function afterFilter() {
parent::afterFilter();
if($this->action == 'generate') {
$this->redirect(array('action'=>'download'));
}
}
The reason I have an afterFilter function is because the word document that needs to be downloaded is created in the view file.
Does anyone know why this doesn't work?

You have to remove the call to the redirect method in your download method because it prevents your view from getting "rendered" due to the redirect.

Related

How do I set up an adapter in zend framework 2?

this is the content of the autoload/global.php file :
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=web_builder;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
this is the content of the autoload/local.php file:
return array(
'db' => array(
'username' => 'DB_User_Name',
'password' => 'DB_Password',
,
); )
this is part of the content of module/Module.php :
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\Adapter\Adapter;
.........
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Controller\UserController' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new Model\StickyNotesTable($dbAdapter);
return $table;
},
),
);
}
Here I really don't understand what this function do, I just copy pasted from an example. If you could explain me what does getServiceConfig function do, I will really appreaciate it.
Finally the controller content:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
class UserController extends AbstractActionController{
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
}
public function loginAction(){
// here i just want to a simple select and yes I know queries will be executed
//in Model, but I want to here a simple query.
//For example in Codeigniter I can't do in model, controller, or view as well.
return new ViewModel();
}
The result of all this code is obviously an error:
Catchable fatal error: Argument 1 passed to Application\Controller\UserController::__construct() must be an instance of Zend\Db\Adapter\Adapter, none given, called in C:\xampp\htdocs\zf2\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170 and defined in C:\xampp\htdocs\zf2\module\Application\src\Application\Controller\UserController.php on line 21
Can someone post an answer to make this database or query stuff work ? thx

Better approach to do this for security and code management purpose

I am working on a Cakephp 2.3 on a very big project and I'm about to launch my site worldwide.
I have a login system on my app. I am sharing my code because I want to make sure if I am coding right or not ... and also any check for any functions missing or if any advice of adding something or removing something in the code would be greatly appreciated. And also comment in security perspective too...
Do tell me some tips of making my website faster.. for example how to write faster queries or remove unwanted from this blabla
class UsersController extends AppController
{
public $components = array('Cookie');
public function beforeFilter()
{
parent::beforeFilter();
App::uses('Utility', 'Utility');
$this->Auth->allow('index');
$this->Security->requireSecure('login'); // for security
$this->Auth->authenticate = array(
'Authenticate.Cookie' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'userModel' => 'User',
'scope' => array(
'User.active' => 1
)
),
'Authenticate.MultiColumn' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'columns' => array(
'email',
'mobileNo'
),
'userModel' => 'User'
)
);
}
public function index()
{
$this->layout = 'logindefault';
if (!$this->Auth->login() || !$this->Auth->loggedIn()) {
$this->redirect(array(
'controller' => 'users',
'action' => 'login'
));
} else {
$this->redirect(array(
'controller' => 'users',
'action' => 'dashboard'
));
}
}
public function login()
{
$this->layout = 'logindefault';
$this->set('title_for_layout', 'Account Login');
if ($this->Auth->login() || $this->Auth->loggedIn()) {
$lastLogin = $this->Auth->User('lastLogin');
if ($lastLogin != null) {
$this->redirect($this->Auth->redirect());
} else {
$this->redirect(array(
'controller' => 'Userinfo',
'action' => 'gettingstarted'
));
}
} else {
if ($this->request->is('post')) {
$mobileNo = $this->request->data['User']['email'];
$mobileNo = Utility::addPlusToMobileNo($mobileNo);
$this->request->data['User']['email'] = $mobileNo;
if ($this->Auth->login() || $this->Auth->loggedIn()) {
if ($this->Session->check('Auth.User')) {
$this->_setCookie($this->Auth->user('idUser'));
$lastLogin = $this->Auth->User('lastLogin');
if ($lastLogin != null) {
$this->redirect(array(
'controller' => 'users',
'action' => 'dashboard'
));
} else {
$this->redirect(array(
'controller' => 'Userinfo',
'action' => 'gettingstarted'
));
}
}
} else {
$this->Session->setFlash('Incorrect Email/Password Combination');
}
}
}
}
protected function _setCookie($id)
{
if (!$this->request->data('User.remember_me')) {
return false;
}
$data = array(
'username' => $this->request->data('User.email'),
'password' => $this->request->data('User.password')
);
$this->Cookie->write('User', $data, true, '1 week');
return true;
}
public function logout()
{
$this->Cookie->delete('User');
$this->redirect($this->Auth->logout());
}
Looks like you're already using the SecurityComponent if you want to secure your app use it everywhere. For AJAX forms white list only the fields you need, dont disable the component!
Put App::uses('Utility', 'Utility'); on top of the file
$mobileNo = Utility::addPlusToMobileNo($mobileNo); should happen in the model beforeSave()
If this is supposed to be used world wide I assume you want translations, this is missing the translation method call __() setFlash('Incorrect Email/Password Combination');
Most of the code CAN and should go into the model layer
Are there unit tests? If not add unit tests, specially test validation of data and false data input. You want ~85%+ Code Coverage for unit tests.
You're not following the CakePHP coding standards
There is no way to tell you more than this without being able to access the whole app code and doing a code review (I could do that). For queries, always just query the data you need, check the generated SQL queries, use DebugKit to check the query times to find slow querys and slowly rendering pages.

cakephp 2.2 Using contain with Auth not working

I have a working example of Auth set up with Users & Groups, based on the cookbook tutorial. I have an additional Locations table, which is associated with my Groups.
Location hasMany Group. Group belongsTo Locations. In 2.2 I think I should be able to get location data back for a User, but am not able to.
// App controller
public function beforeFilter() {
$this->Auth->authenticate = array(
'all' => array (
'scope' => array('User.status' => 1)
),
'Form' => array(
'contain' => array('Group', 'Location'),
'fields' => array('Location.name')
)
);
The above code only works if I create a direct association between User and Location. Is it possible to use contain here with a Group to Location association?
Problem of BaseAuthenticate is how it returns user info: return $result[$model];.
So when I need contains I'm using alternative component placed in app/Controller/Auth:
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class FormAndContainableAuthenticate extends FormAuthenticate {
protected function _findUser($username, $password) {
if (empty($this->settings['contain'])) { //< deafult
$userData = parent::_findUser($username, $password);
} else { //< with contains
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array(
$model . '.' . $fields['username'] => $username,
$model . '.' . $fields['password'] => $this->_password($password),
);
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$modelObj = ClassRegistry::init($userModel);
$modelObj->contain($this->settings['contain']);
$result = $modelObj->find('first', array(
'conditions' => $conditions
));
if (empty($result) || empty($result[$model])) {
return false;
}
foreach($result as $modelName => $modelData) {
if ($modelName !== $model) {
$result[$model][$modelName] = $modelData;
}
}
$userData = $result[$model];
}
// remove dangerous fields like password
unset($userData[$this->settings['fields']['password']]);
if (!empty($this->settings['exclude'])) {
foreach ($this->settings['exclude'] as $fieldName) {
unset($userData[$fieldName]);
}
}
return $userData;
}
}
As you can see - it uses parent Component when no contains provided.
Also some bonus: you can provide a set of fields to remove from resulting array. Just pass field names via 'exclude' key
How to use Component:
public $components = array(
'Auth' => array(
'authenticate' => array(
'FormAndContainable' => array(
'fields' => array(
'username' => 'username',
'password' => 'password',
),
'userModel' => 'Staff',
'contain' => array('StaffPermission'),
'exclude' => array('plain_password')
)
),
),
);
If User is not linked to Location, but Group is, you should try this:
'contain' => array('Group' => array('Location')),

CakePHP redirect loop

I'm having the weirdest Cake error with my code. When the code below calls the add() method (also reproduced here and from a different controller), the code redirects him back with a 302 found HTTP code to the edit() action (in essence, to the user it appears as if nothing happens). To further complicate matters, when I call the same URL when I'm not on that page (despite the pages not being reliant on each other), I get redirected to the base of my app, which results in a redirect loop. I tried calling other methods from this controller (with their proper arguments) to see if this was just a problem with the add() action, but I get the same redirect loop. I've already checked all over SE but cannot find a relevant answer.
Here is the relevant code:
function edit($id=null) {
if(!$id) {
$this->Session->setFlash('Invalid!');
$this->redirect(array(
'action' => 'index')
);
}
else {
//Get the slides themselves
$slides = $this->Slide->find('all', array('conditions' => array('Slide.module_id' => $id)));
$this->set('slides', $slides);
//Get the data for the Module
$module = $this->Module->find('first',
array(
'conditions' => array (
'Module.id' => $id
),
'fields' => array(
'Module.module_name',
'Module.id')
)
);
}
}
And here is the add() code (again, from a different module):
function add($module = null) {
if ($this->request->is('get')) {
//Set some variables for the view (this code I know works as it has been used successfully elsewhere
}
else { //User is POSTing
$this->Slide->create();
$this->Slide->save($this->data);
}
}
Thanks to everyone in advance; I couldn't do this without your support!
EDIT: Here is the AppController code:
public $components = array(
'Auth' => array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
),
'loginAction' => array(
'controller' => 'users',
'action' => 'login'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
),
'logoutRedirect' => array('/')
),
'Session'
);
public $helpers = array('Html', 'Form', 'Session');
public function isAuthorized() {
return true;
}
public function Controller() {
}
}

CakePHP Pagination. Keeping Model Fat

I currently have this in my Model (Referer Model):
public function getReferers($type = 'today') {
if ($type == 'this_month') {
return $this->_getThisMonthsReferers();
} elseif ($type == 'today') {
return $this->_getTodaysPageReferers();
}
}
private function _getThisMonthsReferers() {
$today = new DateTime();
return $this->Visitor->find('all', array(
'fields' => array(
'Referer.url',
'COUNT(UserRequest.visitor_id) as request_count',
'COUNT(DISTINCT(Visitor.id)) as visitor_count',
'COUNT(UserRequest.visitor_id) / COUNT(DISTINCT(Visitor.id)) as pages_per_visit',
'COUNT(DISTINCT(Visitor.id)) / COUNT(UserRequest.visitor_id) * 100 as percent_new_visit'
),
'joins' => array(
array(
'table' => 'user_requests',
'alias' => 'UserRequest',
'type' => 'RIGHT',
'conditions' => array(
'UserRequest.visitor_id = Visitor.id'
)
)
),
'conditions' => array(
'Visitor.site_id' => $this->Site->id,
'MONTH(UserRequest.created)' => $today->format('m'),
'YEAR(UserRequest.created)' => $today->format('Y')
),
'group' => array(
'url'
)
));
}
The thing is that I how I would paginate this. It will be so easy if just copy my code out of the model and to the controller. The thing is I want the keep the query in my Model.
How is this supposed to be done in CakePHP?
A custom find type is one method. You can find more information here: http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html#custom-query-pagination
To turn your _getThisMonthsReferers into a custom find, follow this http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types
For example:
// model
protected function _findThisMonthsReferers($state, $query, $results = array()) {
if ($state === 'before') {
$query['fields'] = ....
$query['joins'] = ....
return $query;
}
return $results;
}
// controller
public $paginate = array('findType' => 'thisMonthsReferers')
EDIT:
I think it should be :
public $paginate = array('thisMonthsReferers');
However the Solution I used derived from this answer is adding this to the method I am using
$this->paginate = array('thisMonthsReferers');
Since I don't want i used in all my actions. Then paginating the Model like this.
$this->paginate('Visitor);
Instead of returning the results of the find, just return it's array of options:
return array(
'fields' => array(
//...etc
Then use those options to paginate in the controller. More details on this answer of this similar question: Paginate from within a model in CakePHP
It still keeps the model fat (with any logic that might alter the conditions, joins, fields...etc), and the controller skinny, which just uses the returned array as paginate options.

Resources