Laravel Controller, save only url without domain - laravel

I get from ctf0/media-manager the link to a chosen file, like
http://example.com/folder1/mypic.jpg
In my database I want only save
/folder1/mypic.jpg
because I know the domain, it's every time my one.
I need to cut the first letters flexible by counting the letters from my .env in my controller.
Maybe I want to change the domain to http://productive-example.com later, then the letters are different.
Sorry for my bad english, I hope you understand the problem.

You can use PHP's parse_url function if you would like:
$url = 'http://something.com/some/path/file.jpg';
$path = parse_url($url, PHP_URL_PATH);
// "/some/path/file.jpg"
PHP.net Manual - Function parse_url

Related

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!

Codeigniter Routes.php within folder

I am using the latest version of CodeIgniter on Server2008 with IIS7.5
I have all of my CI files in a folder mywebsite.com/survey
nps = Controller
survey = Function
client_id = variable base64 encoded client number
I have a script that runs when you visit:
http://mywebsite.com/survey/nps/survey/client_id/MjgzOTcyMW
But I want for it to run when you visit:
http://mywebsite.com/survey/MjgzOTcyMW
How do I set up my routes.php?
I currently have:
$route['/:any'] = 'nps/survey/client_id/';
try
$route['(:any)'] = 'nps/survey/client_id/$1';
or
$route['survey/(:any)'] = 'nps/survey/client_id/$1';
You have to make sure you don't mix up your routes here:
Using just $route['/:any'] would be wrong (even if you had the (:any) correct.
To properly define a route), remember that the left hand side is the pattern route, and the right hand (after the =) is the translated controller/method/parameter format.
So define the route (after all your other routes) as they are to be ordered from MOST specific to least specific (similar to ALLOW/DENY rules etc;):
$route['survey/(:any)'] = 'nps/survey/client_id/$1';

Additional URI segment before Codeigniter controller

I'm making this little project in Codeigniter and I need to have one additional segment before controller.
The default Codeigniter URL is:
base_url/controller/function/parameter1/../parametern
What I need is:
base_url/something/controller/function/parameter1/../parametern
Where "something" is a name that user creates so I cant create a subfolder in controllers folder as suggested in other topics because its dynamic and each user chooses what he likes.
Basically what I need is that it like ignores that segment (I would catch that segment in a hook, extend CI_controller or something like that and validate it), for example if I write base_url/stackoverflow-rocks/home/function, base_url/asd-whatever/home/function Codeigniter would look at it like base_url/home/function
I have also looked at Passing variables before controller URI segment in CodeIgniter question, its almost the same as mine but the suggested answer didn't work.
I used $route['(:any)/(:any)'] = '$2'; which works if the url is base_url/whatever/home, but if the url is base_url/whatever/home/function or base_url/whatever/home/function/param1/../paramn it doesn't, the workaround for this is to write:
$route['(:any)/(:any)'] = '$2';
$route['(:any)/(:any)/(:any)'] = '$2/$3';
...
$route['(:any)/../(:any)'] = '$2/../$n'
which is easy, but seems a bit lame, and it will only work if I have from 2 to n segments in url. I also tried to mix it with regular expressions, like:
$route['(:any)/(.*)'] = '$2'
But it works just like the previous one, (.*) is just one segment but not the whole url...
Is there some way to just write
$route['(:any)/rest of the url'] = 'rest of the url';?
I also tried using .htaccess:
RewriteRule ([^/]*)/(.*) inedx.php?/$2
or
RewriteRule (.*)/(.*) index.php?/$2
But it didn't work because $2 referenced to the first part, for example if I write:
base_url/one/two it rewrites it to base_url/index.php?/one.
But if I use:
RewriteRule (.*)/(.*) index.php?/$1/test/$2
it references as it should, for example base_url/one/two => base_url/index.php?/one/test/two, so $1 = one and $2 = two, as it should be.
Quite a long question but I hope someone can help, thanks!
see if this works:
$route['base_url/controller/(:any)'] = 'base_url/$1'

code igniter routing

I am trying to work out the code igniter routing
I have a url that will look like
http://example.com/register
I want that to hit
http://example.com/account/register/normal
I also have
http://example.com/invite/something_random_here
which I want to hit
http://example.com/account/register/invite/something_random_here
I also have
http://example.com/register/something_random_here
which I want to hit
http://example.com/account/register/subscribed/something_random_here
How do I setup these routes?
Pretty much Straight out of the User Guide
$route['register'] = "account/register/normal";
$route['invite/(:any)'] = "account/register/invite/$1";
Basically anything after invite/ will get tacked onto the end of account/register/invite. I believe it only works for one segment, if you want multiple segment support you'll have to use a regular expression:
$route['invite/(.+)'] = "account/register/invite/$1";
Another usefull one (because I believe (:any) only works for characters) would be:
$route['invite/([a-zA-Z0-9_-]+)'] = "account/register/invite/$1";
This will let all alpha-numeric values (single segment) with _ or - go through, great for GUIDs :)
I believe for your first URL, you would use the following route:
$route['register'] = "account/register/normal";
Your second URL, would make use of the following route:
$route['invite/(:any)'] = "account/register/invite/$1";
Both of these routes would need to be placed in your "config/routes.php" file.
Hope this helps?

SEO-friendly URLs in CodeIgniter without the use of slugs?

Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a url_title() function in the URL Helper (which will need loaded, of course) that will change Foo Bar to foo-bar.
$name = 'Foo Bar';
$seo_name = url_title($name, TRUE);
// Produces: foo-bar
http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the TRUE parameter will lowercase everything.
To solve your problem, I suppose you could either do a foreach statement in your routes.php file or pass the url_title() value to the URL, rather than the ID, and modify your code to match the url_title() value with its category name in the DB.
Afaik the link between 4 and "foo-bar" has to be stored in the DB, so you'll have to run some queries. This is usually not done via routing in CI. Also routing just points a URL to a controller and function and has little to do with url rewriting.
Why don't you want to use slugs?
You could try storing the search engine friendly route in the database using this method or this one.
I wouldn't recommend throwing a 404. Use the canonical link tag in the instead if your worried about Google indexing both http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.
But if you really want to I guess you could write a function that is called during the pre_controller hook http://codeigniter.com/user_guide/general/hooks.html that checks to see if the URL has an integer as the second segment then call the show_404() method. Perhaps a better solution when writing this function would be to redirect to the SEO friendly version.
Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Yes.
Using CI 3,
http://www.codeigniter.com/user_guide/general/routing.html
Use Callbacks, PHP >= 5.3
$route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id)
{
return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id;
};
You can route to call a function to extract the name of the category.
Hope I answered your question and can help more people to like codeigniter as I believe it's speedy and light.
Slugs usage is important to make web application more secure which i think is important.
A better recommendation will be to use route to give you a better solution.
$route['(:any)/method/(:num)'] = 'Class/method';
or
$route['(:any)/method/(:num)'] = 'Class/method/$1';
$route['(:any)/gallery/(:num)'] = 'Class/gallery/$1';
base_url()/business-services/gallery/6
base_url()/travel/gallery/12
how to modify routes in codeigniter
Have fun :)

Resources