CakePHP - Router::url() generating url relative to current page - cakephp

I'm trying to replace all of my static routes with the CakePHP 3.8 Router::url() method.
On my local environment, when accessing the the below code from the manage/lender-products/read/2 route, I get the expected results of /manage/lenders from the below code:
\Cake\Routing\Router::url(['controller' => 'Lenders', 'action' => 'index'])
However, on production (bref.sh/AWS Lambda/PHP 7.4), I get the unexpected result of /manage/lender-products/read/manage/lenders.
It appears that in my production environment, the URL is being generated and is including the current pages url in the end result.

In case you do not set a custom base path for the App.base config option, CakePHP will try to figure the possible base path out on its own, based on $_SERVER['PHP_SELF'] and $_SERVER['DOCUMENT_ROOT'], so it's likely that one or both of these contain unexpected values in your AWS environment.
The simple fix would be to manually set the base path in your config/app.php. If your application doesn't actually live in a public subdirectory (ie in case webroot is your document root), then you should set the path to an empty string, otherwise provide the path, like /my/app (with a leading slash, but without a trailing slash!).
See also
Cookbook > Configuration > General Configuration

Related

404 page not found error when passing getMapping( value="/") and requestParameters

Myapp is java springboot microservice deployed in kubernetes. In local it works fine since I do not need proxy and kubernetes.yml, however when I deploy to int environment, I run into "404 page not found" error.
Please advice if there is any other way to call the service endpoint with this path /api/v1/primary-domain/domain-objects?parameter1=645&parameter2=363&parameter3=2023-02-01
Why is it not able to find the resource? Are there any options to make this work still with same naming pattern for path?
application.properties
server.servlet.context-path=/api/v1/primary-domain/domain-objects management.endpoints.web.base-path=/ management.endpoint.health.show-details=always management.endpoints.web.path-mapping.health=health
#API Registry
springdoc.api-docs.path=/doc
controller:
`#GetMapping(value="", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<DomainObjectsMsResponseDTO>> getDomainObjects(
#RequestParam(name = "parameter1", required = false) String parameter1,
#RequestParam(name = "parameter2", required = false) String parameter2,
#RequestParam(name = "parameter3", required = false) String parameter3,
) throws Exception{..}`
The path variable in proxy is /v1/primary-domain/domain-objects
proxy.yml
.
.
spec: path: /v1/primary-domain/domain-objects target: /api/v1/primary-domain/domain-objects
.
.
Due to the architecture direction the path for health, doc and actual service endpoint should follow certain naming convention, hence running this issue.
If I use proxy.yml path variable v1/primary-domain and getMapping( value="/domain-objects"..) then it works fine but the domain-objects/doc endpoint returns sever array with url: api/v1/primary-domain, which is not what I want. Since under primary-domain multiple microservices will be created which will be in their own gitRepos and they will path like /primary-domain/points and /primary-domain/positions
I tried getMapping( value="/"..) and removing value variable entirely from getMapping, but still getting same error
I tried changing the Label variables, path target and paths in kube and proxy and matched the app.proeprties and controller to go with it. However with every approach one thing gets broken. None of the approach satisfies endpoint, health endpoint, doc endpoint( open api)

wagtail 'Page with this Path already exists.' error on attempting to create page manually

I have some code to create a Custom page object as part of a data import:
instance = PerformancePage(
run=run,
date=json_data['date'],
time=json_data['time'],
price=json_data['price'],
title=f'{run.title} {json_data["date"]} {json_data["id"]}',
content_type=ContentType.objects.get_for_model(PerformancePage)
)
perf = run.add_child(instance=instance)
and that sometimes raises:
django.core.exceptions.ValidationError: {'path': ['Page with this Path already exists.']}
A bit of debug code does show that there is another page out there with the same path:
except ValidationError:
print('error attempting to save', instance)
print('path', instance.path)
print('is leaf', run.is_leaf())
rivals = Page.objects.filter(path=instance.path)
print(rivals.last().specific.run == run)
Why might that be?
trying to manually increment the rival path to set a new path doesn't work either:
instance.path = rivals.last().specific._inc_path()
perf = run.add_child(instance=instance)
# still raises
Interestingly, if I just skip over those exceptions and continue my import,
when I print out those paths, they seem to follow a similar pattern:
path 00010001000T0005000D0001
path 00010001000T000800050001
path 00010001000T000900060001
path 00010001000T000A00050001
path 00010001000T000A00050001
path 00010001000T000A00070001
path 00010001000T000A00070001
path 00010001000T000A00030001
could that be relevant?
Looks like the in-memory parent "run" object was out of date. re-fetching it from the database before trying to add the child fixes the problem:
run = RunPage.objects.get(id=run.id)

retrieving an image from the file path in the database in cakephp

I am using the following code
echo $this->Html->image($article['Article']['image']);
to retrieve an image from a path in the database, but instead the browser retrieves the following
<img src="/loopmatic/img/uploads%5CIMG_0567.JPG" alt="">
Can someone help in explaining an alternative method to use, or why i see a percentage sign in the path instead of a forward slash
%5C is the '\' character urlencoded. URL's are not like file systems so you have to turn the \ in a /.
I've written a complete file storage and image processing system that deals with that as well. Check it out here or just grab the method from the helper.
public function normalizePath($path) {
return str_replace('\\', '/', $path);
}

Nginx config for serving snapshots to the Google bot

I have an AngularJS app which I'd like to get indexed properly on Google.
I wrote a client that scrapes the sites for links and then downloads the pages with Phantomjs making snapshots. This all works fine. What I'm having a problem with is serving those snapshots to the Google bot.
For some reason, the Google bot appends ?_escaped_fragment= to my URLs. As an example, http://me.com/about gets changed to http://me.com/about?_escaped_fragment=. I've verified this in the access logs.
I'm trying to catch this request and serve the Google bot the snapshot with this config:
location / {
if ($args ~ "_escaped_fragment_=") {
rewrite ^ /snapshots/$1;
}
}
However, requesting this URL: http://me.com/about?_escaped_fragment= always results in a 404. Same with the other pages.
The snapshots are stored in /snapshots, relative to the root of the website. They're named after their pages, following directory structure, so http://me.com/business/register has a snapshot in /snapshots/business/register.html.
What can I do to get these snapshots to work?
Thanks.
Ok first let me explain why google uses ?_escaped_fragment_, This is used for websites that rely on ajax, and mark their page with hashes, like for example if you have http://example.com/gallery/#!image1 and each time the user changes to the next image you update the hash to image2, image3, but if the user goes directly to http://example.com/gallery/#!image50 your javascript uses that hash to load the 50th image directly instead of image1 ( servers can't see the hash part, only javascript can ).
So google uses this _excaped_fragment_ to tell the server which page it's trying to cache.
For more explanation use this link
As for why you get a 404 error, I think because you used a $1 without using a capturing block, The right rule would be something like this
location / {
if ($args ~ "_escaped_fragment_=(.*)") {
rewrite ^ /snapshots/$1;
}
}
But I don't think this will fix your problem, because according to your example, you didn't use hashes, you used the uri of the page, so i would rewrite the rule to something like this
location / {
# try snapshot, if not found try direct file.
try_files snapshots$request_uri.html $uri;
}
Here is what I have in nginx and it is working fine, you might need to add a special one for index.html (i.e. when accessing the root of your website)
if ($args ~ "_escaped_fragment_=/(.+)/?") {
set $path $1;
rewrite ^ /snapshots/$path.html;
break;
}
location /snapshots/ {
internal;
alias /var/www/snapshots/;
}
So http://me.com/?_escaped_fragment_=/about will access /var/www/snaphots/about.html
Don't forget this meta tag as well in your page if you use html pushstate instead of hashbangs:
meta(name="fragment", content="!")

Codeigniter "file_exists($filename)"

Need help with the codeigniter, I think file_exists is for server path, not for url. but my image folder got same level with application and system folder. find nothing on google, please help
$url=base_url();
$filename="$url/upload/$id.jpg";
if (file_exists($filename)){
echo "<li><img src=\"".$url."upload/$id.jpg\" width=\"40\" height=\"40\" /></li>";
}else{
echo "<li><img src=\"http://www.mydomain.com/haha/image/noimg.png\" width=\"40\" height=\"40\" /></li>";
}
Codeigniter is always running on index.php, so all paths are relative from there. You can use any of the following, assuming upload/ is at the same level as index.php:
file_exists("upload/$id.jpg")
file_exists("./upload/$id.jpg")
file_exists(FCPATH."upload/$id.jpg")
FCPATH is a constant that Codeigniter sets which contains the absolute path to your index.php.
As a side note, I prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.

Resources