Cakephp response (sending files) breaks when model functions are added - image

I have baked a File model and controller with default actions. Now I am trying to add an display function which can be used to show images in controlled manner.
I want to protect images so that display function can check does the user have an permissions to view image (image directory is not in a webroot).
I haven't been able to make it work, but when I started from the scratch I managed to find out that really minimal function did work.
Working function looks like this:
public function display($id) {
$this->response->file(ROOT.DS.'img'.DS.'noimage.jpg');
return $this->response;
}
When I add example:
$test=$this->File->findById($id);
to the starting of the function everything breaks.
--> http://www.example.com/files/display/1
The requested file /var/www/example.com/www/img/image.jpg was not found or not readable
Error: The requested address '/files/display/1' was not found on this server.
I have tried with debug zero, file can be found and is readable, obviously because the function without findById works.
Any ideas?
cakephp 2.4.3

You path is totally wrong.
Did you debug() what ROOT.DS.'img'.DS.'noimage.jpg' actually holds?
I bet all the money of the world that you would probably find the solution yourself if you did
The img folder is most likely in webroot
WWW_ROOT . 'img' . DS . 'noimage.jpg'
Note that paths usually end with a DS so no need to add it again.
So if it really is an image folder in ROOT:
ROOT . 'img' . DS . 'noimage.jpg'
Also note that you can easily check if a path is valid using
file_exists()
If the file has the correct file permissions this should return true.
EDIT:
$this->File->...: File is not a good choice for a model name as it collides with the existing core class in Utility. You need to be a little bit more creative with your model naming scheme.

Related

Get correct URL for uploaded files

I have a function in my platform for letting users upload their own icon images. Once they've uploaded them I save them using $request->icon->store('public/icons') and simply save the returned path, something like "public/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png".
I'm not really clear though on what's the correct way to show the icons. The URL for showing the icon in the above example is "/storage/icons/xa6y2am3e4cOdqQuLpvEhFSXDKwFMDOgggS2i67l.png", thus I need to replace "public" in the path with "storage", which makes me think I've done something wrong somewhere (I see no reason why the store() method should provide me with a path that's not correct).
I have done my symlinks as described in the documentation. Using the local storage. What am I missing?
This is how I handle my storage in one of my apps that includes blogs:
$storedImageName = $request->file('main_image')->store('blog_images', 'public');
The store method actually returns the stored file name along with the path. Here, I specify that my disk is public and that the folder inside public is blog_images. I store the result of that in $storedImageName.
Now, to save it in the database, I do not actually save the whole path, I save ONLY the image name. This is because, you may want to update your directory name in the future, or move it to another location, etc. You can get that like this:
$onlyImageName = basename($storedImageName);
basename() is PHP's function, has nothing to do with Laravel.
This way, I can render my images in my blade files like this:
<img ... src="{{ asset('/storage/blog_images/' . $blog->main_image) }}" />
asset() helper will provide you with path to your public directory, and then you just need to specify the rest of the path to your image.

Laravel: display file from cloud storage in the browser

This snippet from the Laravel docs, https://laravel.com/docs/5.5/responses#file-responses, seems to be just what I need:
return response()->file($pathToFile);
The problem is that my file is stored on an S3 disk, and I can't seem to reference it properly.
I tried using Storage::disk('s3')->getDriver()->getAdapter()->applyPathPrefix($myPath); to get the fully qualified file name. It just returned the value of $myPath though.
I then tried to get the url using Storage::disk('s3')->url($myPath); The URL looks fine however Symphony says it does not exist. When I check with Storage::disk('s3')->exists($myPath); however, it returns true.
How do I go about displaying a file from cloud storage directly in the user's browser?
EDIT:
More details below:
To save the item in the first instance I am using $map->storeAs('/my/path/maps/filename.pdf', ['disk' => 's3']);
The output of url() is "https://s3.ap-southeast-2.amazonaws.com/my.domain.com/my/path/maps/filename.pdf"
When I cut-and-past the url in a browser address bar, it loads no problem
It seems to me that the response()->file() method does not accept a URL parameter. Is that the case?
Question - does the file need to be publicly available? (It currently is, but I would prefer to make it private).
The following should be enough:
$path = Storage::disk('s3')->url($filename);
I don't have a working example set up, but from memory $filename should be the same as what you originally placed in the ->put() method. So when you say $mypath in your question, hopefully that isn't already prefixing stuff like your s3 instance.
If this isn't the case, can you edit the question to include the result of ->url() and an example of your put() call and $path.
Looking at the edit, I think I understand what you are trying to do, which has been solved here:
https://laracasts.com/discuss/channels/laravel/file-response-from-s3

When Migrated Catalyst Website Leaves Module Code

A client wants to move a website they made using Adobe Catalyst to a different hosting provider. I was able to copy the entire website via FTP and move it to the new host. Everything looks fine except for many of the links leaving code that looks like this:
{module_contentholder, name="_U309"} {module_contentholder, name="_U299"}
Does anyone know what this is or how to fix it?
Those are references to Content Holders. They work similarly to PHP's include statement, but the file they reference is fixed to a single path: /_System/ContentHolders/.
You will likely come across more tags like that, such as {module_menu} and {tag_pagecontent}. You'll need to manually adapt them to the whatever the new host uses. The documentation will help: http://docs.businesscatalyst.com/reference/
The obtuse names of the content holders shown in your example indicates the site was likely to have been generated by Adobe Muse, a WYSIWYG editor. I strongly recommend that you find the original .muse project files, and use those to update the site. Muse can compile the site for platforms other than Business Catalyst.
Through research I found out there is no way to get those codes to display properly without editing each page individually. Fortunately, I wrote a PHP script that goes through the code of each page and replaces it automatically.
Step 1: Make a file in the index directory called replacement.php
Step 2: Put this code in
$file = $_GET['file'];
$path = '/path/to/public_html/' . $file;
$file_contents = file_get_contents($path);
preg_match_all("/{module(.*?)}/", $file_contents, $matches);
foreach($matches[0] as $match) {
if(preg_match('/\"([^\"]*?)\"/', $match, $query)) {
$queryNew = str_replace("\"", "", $query[0]);
$queryPath = '/path/to/public_html/_System/ContentHolders/' . strtolower($queryNew) . '.html';
$queryContents = file_get_contents($queryPath);
$file_contents = str_replace($match, $queryContents, $file_contents);
}
}
file_put_contents($path, $file_contents);
Step 3: Replace where it says /path/to/public_html/ to your domain files location.
Step 4: go to http://www.yourdomain.com/replacement.php?file=index.html to change over the index file. You can change "index.html" in the url to any other page you want converted.
Hopefully this helps someone else in the future.

Where do I find the contents of $this->getAbsoluteFooter() Magento

I'm struggling to find what this calls '$this->getAbsoluteFooter()' or where it's contents are.
Is it a template file?
The reason I ask is because my site was hacked with a js injection in the footer. Disabling $this->getAbsoluteFooter() removed the injection so I'm anxious to find the source.
I've Googled it and the only thing I can find is someone asking the same question.
Thanks.
You've been hacked which means this could be anywhere, so keep that in mind when this doesn't work for you.
The getAbsoluteFooter method is normally defined in the following file.
#File: app/code/core/Mage/Page/Block/Html.php
public function getAbsoluteFooter()
{
return Mage::getStoreConfig('design/footer/absolute_footer');
}
In a normal system, the getStoreConfig method will return the value stored in core_config_data for the passed in path (design/footer/absolute_footer).
Of course, since you're hacked, the actual class file $this refers to in your template could be anywhere on the server (depending on the severity of your hack). Give the following a try to find the real file on your specific system
//$this->getAbsoluteFooter();
$r = new ReflectionClass($this);
var_dump($r->getFilename());
That should reveal the actual filename, which may be app/code/core/Mage/Page/Block/Html.php, or may be something else.
Good luck!
I found out that a code was injected in the database on the core_config_data table with path 'design/footer/absolute_footer';
More on https://magento.stackexchange.com/a/42529/57576
Ty

prevent duplicate value using ajax in sugar crm

i have create module using module builder , now i am having a field called as book Name
now if i give same book name 2 time t is accepting .
i don't want to use and plug in for checking duplicate value because i want to learn the customization through code .
so i can call ajax and check in data base weather the same book name is exist in db or not but i don't know how controller works in sugar crm . and how to call ajax in sugar crm .
can any one guide me , your help is much appreciated .
If you really want to accomplish this using ajax then I'd recommend an entryPoint as the way to go. This customization will require a couple of simple things. First you'll write a little bit of javascript to perform the actual ajax call. That ajax call will post to the entryPoint you write. The entryPoint will run the query for you and return a response to you in the edit view. So lets get started by writing the entryPoint first.
First, open the file custom/include/MVC/Controller/entry_point_registry.php. If the folder structure and file do not exist yet, go ahead and create them.
Add the following code to the entry_point_registry.php file:
$entry_point_registry['test'] = array('file' => 'custom/test.php', 'auth' => true);
Some quick explanation about that line:
The index value of test can be changed to whatever you like. Perhaps 'unique_book_value' makes more sense in your case. You'll see how this value is used in a minute.
The file value in the array points to where you're gonna put your actual code. You should also give this a more meaningful name. It does NOT need to match the array key mentioned above.
The 'auth' => true part determines whether or not the browser needs to have an active logged in session with SugarCRM or not. In this case (and almost all) I'd suggest keeping this to true.
Now lets look at the code that will go in custom/test.php (or in your case unique_book_name.php):
/* disclaimer: we are not gonna get all crazy with using PDO and parameterized queries at this point,
but be aware that there is potential for sql injection here. The auth => true will help
mitigate that somewhat, but you're never supposed to trust any input, blah blah blah. */
global $db; // load the global sugarcrm database object for your query
$book_name = urldecode($_REQUEST['book_name']); // we are gonna start with $_REQUEST to make this easier to test, but consider changing to $_POST when confirmed working as expected
$book_id = urldecode($_REQUEST['book_id']); // need to make sure this still works as expected when editing an existing record
// the $db->quote is an alias for mysql_real_escape_string() It still does not protect you completely from sql injection, but is better than not using it...
$sql = "SELECT id FROM book_module_table_name WHERE deleted = 0 AND name = '".$db->quote($book_name)."' AND id <> '".$db->quote($book_id)."'";
$res = $db->query($sql);
if ($db->getRowCount($res) > 0) {
echo 'exists';
}
else {
echo 'unique';
}
A note about using direct database queries: There are api methods you can use to accomplish this. (hint: $bean->retrieve_by_string_fields() - check out this article if you wanna go that route: http://developer.sugarcrm.com/2012/03/23/howto-using-the-bean-instead-of-sql-all-the-time/) However, I find the api to be rather slow and ajax should be as fast as possible. If a client asked me to provide this functionality there's a 99% chance I'd use a direct db query. Might use PDO and parameterized query if I'm feeling fancy that day, but it's your call.
Using the above code you should be able to navigate to https://crm.yourdomain.com/index.php?entryPoint=test and run the code we just wrote.
However at this point all you're gonna get is a white screen. If you modify the url to include the entryPoint part and it loads your home page or does NOT go to a white screen there are 3 potential causes:
You put something different for $entry_point_registry['test']. If so change the url to read index.php?entryPoint=whatever_you_put_as_the_array_key
You have sugar in a folder or something on your domain so instead of crm.yourdomain.com it is located somewhere ugly and stupid like yourdomain.com/sugarcrm/ if this is the case just make sure that your are modifying the url such that the actual domain portion is preserved. Okay I'll spell it out for you... https://yourdomain.com/sugarcrm/index.php?entryPoint=test
This is more rare, but for some reason that I cannot figure out apache sometimes needs to be reloaded when adding a new entrypoint. If you have shell access a quick /etc/init.d/apache2 reload should do the trick. If you don't have shell access you may need to open a ticket with your hosting provider (or get a fricking vps where you have some control!!!, c'mon man!)
Still not working? Did you notice the "s" in https? Try http instead and buy a fricking $9 ssl cert, geez man!
Okay moving on. Let's test out the entryPoint a bit. Add a record to the book module. Let's add the book "War of Art" (no, not Art of War, although you should give that a read too).
Now in the url add this: index.php?entryPoint=test&book_name=Art%20of%20War
Oh gawd that url encoding is hideous right! Don't worry about it.
You should hopefully get an ugly white screen with the text "exists". If you do let's make sure it also works the other way. Add a 2 to the book name in the url and hopefully it will now say "unique".
Quick note: if you're using Sugar you're probably also using mysql which is case insensitive when searching on strings. If you really need case sensitivity check out this SO article:
How can I make SQL case sensitive string comparison on MySQL?
Okay so now we have our entryPoint working and we can move on to the fun part of making everything all ajaxical. There are a couple ways to go about this, but rather than going the most basic route I'm gonna show you what I've found to be the most reliable route.
You probably will need to create the following file: custom/modules/CUSTOM_BOOK_MODULE/views/view.edit.php (I hope by now I don't need to point out changing that path to use your module name...
Assuming this file did not exist and we are starting from scratch here is what it will need to look like:
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class CUSTOM_BOOK_MODULEViewEdit extends ViewEdit
{
public function display()
{
// make sure it works in the subpanel too
$this->useForSubpanel = true;
// make the name value available in the tpl file
$this->ss->assign('name_value', $this->bean->name);
// load the parsed contents of the tpl into this var
$name_input_code = $this->ss->fetch('custom/modules/CUSTOM_BOOK_MODULE/tpls/unique_book_checker.tpl.js');
// pass the parsed contents down into the editviewdefs
$this->ss->assign('custom_name_code', $name_input_code);
// definitely need to call the parent method
parent::display();
}
}
Things are looking good. Now we gotta write the code in this file: custom/modules/CUSTOM_BOOK_MODULE/tpls/unique_book_checker.tpl.js
First a couple of assumptions:
We're going to expect that this is Sugar 6.5+ and jquery is already available. If you're on an earlier version you'll need to manually include jquery.
We're going to put the event listener on the name field. If the book name value that you want to check is actually a different field name then simply adjust that in the javascript below.
Here is the code for custom/modules/CUSTOM_BOOK_MODULE/unique_book_checker.tpl.js:
<input type="text" name="name" id="name" maxlength="255" value="{$name_value}" />
<span id="book_unique_result"></span>
{literal}
<script type="text/javascript">
$(document).ready(function() {
$('#name').blur(function(){
$('#book_unique_result').html('<strong> checking name...</strong>');
$.post('index.php?entryPoint=test', {book_name: $('#name').val(), book_id: $('[name="record"]').val()}, function(data){
if (data == 'exists') {
removeFromValidate('EditView', 'name');
addToValidate('EditView', 'name', 'float', true, 'Book Name Must be Unique.');
$('#book_unique_result').html('<strong style="color:red;"> ✗</strong>');
}
else if (data == 'unique') {
removeFromValidate('EditView', 'name');
addToValidate('EditView', 'name', '', true, 'Name Required');
$('#book_unique_result').html('<strong style="color:green;"> ✓</strong>');
}
else {
// uh oh! maybe you have php display errors on?
}
});
});
});
</script>
{/literal}
Another Note: When the code detects that the name already exists we get a little hacky and use Sugar's built in validation stuff to prevent the record from saving. Basically, we are saying that if the name already exists then the name value MUST be a float. I figured this is pretty unlikely and will do the trick. However if you have a book named 3.14 or something like that and you try to create a duplicate this code will NOT prevent the save. It will tell you that a duplicate was found, but it will not prevent the save.
Phew! Okay last two steps and they are easy.
First, open the file: custom/modules/CUSTOM_BOOK_MODULE/metadata/editviewdefs.php.
Next, find the section that provides the metadata for the name field and add this customCode attribute so that it looks like this:
array (
'name' => 'name',
'customCode' => '{$custom_name_code}',
),
Finally, you'll need to do a quick repair and rebuild for the metadata changes to take effect. Go to Admin > Repair > Quick Repair & Rebuild.
Boom! You should be good to go!

Resources