Zend Framework: Checking if route exists from code - zend-framework

in zend framework, is there anyway i can check if a route exists from code?
example
say the following routes/urls are valid (point to controller/action)
/users
/users/1 // /users?id=1
/users/page/1 /users?page=1
/users/tagged/tagname/page/1 /users?tagged=1&page=1
if the user tries to goto /users/nonexistantpage it should fail. soemthing to check if the user request the url, will it fail, but on the code level.

I believe you're looking for the match() method for the Zend router. See if that helps.

It's kinda old question, but I guess this is what you are looking for:
foreach(Zend_Controller_Front::getInstance()->getRouter()->getRoutes() as $route)
{
$route->match($uri);
}

For those using Zend Framework 2, this is very simple.
Let say we want to check if an URI matches against registered router and redirect the user if this is different from the current url.
$goto = 'http://www.mysite.tld/admin';
$request = $this->getRequest();
$request->setUri($goto);
if ($routeToBeMatched = $this->getServiceLocator()->get('Router')->match($request)) {
$currentRouteMatchName = $this->getEvent()->getRouteMatch()->getMatchedRouteName();
if ($routeToBeMatched->getMatchedRouteName() != $currentRouteMatchName) {
return $this->redirect()->toRoute($goto);
}
}

If you use rewrite router (Zend_Controller_Router_Rewrite), it has a method hasRoute($route_name)
Then if you want to check if route exists anywhere in your application you can check it like that:
Zend_Controller_Front::getInstance()->getRouter()->hasRoute("my_route");

Related

Google sites API, IllegalArgumentException("Trying to set foreign cookie") after RedirectRequiredException

I am using the gdata-media-1.0-1.47.1.jar functionality to fetch media data using the com.google.gdata.client.media.MediaService.getMedia(IMediaContent mediaContent) method. For some requests I get a RedirectRequiredException. When I redo the getMedia request, using the url i get from RedirectRequiredException.getRedirectLocation(), I get an IllegalArgumentException("Trying to set foreign cookie") exception.
From what I can see, the reason for this is that the domain in the response header for the cookie doesn't match the domain of the redirect location. In com.google.gdata.client.http.GoogleGDataRequest.matchDomain() the first argument is ".docs.google.com" and the second is "docs.google.com" which makes the domain matching fail.
Is this a correct behaviour? Why is this happening? Is there something I can do about this? Am I doing anything wrong here? Is is possible to avoid this problem?
SitesService sitesService = new SitesService("SomeAppName");
try {
MediaContent mc = new MediaContent();
mc.setUri(aURI);
return sitesService.getMedia(mc);
} catch (RedirectRequiredException e) {
MediaContent mc = new MediaContent();
mc.setUri(e.getRedirectLocation());
return sitesService.getMedia(mc);
}

Redirect after node delete does not delete the node

I am implementing the 'form_alter' hook in Drupal 7. I want to redirect the web to a specific node after deleting any node of type 'article'.
It seems that the proper way of doing so is:
function mymodule_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
case 'node_delete_confirm':
if($form['#node']->type == 'article'){
$form['actions']['submit']['#submit'][] = '_mymodule_redirect';
}
break;
}
}
function _mymodule_redirect($form, &$form_state){
$form_state['redirect'] = 'node/60';
}
When I put this code in my module it does redirect after confirming the node delete but the node is not actually deleted, if I go to the home page it is still alive!
If I remove the code the node is deleted as expected and the webpage is redirected to the frontpage as usual.
What am I doing wrong?
UPDATE: I forced the 'node_delete_confirm_submit' before the redirect action writing the following line before adding my redirect handler:
$form['actions']['submit']['#submit'][] = 'node_delete_confirm_submit';
This solves the problem.
The easiest way to accomplish this task (and not have to use a hook at all) would be to use the Rules module. It's a nice clean way of performing any number of actions on your site, and I know there's a rule for redirecting the user after content of a certain type is deleted.
Just for clarification I repeat the entire correct answer:
/**
* Implements hook_form_alter()
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
switch ($form_id) {
case 'node_delete_confirm':
// replace 'article' in next line with your node type machine name
if($form['#node']->type == 'article') {
$form['actions']['submit']['#submit'][] = 'node_delete_confirm_submit';
$form['actions']['submit']['#submit'][] = '_MYMODULE_redirect';
}
break;
}
}
function _MYODULE_redirect($form, &$form_state){
// replace 'node/123' in next line with node you like redirect to
$form_state['redirect'] = 'node/123';
}
Doing only $form['actions']['submit']['#submit'][] = '_MYMODULE_redirect'; was not enough. Still $form['actions']['submit']['#submit'][] = 'node_delete_confirm_submit'; needed to be triggered. Now the delete and the redirect are both triggered.

AngularJS $resource creating new object instead of updating object

// Set up the $resource
$scope.Users = $resource("http://localhost/users/:id");
// Retrieve the user who has id=1
$scope.user = $scope.Users.get({ id : 1 }); // returns existing user
// Results
{"created_at":"2013-03-03T06:32:30Z","id":1,"name":"testing","updated_at":"2013-03-03T06:32:30Z"}
// Change this user's name
$scope.user.name = "New name";
// Attempt to save the change
$scope.user.$save();
// Results calls POST /users and not PUT /users/1
{"created_at":"2013-03-03T23:25:03Z","id":2,"name":"New name","updated_at":"2013-03-03T23:25:03Z"}
I would expect that this would result in a PUT to /users/1 with the changed attribute. But it's instead POST to /users and it creates a new user (with a new id along with the new name).
Is there something that I'm doing wrong?
AngularJS v1.0.5
you just need to tell the $resource, how he has to bind the route-parameter ":id" with the JSON Object:
$scope.Users = $resource("http://localhost/users/:id",{id:'#id'});
This should work,
regards
thanks for the answer. It worked in the end for me too.
As a side note, I was using .NET WEB API and my entity has an Id property (UPPER CASE "I").
The PUT and DELETE worked only after I used the following:
$scope.Users = $resource("http://localhost/users/:Id",{Id:'#Id'});
Hope it helps.

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.

How to get the complete request that calls my MVC2 controller?

Newbie question … sorry ;-)
I have to write and to integrate a new website in a complex web application.
My new (MVC2) website will be hosted on a separate server and only called when the user clicks on a link in the already existing, complex website.
Means I(!) define the URL which calls my(!) new website.
But “they” (the calling, already existing, complex web application/website) will add an attribute to the url. This attribute is the sessionID.
Ok, I think I understand already that this calls my (MVC2) controller.
But how can I get in my (MVC2) controller the “calling URL” (which include the added sessionID)?
Hopefully that someone understand what I ask ;-)
Thanks in advance!
I want just share my little parser - hopefully it helps someone. ;-)
Also requests like
(Request.Url.Query =) "?sessionID=12345678901234567890123456789012&argumentWithoutValue&x=1&y&z=3"
will be well parsed.
Here my code:
Hashtable attributes = new Hashtable();
string query = Request.Url.Query;
string[] arrPairs = query.Split('&'); // ...?x=1&y=2
if (arrPairs != null)
{
foreach(string s in arrPairs)
{
if (!String.IsNullOrEmpty(s))
{
string onePair = s.Replace("?", "").Replace("&", "");
if (onePair.Contains("="))
{
string[] arr = onePair.Split('=');
if (arr != null)
{
if (arr.Count() == 2)
{
attributes.Add(arr[0], arr[1]);
}
}
}
else
{
// onePair does not contain a pair!
attributes.Add(onePair, "");
}
}
}
You really should set your URL and Route to be more MVC-Like. The URL you are calling should be:
newapp/controller/action/sessionId
Then set your route up:
routes.MapRoute(
"sessionId",
"{controller}/{action}/{sessionId}",
new { controller = "controller", action = "action", sessionId = 0 });
Then in your controller:
public ActionResult Action(int sessionId)
{
}
In your controller you still have direct access to the Request object, so you can use Request.Url, etc.
Does that answer your question, or is it something else that you need?