drupal path alias exist or not - drupal

How to find whether url is exist or not ? i.e url that leads to 'page not found' error . for ex: finding test/testpage is exist or not
i mean that to check whether given relative path or full path is really exist on the site or it leads to page not found error

You can use the menu_valid_path() function for this. This returns TRUE or FALSE based on 1. Whether the menu path exists and 2. if the current user has permission to view the item.
You call it like this:
$item_exists = menu_valid_path(array('link_path' => $some_path));
Where $some_path is the path you want to test.

If you want to know does only an alias exist or not, use:
$path_exist = drupal_lookup_path('alias',$path);
But if you want to know does one of system path or alias is exist, use:
$path_exist = drupal_lookup_path('alias',$path) || drupal_lookup_path('source',$path);

Since Drupal 8.8, Path Alias is a content entity.
So we can use
$pathStorage = \Drupal::entityTypeManager()->getStorage('path_alias');
$aliases = $pathStorage->loadByProperties(['alias' => $alias]);
// or
// $pathStorage->loadByProperties(['path' => $path]);
$existingAlias = count($aliases) > 0;

Refer to this URL for Drupal 8.
You can use:
\Drupal::service('path.alias_storage')->aliasExists('current_path', 'en')
And it will load "1" if alias exists in system.

Also you can use requesting page: http://api.drupal.org/api/function/drupal_http_request/6
On error you will get not empty $result->error.

For Drupal 9 \Drupal::service('path.alias_storage')->aliasExists() is not longer available.
But you can use:
$path_alias_repository = \Drupal::service('path_alias.repository');
if ($path_alias_repository->lookupByAlias($alias, 'en')) {
return TRUE;
}
Solution is taken from here.

Related

Drupal 8 | Wrong alias used

Bonjour,
I have a problem on Drupal 8 that I can't solve, that's why I'm calling on you.
I have 2 aliases for the same node :
/public/event/10
/pro/event/10
I have a block_1 that only appears on the " /public/* " pages and a block_2 on the " /pro/* " pages.
When I access to the url "/pro/event/10", block_1 is displayed and not block_2.
I conclude that Drupal selects the alias "/public/event/10" (probably the first one he finds) while I'm on the page "/pro/event/10".
How can I programmatically tell Drupal the right alias to use?
Thank you in advance for your help.
Here is the code if it can help someone
class OOutboundPathProcessor implements OutboundPathProcessorInterface
{
function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
{
// Only for nodes
if (!isset($options['entity_type']) OR $options['entity_type'] !== 'node')
{
return $path;
}
// Get current 'space'
$espace = \Drupal::service('session')->get('espace');
// Get the node to process
$node = $options['entity'];
// New path
$str_path = "/%s/%s/%s";
$new_path = sprintf($str_path, $espace, $node->bundle(), $node->id());
// Check new path
$isValid = \Drupal::service('path.validator')->isValid($new_path);
if ($isValid === true) return $new_path;
return $path;
}
}
You might want to create your own path_processor_outbound service by implementing OutboundPathProcessorInterface.
This implementation may work on /node/{id} paths if the current requests path matches /public/event/** or /pro/event/**.
Analyzing the node entity for it's type (bundle): If it is event generate and return your desired path; if it is not event don't manipulate the path and return the original.
Writing the actual implementation in PHP code may be your own pleasure ;-)

Drupal 7 | Preserve file after entity_wrapper unset?

Question is quite simple: How to preserve file on server and in file tables, so its fid is still valid after unsetting/changing value with entity wrapper?
$ewrapper = entity_metadata_wrapper('node', $sourceNode);
unset($sourceNode->field_image[$sourceNode->language][0]);
$ewrapper->save();
Now the related file is deleted as soon as the above is called. Same happends if I use:
$ewrapper->field_image->set($newImage);
In this case I need to keep the old image.
Thanks for your help guys!
I think that you should change file status from FILE_STATUS_TEMPORARY to FILE_STATUS_PERMANENT. Check out this answer here:
https://api.drupal.org/comment/23493#comment-23493
Basically, there is no file_set_status() function, like Drupal 6 had one, but now this code should do the same job:
// First obtain a file object, for example by file_load...
$file = file_load(10);
// Or as another example, the result of a file_save_upload...
$file = file_save_upload('upload', array(), 'public://', FILE_EXISTS_REPLACE);
// Now you can set the status
$file->status = FILE_STATUS_PERMANENT;
// And save the status.
file_save($file);
So, you load file object one or another way, change it's status property and save object back again.

History.pushState(data,title,url) concatenates (instead of replacing) url to address bar if there is a trailing slash

For example,
If I use the search bar from "www.site.com" I see "www.site.com/search", which is fine.
If I use the search bar from "www.site.com/events/" I see "www.site.com/events/search", which is silly.
Why does it do this? Is this the behavior or a history.js bug or my bug?
Give an example of what you are doing.
If your current URL in the address bar has the form: http://somesite.com/path/
And you pass pushState( null, null, 'newpath' ); in this case, the link will look like http://somesite.com/path/newpath but if you pass a parameter as: pushState( null, null, '/newpath' ), in this case would look like this:
http://somesite.com/newpath
If your application is not deployed at the root (such as with a virtual directory, or just in a deeper hierarchy) then you'll end up screwing up the URL if you do history.pushState({}, '/newpath');
There's a couple alternatives :
1) Get your root path in a javascript variable that you can just prepend the URL to it. In this example window.ViewModel.rootPath is just an arbitrary place - just modify this for however you want to store global variables.
You will have to set the rootPath in script (example here for .NET).
<script>
window.ViewModel.rootPath = "#Request.ApplicationPath";
</script>
history.pushState({}, window.ViewModel.rootPath + '/newpath');
2) Check if the URL ends with a / and if it does you need to go up 1 directory level. Note: This approach requires you to know the 'parent' directory of what you're posting - in this case YourAccount.
history.pushState({ mode: 'Club' }, '',
(window.location.href.endsWith('/') ? '../' : '') +
'YourAccount/ManageClub/' + id );
If the current URL is /preview/store/YourAccount then this will become ../YourAccount/ManageClub/123.
If the current URL is /preview/store/YourAccount/ then this will become YourAccount/ManageClub/123.
These with both end up at the same URL.

Drupal user access callback selective response

Please bear with this Drupal API novice whilst I explain some background stuff!
I have been experimenting with the code below to create 2 separate responses when my users click on a custom node creation link. By default, a page opens that allows users to go through the usual steps in creating a node.
What my module does is check if the user has specific permissions and either allow them to proceed in creating the node or throw up an access denied page.
function mymodule_menu_alter(&$items) {
$items["node/add/page/%"]['access callback'] = 'mymodule_access_callback';
}
function mymodule_access_callback(){
if( user_access('open sesame') ){
drupal_set_message("successfully intecepting new node creation");
return true;
}
return false;
}
The node/add/page is blocked successfully but it does so in both cases. The if statement determines if the user has a certain permission and within it I added return true which resulted in the following error:
Fatal error: require_once() [function.require]: Failed opening
required '/node.pages.inc' (include_path='.:') in
/var/www/vhosts/mysite.co.uk/httpdocs/includes/menu.inc on line 347
As a novice, I am not sure what I need to do in order to avoid the access denied page for the right users.
Try this:
function mymodule_menu_alter(&$items) {
$items["node/add/page/%"]['access callback'] = 'mymodule_access_callback';
$items["node/add/page/%"]['file'] = drupal_get_path('module', 'node') . '/node.pages.inc';
}
EDIT
Try changing the second line above to this:
$items["node/add/page"]['file'] = drupal_get_path('module', 'node') . '/node.pages.inc';
It's an attempt to explicitly set the file path for the parent item of the path you're defining.
Also this might be a stupid thing to say but every time you make a change to hook_menu_alter() make sure you clear Drupal's caches so the changes are picked up.

Getting the mime w/o using urlmon

I was using urlmon to find the MIME of files however it didnt go well when i couldn't get the correct mime of css files and more SWFs. What can i use to get the file mime?
Hmm, I am not sure I completely understand your question, but if you want to do some sort of look up against a master list you can look at the IIS Metabase
using (DirectoryEntry directory = new DirectoryEntry("IIS://Localhost/MimeMap")) {
PropertyValueCollection mimeMap = directory.Properties["MimeMap"];
foreach (object Value in mimeMap) {
IISOle.MimeMap mimetype = (IISOle.MimeMap)Value;
//use mimetype.Extension and mimetype.MimeType to determine
//if it matches the type you are looking for
}
}

Resources