Is anybody else using David Persson's media plugin for CakePHP? I'm struggling with setting up some features of the latest version. I'd like to set it up to make a UUID-based filename for uploaded images, but I'm not sure how to go about it.
I will fight with it some more, but I'm posting to find out if anybody here can tell me if the 1.3 is generally working or generally NOT working.
Finally got this (partially) working. The UUID filename stuff works when I place the following code in my Attachment model:
function transferTo($via, $from) {
extract($from);
$irregular = array(
'image' => 'img',
'text' => 'txt'
);
$name = Mime_Type::guessName($mimeType ? $mimeType : $file);
if (isset($irregular[$name])) {
$short = $irregular[$name];
} else {
$short = substr($name, 0, 3);
}
$path = $short . DS;
$path .= String::uuid();
$path .= !empty($extension) ? '.' . strtolower($extension) : null;
return $path;
}
I'm still having some trouble with other parts of the Media Helper, but the author posted some updates to his git repository today (Jul 17 2010).
Related
Currently have working on an image upload in a Laravel/Inertia/React stack.
Issue: It currently works using a symbolic link to the public folder. This is no good as it means anyone can access the images if they have the link. How can I do this differently so that only the owner of the image can view it?
Displaying the image:
<img src={`/storage/${props.company.logo_filename}`}/>
Storing the logo:
public function storeLogo(Request $request)
{
$company = auth()->user()->company();
$logo = $request->file('logo');
$extension = $logo->getClientOriginalExtension();
Storage::disk('public')->put($logo->getFilename() . '.' . $extension, File::get($logo));
dd(Storage::url('public/'. $logo->getFilename()));
$company->logo_mime = $logo->getClientMimeType();
$company->logo_original_filename = $logo->getClientOriginalName();
$company->logo_filename = $logo->getFilename() . '.' . $extension;
$company->save();
//DELETE old Logo if exists
return Redirect::back()->with(
'message',
[
'type' => 'success',
'text' => 'Logo Updated'
]
);
}
note: In this particular scenario (company logos) I'm aware that it probably doesn't matter if someone else gets access to the images. Please just assume they are sensitive.
You could add a route to serve the files and check if the current user is allowed to access the file.
use Illuminate\Support\Facades\Storage;
Route::get('files/{filename}', function (string $filename) {
// Do your magic to check if the current user is allowed to access that file
// Do your magic to determine the full path of the file
$fullPath = '/some/directory/' . $filename;
// Once we have the full path we can stream the contents of the file to the client
return Storage::response($fullPath);
});
Unfortunately the Storage::response() method is undocumented as far as I know, but you can find it's implementation here:
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Filesystem/FilesystemAdapter.php
I need to attach a recent file to an email. The attachment is there, but it is 0 bytes. The path is correct
I have the following code, in part:
$file = WWW_ROOT . $handle->file_dst_pathname;
/* $file = /var/www/app/webroot/files/uploads/children/0000000220.pdf which is correct */
$attachment_name = 'Progress Note for ' . $parent['Child']['child_name'] . '-' . date('mdY') . '.' . $data['extension'];
$Email->attachments(array($attachment_name => $file));
I am using Cakephp 2.4.9
Any help is appreciated.
Greg
according to the docs
$Email->attachments(array(
$attachment_name => array(
'file' => '$file'
)
));
It probably depends on the version of CakePHP you are using (2.x) and probably a version of PHP. I was struggling with the 0 bytes attachments as well. I had to dig in the vendor email file. Basically it turned out, that the _readFile() fn was messing things up with CakePHP File Reader.
So what worked for me was to specify the filename, specify the full path and attach the data of the file in base64. Then everything worked. All other options from documentation didnt work. I was running PHP 5.4.45 (old one).
'filename' = array(
'file' => '/full/path/to/the/file/on/disc.pdf',
'data' => chunk_split(base64_encode(file_get_contents('/full/path/to/the/file/on/disc.pdf')))
);
I am in a problem with CakePDF. I am using CakePHP 2.3.6. I setup everything alright, bootstrap & core files are ok.
Now, I want to generate many pdf files and download them. Downloading is ok, but when I download the files, I see that the generated pdf files say that Undefined $data, where I send $data to the view file.
Here is my Controller code:
App::uses('CakePdf', 'CakePdf.pdf');
// ...
public function createPdf($id) {
$data = $this->DBTable->find('all', array(
'conditions' => array(
'DBTable.id' => $id
)
));
$CakePdf = new CakePdf();
$path = APP . DS . 'pdf' . DS;
foreach($data as $key => $var) {
$CakePdf->template('create', 'default');
$this->set('var', $var);
$this->pdfConfig = array(
'orientation' => 'portrait',
'filename' => $var['id'] . ".pdf"
);
$CakePdf->write($path . $var['id'] . ".pdf");
}
}
Here, I am downloading the files some other way, not related to this problem, because downloading is ok. When I run this, all files are downloaded, and when I see the files, they say "Udefined var", looks like they didn't receive and variable called "$var".
I put the view file & the layout exactly where ceeram said.
What should I do now ? Please help me.
At last I got a solution to this. In the Controller function :
$data=$this->ModelName->find('all');
$CakePdf=new CakePdf();
$CakePdf->template('view_file','default');
$this->pdfConfig=array('orientation'=>'portrait','filename'=>$data['name']);
$CakePdf->viewVars(array('data'=>$data));
$CakePdf->write($path.$data['name'].".pdf");
Here, we have to store view_file.ctp in View/Pdf/, and default in View/Layouts/pdf/, where view_file.ctp is the view file which we want to convert in pdf, and default is the layout for this specific view file.
Here, viewVars() function passes the data to the view file, just like :
$this->set->('data',$data);
Let me know if anything is not clear here.
Thanks.
I'm new to cakephp and I have found this milesjohnson's upload plugin ,
and I kind of like it, mostly because it gives me the chance of renaming the file once uploaded.Unfortunately, I can't get it to upload any zip/rar files.
This is the action where I upload the file:
function add() {
if (!empty($this->data)) {
if ($data = $this->Uploader->upload('link_referencia', array('name' => date("dmYhis")))) {
debug($data);
$this->data['Publicacione']['link_referencia']=$data['name'];
}
$this->Publicacione->create();
if ($this->Publicacione->save($this->data)) {
$this->Session->setFlash(__('The publicacione has been saved', true));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The publicacione could not be saved. Please, try again.', true));
}
}
$users = $this->Publicacione->User->find('list');
$this->set(compact('users'));
}
And this is the error I get everytime I attempt to upload any zip/rar file :
EDIT
Full insert query:
INSERT INTO `publicaciones` (`vigencia`, `tipo`, `titulo`, `descripcion`, `fecha_publicacion`, `fecha_caducidad`, `link_referencia`, `modified`, `created`) VALUES (1, 'c', 'there\'s nothing you can\'t do', '
fsdfsdfsdf
', '2011-06-07', '2011-06-30', Array, '2011-06-07 16:47:23', '2011-06-07 16:47:23')
Does anyone have any ideas on what the problem might be?
Thanks in advance.
i think there is nothing with the code what you have written but you should look at in to the plugin and find out whether it gives permission you to upload zip or not.
there will be conditions in your pluggin that you can upload only some kind of files like jpg,png,txt something like that.
I hope that helps you.
Regards,
Archit
Are you totally sure your File input on the form has type=>file specified, and same for your form?
Also I would look at other uploaders - MeioUpload can allow renaming and so on and is a bit more up to date. There is also the Cuploadify plugin (uploadify for cake) you can find on github.
Make sure your form is set to multipart/form-data like so:
<?php echo $this->Form->create('File', array('enctype' => 'multipart/form-data')); ?>
The following code will upload a file:
if ($this->request->is('post')) {
if ( $this->data['File']['file']['error'] <= 0 && $this->data['File']['file']['size'] <= 8388608 ) { // Check for no errors and that File size is around 8mb.
$folder = new Folder (ROOT . DS . 'app' . DS . 'filestorage' . DS, true); // create folder in /app/filestorage/
$path = $folder->path . $this->data['File']['file']['name']; // Set path to newly created folder + uploaded file name.
$tmpUrl = new File ( $this->data['File']['file']['tmp_name'] ); // Create temporary file object
if ($tmpUrl->copy($path , true) ) { // If copying file to path is successful,
$this->Session->setFlash(__('File uploaded succesfully!'));
}
}
my url is http://localhost/myAppliation/....
I want to get the "myApplication". Which is the key word to get the value?
I think you want:
$this->webroot
or
$this->base
or
$this->here
in your controller. See http://api.cakephp.org/class/controller for definition of this variables.
Edit: Didn't see that you were using CakePHP. If you weren't using any frameworks, you would get the path via this:
First you need to reconstruct the URL.
$pageURL = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
Then parse it for the path.
$parts = parse_url($pageURL);
$path = $parts['path'];
After that if you want to only get the first path, explode it on '/', strip out the null values, and then the first one will be the first path, and so on.
$paths = explode('/', $path);
foreach($paths as $key => $value)
{
if(!empty($value))
{
$new_paths[] = $value;
}
}
$first_path = $new_paths[0];
There is something called the $Name attribute, but I'm not sure if that gives you the application name. The CakePHP manual says:
PHP4 users should start out their
controller definitions using the $name
attribute. The $name attribute should
be set to the name of the controller.
Usually this is just the plural form
of the primary model the controller
uses. This takes care of some PHP4
classname oddities and helps CakePHP
resolve naming.
http://book.cakephp.org/view/52/name
http://book.cakephp.org/view/317/Cake-s-Global-Constants-And-Functions
I think you want to use the WEBROOT_DIR constant.