I've my Laravel project in a sub (sub) folder from my root folder and am using the simplePaginate() method in some views. After a little search I've noticted the AbstractPaginator is used and provides a method url() which is somewhere down the road invoked by the BootstrapThreeNextPreviousButtonRendererTrait which gets called from SimpleBootstrapThreePresenter.
I've been searching in the my config/app.php and helpers.php file to find something pointing to a solution. But haven't found anything yet.
How can I set up Laravel (5.1) to use my subfolder structure with the pagination class?
I've solved it modifying the BootstrapThreeNextPreviousButtonRendererTrait. I'm aware I could have also modified the AbstractPaginator but since I'm not overseeing the consequences of that right now I've chosen to tailor the trait to my needs, like so:
<?php
namespace Illuminate\Pagination;
use Illuminate\Support\Facades\Request;
trait BootstrapThreeNextPreviousButtonRendererTrait
{
/**
* Get the previous page pagination element.
*
* #param string $text
* #return string
*/
public function getPreviousButton($text = '«')
{
// If the current page is less than or equal to one, it means we can't go any
// further back in the pages, so we will render a disabled previous button
// when that is the case. Otherwise, we will give it an active "status".
if ($this->paginator->currentPage() <= 1) {
return $this->getDisabledTextWrapper($text);
}
$url = url() . '/' . Request::path() . '?page=' . ($this->paginator->currentPage() - 1);
//Laravel shipped code disabled because of an installation in a sub-sub folder.
//$url = $this->paginator->url(
// $this->paginator->currentPage() - 1
//);
return $this->getPageLinkWrapper($url, $text, 'prev');
}
/**
* Get the next page pagination element.
*
* #param string $text
* #return string
*/
public function getNextButton($text = '»')
{
// If the current page is greater than or equal to the last page, it means we
// can't go any further into the pages, as we're already on this last page
// that is available, so we will make it the "next" link style disabled.
if (! $this->paginator->hasMorePages()) {
return $this->getDisabledTextWrapper($text);
}
$url = url() . '/' . Request::path() . '?page=' . ($this->paginator->currentPage() + 1);
//Laravel shipped code disabled because of an installation in a sub-sub folder.
//$url = $this->paginator->url($this->paginator->currentPage() + 1);
return $this->getPageLinkWrapper($url, $text, 'next');
}
}
Related
I want to display the image that stored in public folder on Lumen project.
But I got 404 not found when try to display it in browser.
I already create the asset url helper:
if (!function_exists('urlGenerator')) {
/**
* #return \Laravel\Lumen\Routing\UrlGenerator
*/
function urlGenerator() {
return new \Laravel\Lumen\Routing\UrlGenerator(app());
}
}
if (!function_exists('asset')) {
/**
* #param $path
* #param bool $secured
*
* #return string
*/
function asset($path, $secured = false) {
return urlGenerator()->asset($path, $secured);
}
}
and this is how I call the image URL :
asset('public/uploads/images/product/') . $product->image
why lumen referring to route when I try to call image in public folder ?
You can do like the below.
asset('uploads/images/product/' . $product->image)
or
asset('uploads/images/product/') . '/' . $product->image
The asset() URL helper already generates a path to your root folder (which is inside the public fodler) and so you don't need to include it.
Using:
asset('uploads/images/product/' . $product->image)
or
asset('uploads/images/product/') . $product->image
should work just fine for you.
Remember you can always look at the link that gets generated to see what your helper is generating - and tweak it as required.
I want to put my module in Prestashop market place, and make it standard everyone can use it. This plugin needs to know the admin directory name dynamically to do its service.
I have searched on the Internet a lot of times, but I didn't find a solution to this issue.
You can use _PS_ADMIN_DIR_ witch is set in [your_admin_dir]/index.php:
if (!defined('_PS_ADMIN_DIR_')) {
define('_PS_ADMIN_DIR_', getcwd());
}
This constant is only set when you're on an admin context. Your FrontOffice doesn't have knowledge of this directory and should not for obvious security reason.
There's also a getAdminLink method in class Link:
/**
* Use controller name to create a link
*
* #param string $controller
* #param bool $with_token include or not the token in the url
* #return string url
*/
public function getAdminLink($controller, $with_token = true)
{
$id_lang = Context::getContext()->language->id;
$params = $with_token ? array('token' => Tools::getAdminTokenLite($controller)) : array();
return Dispatcher::getInstance()->createUrl($controller, $id_lang, $params, false);
}
Example:
// Here we create a link to the dashboard without token
$this->context->link->getAdminLink(Tab::getClassNameById(1), false)
I am trying to implement URL based translation in Zend Framework so that my site is SEO friendly. This means that I want URLs like the below in addition to the default routes.
zend.local/en/module
zend.local/en/controller
zend.local/en/module/controller
zend.local/en/controller/action
The above are the ones I have problems with right now; the rest should be OK. I have added a controller plugin that fetches a lang parameter so that I can set the locale and translation object in the preDispatch method. Here are some of my routes (stored in a .ini file):
; Language + module
; Language + controller
resources.router.routes.lang1.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.lang1.route = "(^[a-zA-Z]{2})/(\w+$)"
resources.router.routes.lang1.defaults.controller = index
resources.router.routes.lang1.defaults.action = index
resources.router.routes.lang1.map.1 = "lang"
resources.router.routes.lang1.map.2 = "module"
; Language + module + controller
; Language + controller + action
resources.router.routes.lang2.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.lang2.route = "(^[a-zA-Z]{2})/(\w+)/(\w+$)"
resources.router.routes.lang2.defaults.module = default
resources.router.routes.lang2.defaults.action = index
resources.router.routes.lang2.map.1 = "lang"
resources.router.routes.lang2.map.2 = "controller"
resources.router.routes.lang2.map.3 = "action"
As the comments indicate, several URL structures will match the same route, which makes my application interpret the format incorrectly. For instance, the following two URLs will be matched by the lang1 route:
zend.local/en/mymodule
zend.local/en/mycontroller
In the first URL, "mymodule" is used as module name, which is correct. However, in the second URL, "mycontroller" is used as module name, which is not what I want. Here I want it to use the "default" module and "mycontroller" as controller. The same applies for the previous lang2 route. So I don't know how to distinguish between if the URL is of the structure /en/module or /en/controller.
To fix this, I experimented with the code below in my controller plugin.
// Get module names as array
$dirs = Zend_Controller_Front::getInstance()->getControllerDirectory();
$modules = array_keys($dirs);
// Module variable contains a module that does not exist
if (!in_array($request->getModuleName(), $modules)) {
// Try to use it as controller name instead
$request->setControllerName($request->getModuleName());
$request->setModuleName('default');
}
This works fine in the scenarios I tested, but then I would have to do something similar to make the lang2 route work (which possibly involves scanning directories to get the list of controllers). This just seems like a poor solution, so if it is possible, I would love to accomplish all of this with routes only (or simple code that is not so "hacky"). I could also make routes for every time I want /en/controller, for instance, but that is a compromise that I would rather not go with. So, if anyone knows how to solve this, or know of another approach to accomplish the same thing, I am all ears!
I've reproduced your problem here and come out with the following (not using config files though):
Router
/**
* Initializes the router
* #return Zend_Controller_Router_Interface
*/
protected function _initRouter() {
$locale = Zend_Registry::get('Zend_Locale');
$routeLang = new Zend_Controller_Router_Route(
':lang',
array(
'lang' => $locale->getLanguage()
),
array('lang' => '[a-z]{2}_?([a-z]{2})?')
);
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
// Instantiate default module route
$routeDefault = new Zend_Controller_Router_Route_Module(
array(),
$frontController->getDispatcher(),
$frontController->getRequest()
);
// Chain it with language route
$routeLangDefault = $routeLang->chain($routeDefault);
// Add both language route chained with default route and
// plain language route
$router->addRoute('default', $routeLangDefault);
// Register plugin to handle language changes
$frontController->registerPlugin(new Plugin_Language());
return $router;
}
Plug-in
/**
* Language controller plugin
*/
class Plugin_Language extends Zend_Controller_Plugin_Abstract
{
/**
* #var array The available languages
*/
private $languages = array('en', 'pt');
/**
* Check the URI before starting the route process
* #param Zend_Controller_Request_Abstract $request
*/
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$translate = Zend_Registry::get('Zend_Translate');
$lang = $translate->getLocale();
// Extracts the URI (part of the URL after the project public folder)
$uri = str_replace($request->getBaseUrl() . '/', '', $request->getRequestUri());
$langParam = substr($uri, 0, 3);
// Fix: Checks if the language was specified (if not, set it on the URI)
if((isset($langParam[2]) && $langParam[2] !== '/') || !in_array(substr($langParam, 0, 2), $this->languages)) { {
$request->setRequestUri($request->getBaseUrl() . '/' . $lang . "/" . $uri);
$request->setParam('lang', $lang);
}
}
}
Basically, there's the route chain for applying the language settings within the module default route. As a fix, we ensure that the URI will contain the language if the user left it out.
You'll need to adapt it, as I'm using the Zend_Registry::get('Zend_Locale') and Zend_Registry::get('Zend_Translate'). Change it to the actual keys on your app.
As for the lang route: [a-z]{2}_?([a-z]{2})? it will allow languages like mine: pt_BR
Let me know if it worked for you.
Recently I've been doing some research into SEO and how URIs that use hyphens or underscores are treated differently, particularly by Google who view hyphens as separators.
Anyway, eager to adapt my current project to meet this criteria I found that because Kohana uses function names to define pages I was receiving the unexpected '-' warning.
I was wondering whether there was any way to enable the use of URIs in Kohana like:
http://www.mysite.com/controller/function-name
Obviously I could setup a routeHandler for this... but if I was to have user generated content, i.e. news. I'd then have to get all articles from the database, produce the URI, and then do the routing for each one.
Are there any alternative solutions?
Note: This is the same approach as in Laurent's answer, just slightly more OOP-wise. Kohana allows one to very easily overload any system class, so we can use it to save us some typing and also to allow for cleaner updates in the future.
We can plug-in into the request flow in Kohana and fix the dashes in the action part of the URL. To do it we will override Request_Client_Internal system class and it's execute_request() method. There we'll check if request->action has dashes, and if so we'll switch them to underscores to allow php to call our method properly.
Step 1. Open your application/bootstrap.php and add this line:
define('URL_WITH_DASHES_ONLY', TRUE);
You use this constant to quickly disable this feature on some requests, if you need underscores in the url.
Step 2. Create a new php file in: application/classes/request/client/internal.php and paste this code:
<?php defined('SYSPATH') or die('No direct script access.');
class Request_Client_Internal extends Kohana_Request_Client_Internal {
/**
* We override this method to allow for dashes in the action part of the url
* (See Kohana_Request_Client_Internal::execute_request() for the details)
*
* #param Request $request
* #return Response
*/
public function execute_request(Request $request)
{
// Check the setting for dashes (the one set in bootstrap.php)
if (defined('URL_WITH_DASHES_ONLY') and URL_WITH_DASHES_ONLY == TRUE)
{
// Block URLs with underscore in the action to avoid duplicated content
if (strpos($request->action(), '_') !== false)
{
throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
}
// Modify action part of the request: transform all dashes to underscores
$request->action( strtr($request->action(), '-', '_') );
}
// We are done, let the parent method do the heavy lifting
return parent::execute_request($request);
}
} // end_class Request_Client_Internal
What this does is simply replacing all the dashes in the $request->action with underscores, thus if url was /something/foo-bar, Kohana will now happily route it to our action_foo_bar() method.
In the same time we block all the actions with underscores, to avoid the duplicated content problems.
No way to directly map a hyphenated string to a PHP function so you will have to do routing.
As far as user generated content, you could do something like Stack Exchange does. Each time user content is saved to the database, generated a slug for it (kohana-3-2-how-can-i-use-hyphens-in-uris) and save it along with the other information. Then when you need to link to it, use the unique id and append the slug to the end (ex:http://stackoverflow.com/questions/7404646/kohana-3-2-how-can-i-use-hyphens-in-uris) for readability.
You can do this with lambda functions: http://forum.kohanaframework.org/discussion/comment/62581#Comment_62581
You could do something like
Route::set('route', '<controller>/<identifier>', array(
'identifier' => '[a-zA-Z\-]*'
))
->defaults(array(
'controller' => 'Controller',
'action' => 'show',
));
Then receive your content identifier in the function with Request::current()->param('identifier') and parse it manually to find the relating data.
After having tried various solutions, I found that the easiest and most reliable way is to override Kohana_Request_Client_Internal::execute_request. To do so, add a file in your application folder in "application\classes\kohana\request\client\internal.php" then set its content to:
<?php defined('SYSPATH') or die('No direct script access.');
class Kohana_Request_Client_Internal extends Request_Client {
/**
* #var array
*/
protected $_previous_environment;
/**
* Processes the request, executing the controller action that handles this
* request, determined by the [Route].
*
* 1. Before the controller action is called, the [Controller::before] method
* will be called.
* 2. Next the controller action will be called.
* 3. After the controller action is called, the [Controller::after] method
* will be called.
*
* By default, the output from the controller is captured and returned, and
* no headers are sent.
*
* $request->execute();
*
* #param Request $request
* #return Response
* #throws Kohana_Exception
* #uses [Kohana::$profiling]
* #uses [Profiler]
* #deprecated passing $params to controller methods deprecated since version 3.1
* will be removed in 3.2
*/
public function execute_request(Request $request)
{
// Create the class prefix
$prefix = 'controller_';
// Directory
$directory = $request->directory();
// Controller
$controller = $request->controller();
if ($directory)
{
// Add the directory name to the class prefix
$prefix .= str_replace(array('\\', '/'), '_', trim($directory, '/')).'_';
}
if (Kohana::$profiling)
{
// Set the benchmark name
$benchmark = '"'.$request->uri().'"';
if ($request !== Request::$initial AND Request::$current)
{
// Add the parent request uri
$benchmark .= ' « "'.Request::$current->uri().'"';
}
// Start benchmarking
$benchmark = Profiler::start('Requests', $benchmark);
}
// Store the currently active request
$previous = Request::$current;
// Change the current request to this request
Request::$current = $request;
// Is this the initial request
$initial_request = ($request === Request::$initial);
try
{
if ( ! class_exists($prefix.$controller))
{
throw new HTTP_Exception_404('The requested URL :uri was not found on this server.',
array(':uri' => $request->uri()));
}
// Load the controller using reflection
$class = new ReflectionClass($prefix.$controller);
if ($class->isAbstract())
{
throw new Kohana_Exception('Cannot create instances of abstract :controller',
array(':controller' => $prefix.$controller));
}
// Create a new instance of the controller
$controller = $class->newInstance($request, $request->response() ? $request->response() : $request->create_response());
$class->getMethod('before')->invoke($controller);
// Determine the action to use
/* ADDED */ if (strpos($request->action(), '_') !== false) throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
/* MODIFIED */ $action = str_replace('-', '_', $request->action()); /* ORIGINAL: $action = $request->action(); */
$params = $request->param();
// If the action doesn't exist, it's a 404
if ( ! $class->hasMethod('action_'.$action))
{
throw new HTTP_Exception_404('The requested URL :uri was not found on this server.',
array(':uri' => $request->uri()));
}
$method = $class->getMethod('action_'.$action);
$method->invoke($controller);
// Execute the "after action" method
$class->getMethod('after')->invoke($controller);
}
catch (Exception $e)
{
// Restore the previous request
if ($previous instanceof Request)
{
Request::$current = $previous;
}
if (isset($benchmark))
{
// Delete the benchmark, it is invalid
Profiler::delete($benchmark);
}
// Re-throw the exception
throw $e;
}
// Restore the previous request
Request::$current = $previous;
if (isset($benchmark))
{
// Stop the benchmark
Profiler::stop($benchmark);
}
// Return the response
return $request->response();
}
} // End Kohana_Request_Client_Internal
Then to add an action with hyphens, for example, "controller/my-action", create an action called "my_action()".
This method will also throw an error if the user tries to access "controller/my_action" (to avoid duplicate content).
I know some developers don't like this method but the advantage of it is that it doesn't rename the action, so if you check the current action it will be consistently called "my-action" everywhere. With the Route or lambda function method, the action will sometime be called "my_action", sometime "my-action" (since both methods rename the action).
I am working on an Authentication Plugin using a Controller Plugin. I define my navigation config within the application.ini file, and then use that and the Database user records to dynamically load the ACL and apply it to Zend_Navigation. This bit works, as it successfully loads the menu and only displays the pages the user is allowed to see.
However, this doesn't stop the user from going to the page directly. What I want to do is identify when the user is going to a page they don't have access to within the Controller Plugin so I can redirect their request to the Authentication page.
I was thinking there must be a function to retrieve the current page from Zend_Navigation, but I can't find it... so maybe it doesn't exist.
Anyway, this is my full Controller Plugin. Anyone see a solution?
<?php
class Pog_Model_AuthPlugin extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $oRequest)
{
/**
* Load user
*/
$oAuth = Zend_Auth::getInstance();
$oDbUsers = new Pog_Model_DbTable_Users();
if (!$oAuth->hasIdentity())
{
$oUser = $oDbUsers->createRow();
$oUser->name = "guest";
$oUser->setReadOnly(true);
}
else
{
$oUser = $oAuth->getIdentity();
$oUser->setTable($oDbUsers);
}
/**
* Load ACL
*/
$oAcl = new Zend_Acl();
$oAcl->addRole($oUser->name);
/**
* Add current user privileges
*/
$oPrivileges = $oUser->getPrivileges();
foreach ($oPrivileges as $oPrivilege)
{
if (!$oAcl->has($oPrivilege->resource))
$oAcl->addResource($oPrivilege->resource);
$oAcl->allow($oUser->name, $oPrivilege->resource, $oPrivilege->privilege);
}
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/**
* Add remaining Navigation resources
*/
foreach ($oNavigation->getPages() as $oPage)
{
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}
/**
* Set ACL and Role
*/
$oNavigation->setAcl($oAcl)->setRole($oUser->name);
/**
* Check if use is allowed to be here
*/
...MAGIC GOES HERE...
}
}
I think that you should be able to get current navigation page as follows:
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/*#var $active array */
$active = $oNavigation->findActive($oNavigation->getContainer());
/*#var $activePage Zend_Navigation_Page_Mvc */
$activePage = $active['page'];
// example of getting page info
var_dump($activePage->getLabel(), $activePage->getController(), $activePage->getAction());
Hope this helps.
This is the solution I used, since I can't get Marcin's solution working in my setup for some reason.
I did some more thinking and thought of a nice simple solution to the problem. Rather than use the Navigation module to find the Active page, I find it myself. Since I am already iterating through the pages, it's a piece of cake to compare the Controller and Action - if these both match I have my Active page!
The new getPages() foreach loop looks like this:
$oCurrentPage = null;
foreach ($oNavigation->getPages() as $oPage)
{
/**
* Check for Current Page
*/
if ($oPage->getController() == $oRequest->getControllerName()
&& $oPage->getAction() == $oRequest->getActionName())
$oCurrentPage = $oPage;
/**
* Add Resource, if missing
*/
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}