How to get baseUrl in Yii2 advanced app after Url rewrite - .htaccess

I have used Yii2 advanced application. i rewrite url in frontend and backend.
After rewrite Frontend url is
localhost:83/Working-copy/mySite/
And For Backend
localhost:83/Working-copy/mySite/admin
Now i want to get base url like
/Working-copy/mySite/
But i don't get it properly
I have tried following ways,
echo Yii::getAlias('#web') // ans= /Working-copy/mySite/admin
echo Yii::getAlias('#backend') // ans= /var/www/Working-copy/mySite/backend
echo Yii::getAlias('#webroot') // ans= /var/www/Working-copy/mySite/backend
echo Yii::$app->request->BaseUrl // ans= /Working-copy/mySite/admin
echo Yii::$app->getBasePath(false) // ans= /var/www/Working-copy/mySite/backend
echo Yii::$app->homeUrl // ans = /Working-copy/mySite/admin/
In some url i get /var/www/ and in some url get /admin/.
i only want my project name.
any solution please?

Create components into common folder.
Add Request.php
namespace common\components;
class Request extends \yii\web\Request {
public $web;
public $adminUrl;
public function getBaseUrl(){
return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
}
public function getActualBaseUrl(){
return str_replace($this->web, "", parent::getBaseUrl());
}
public function resolvePathInfo(){
if($this->getUrl() === $this->adminUrl){
return "";
}else{
return parent::resolvePathInfo();
}
}
}
Use Yii::$app->request->getActualBaseUrl().

Related

CodeIgniter Route pass param in default route

Suppose I have developed a website www.example.com,
Now I want to pass a param just after the domain name. e.g. www.example.com/param. Is that possible?
My defult route
you can pass the parameter to default route like following.
routes.php
$route['default_controller'] = 'pages';
$route['about'] = 'pages/about';
$route['(.*)'] = 'pages';
You should call $route['(.*)'] in the last line of the code, else if you type www.example.com/about About Page URL in the browser, it will redirect to default controller method.
$route['(.*)'] : it means you can pass unlimited param in the URL
use can use $this->uri->segment() or $this->uri->segment_array() to collection the paramaters in the function
example:
If your URL like this
www.example.com/param1/param2/param3/param4
public function index(){
$param1 = $this->uri->segment(1); // return `param1`
$param2 = $this->uri->segment(2); // return `param2`
$param3 = $this->uri->segment(3); // return `param3`
$param4 = $this->uri->segment(4); // return `param4`
// OR
$paramArray = $this->uri->segment_array(4); // all parameter in Array format
}

Trigger an URL with a cron job

I'm working on a Symfony 3 website and I need to call a URL of my website with a cron job.
My website is hosted on OVH where I can configure my cron job.
For now, I have setup the command : ./demo/Becowo/batch/emailNewUser.php
emailNewUser.php content :
<?php
header("Location: https://demo.becowo.com/email/newusers");
?>
In the log I have :
[2017-03-07 08:08:04] ## OVH ## END - 2017-03-07 08:08:04.448008 exitcode: 0
[2017-03-07 09:08:03] ## OVH ## START - 2017-03-07 09:08:03.988105 executing: /usr/local/php5.6/bin/php /homez.2332/coworkinwq/./demo/Becowo/batch/emailNewUser.php
But emails are not sent.
How should I configure my cron job to execute this URL ?
Or should I call directly my controller ? How ?
ok, finally it works !!!
Here are the step I followed for others :
1/ You need a controller to send emails :
As the controller will be called via command, you need to injec some services
em : entity manager to flush data
mailer : to access swiftMailer service to send the email
templating : to access TWIG service to use template in the email body
MemberController.php
<?php
namespace Becowo\MemberBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Becowo\CoreBundle\Form\Type\ContactType;
use Becowo\CoreBundle\Entity\Contact;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
class MemberController extends Controller
{
private $em = null;
private $mailer = null;
private $templating = null;
private $appMember = null;
public function __construct(EntityManager $em, $mailer, EngineInterface $templating, $appMember)
{
$this->em = $em;
$this->mailer = $mailer;
$this->templating = $templating;
$this->appMember = $appMember;
}
public function sendEmailToNewUsersAction()
{
// To call this method, use the command declared in Becowo\CronBundle\Command\EmailNewUserCommand
// php bin/console app:send-email-new-users
$members = $this->appMember->getMembersHasNotReceivedMailNewUser();
$nbMembers = 0;
$nbEmails = 0;
$listEmails = "";
foreach ($members as $member) {
$nbMembers++;
if($member->getEmail() !== null)
{
$message = \Swift_Message::newInstance()
->setSubject("Hello")
->setFrom(array('toto#xxx.com' => 'Contact Becowo'))
->setTo($member->getEmail())
->setContentType("text/html")
->setBody(
$this->templating->render(
'CommonViews/Mail/NewMember.html.twig',
array('member' => $member)
))
;
$this->mailer->send($message);
$nbEmails++;
$listEmails = $listEmails . "\n" . $member->getEmail() ;
$member->setHasReceivedEmailNewUser(true);
$this->em->persist($member);
}
}
$this->em->flush();
$result = " Nombre de nouveaux membres : " . $nbMembers . "\n Nombre d'emails envoyes : " . $nbEmails . "\n Liste des emails : " . $listEmails ;
return $result;
}
}
2/ Call you controller as a service
app/config/services.yml
app.member.sendEmailNewUsers :
class: Becowo\MemberBundle\Controller\MemberController
arguments: ['#doctrine.orm.entity_manager', '#mailer', '#templating', '#app.member']
3/ Create a console command to call your controller
Doc : http://symfony.com/doc/current/console.html
YourBundle/Command/EmailNewUserCommand.php
<?php
namespace Becowo\CronBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class EmailNewUserCommand extends ContainerAwareCommand
{
protected function configure()
{
// the name of the command (the part after "php bin/console")
$this->setName('app:send-email-new-users')
->setDescription('Send welcome emails to new users')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// outputs a message to the console followed by a "\n"
$output->writeln('Debut de la commande d\'envoi d\'emails');
// access the container using getContainer()
$memberService = $this->getContainer()->get('app.member.sendEmailNewUsers');
$results = $memberService->sendEmailToNewUsersAction();
$output->writeln($results);
}
}
4/ Test your command !
In the console, call you command : php bin/console app:send-email-new-users
5/ Create a script to run the command
Doc (french) : http://www.christophe-meneses.fr/article/deployer-son-projet-symfony-sur-un-hebergement-perso-ovh
..Web/Batch/EmailNewUsers.sh
#!/bin/bash
today=$(date +"%Y-%m-%d-%H")
/usr/local/php5.6/bin/php /homez.1111/coworkinwq/./demo/toto/bin/console app:send-email-new-users --env=demo > /homez.1111/coworkinwq/./demo/toto/var/logs/Cron/emailNewUsers-$today.txt
Here it took me some time to get the correct script.
Take care of php5.6 : it has to match your PHP version on OVH
Don't forget to upload bin/console file on the server
homez.xxxx/name has to match with your config (I found mine on OVH, and then in the logs)
IMPORTANT : when you upload the file on the server, add execute right (CHMOD 704)
6/ Create the cron job in OVH
Call your script with the command : ./demo/Becowo/web/Batch/EmailNewUsers.sh
Language : other
7/ Wait !
You need to wait for the next run. Then have a look on OVH cron logs, or on your own logs created via the command in the .sh file
It took me several days to get it..
Enjoy !!
As commented above, you should do it with a symfony commaad. This is an example for you.
NOTE: Although it is working, you can always improve this example. Especially the way command calls your endpoint.
Controller service definition:
services:
yow_application.controller.default:
class: yow\ApplicationBundle\Controller\DefaultController
Controller itself
namespace yow\ApplicationBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
/**
* #Route("", service="yow_application.controller.default")
*/
class DefaultController
{
/**
* #Method({"GET"})
* #Route("/plain", name="plain_response")
*
* #return Response
*/
public function plainResponseAction()
{
return new Response('This is a plain response!');
}
}
Command service definition
services:
yow_application.command.email_users:
class: yow\ApplicationBundle\Command\EmailUsersCommand
arguments:
- '#http_kernel'
tags:
- { name: console.command }
Command itself
namespace yow\ApplicationBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class EmailUsersCommand extends Command
{
private $httpKernel;
public function __construct(HttpKernelInterface $httpKernel)
{
parent::__construct();
$this->httpKernel = $httpKernel;
}
protected function configure()
{
$this->setName('email:users')->setDescription('Emails users');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$request = new Request();
$attributes = [
'_controller' => 'yow_application.controller.default:plainResponseAction',
'request' => $request
];
$subRequest = $request->duplicate([], null, $attributes);
$response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
$output->writeln($response);
}
}
Test
$ php bin/console email:users
Cache-Control: no-cache, private
X-Debug-Token: 99d025
X-Debug-Token-Link: /_profiler/99d025
This is a plain response!
1.0
200
OK

Magento: Browser detection to load right language

How do I implement a browser detection into Magento to load the right language.
Example:
If a US User is surfing to my Magento shop, Magento should load the path: ..myshop../usa/
usa=storecode
If a japanese User is surfing to my Magento shop, Magento should load the path: ..myshop../jp/
jp=storecode
and so on
I guess I have to adapt the .htaccess with rewrite Urls, but I never did that before. How do I have to do it?
How does the code of browser detection look like and where do I have to put it? In the header.phtml?
thank you very very much in advance!
Edit:
index.php in CE 1.7.0.2 looks like this
/**
* Error reporting
*/
error_reporting(E_ALL | E_STRICT);
/**
* Compilation includes configuration file
*/
define('MAGENTO_ROOT', getcwd());
$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
include $compilerConfig;
}
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
$maintenanceFile = 'maintenance.flag';
if (!file_exists($mageFilename)) {
if (is_dir('downloader')) {
header("Location: downloader");
} else {
echo $mageFilename." was not found";
}
exit;
}
if (file_exists($maintenanceFile)) {
include_once dirname(__FILE__) . '/errors/503.php';
exit;
}
require_once $mageFilename;
#Varien_Profiler::enable();
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
Mage::setIsDeveloperMode(true);
}
#ini_set('display_errors', 1);
umask(0);
/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';
Mage::run($mageRunCode, $mageRunType);
But this Link describes the follwing code which you cannot simply replace:
require_once 'app/Mage.php';
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
$langs[] = $found[1];
$quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
}
}
// Order the codes by quality
array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
// get list of stores and use the store code for the key
$stores = Mage::app()->getStores(false, true);
// iterate through languages found in the accept-language header
foreach ($langs as $lang) {
$lang = substr($lang,0,2);
if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
}
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
header('Location: '.getStoreForLanguage()->getBaseUrl());
exit;
}
#Varien_Profiler::enable();
#Mage::setIsDeveloperMode(true);
#ini_set('display_errors', 1);
umask(0);
Mage::run();
Can anybody help me to find out where to put it or where to adapt the index.php
Thank you again!
The request the browser sends has a field called "Accept-Language" header. It's formatting isn't so intuitive and if you wanted to do it correctly, is beyond the ability of the htaccess file and mod_rewrite to parse properly. Here's a typical "Accept-Language" request header:
Accept-Language: da, en-gb;q=0.8, en;q=0.7
Which means: "I prefer Danish, but will accept British English and other types of English"
So you can't simply look for the first two letters of the field. If you don't have Danish, then you've got to continue parsing to find the right language. Magento probably has some ways of dealing with this, for example: http://www.magentocommerce.com/wiki/multi-store_set_up/how_to_automatically_redirect_to_a_store_view_based_on_the_browser_language
Just paste the following code after require_once $mageFilename; in your CE 1.7.0.2 index.php:
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
$langs[] = $found[1];
$quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
}
}
// Order the codes by quality
array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
// get list of stores and use the store code for the key
$stores = Mage::app()->getStores(false, true);
// iterate through languages found in the accept-language header
foreach ($langs as $lang) {
$lang = substr($lang,0,2);
if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
}
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
header('Location: '.getStoreForLanguage()->getBaseUrl());
exit;
}
Make sure you don't delete or overwrite any code in your index.php file and you should be fine!

Concrete5: Can I use $_GET variable for query string on Regular Page?

How does $_GET Variable works with Concrete5? Can I use that on regular page?
I know I can do this with single page via url segment, I'm just wondering if it is possible with regular page.
Example is :http://www.domain_name.com/about-us/?name=test...
Get-parameters are available via the controllers. In the view of a page or block use:
$this->controller->get("parameterName");
A cleaner way for custom parameters would be to define them in the function view() of the page controller. If at http://www.domain_name.com/about-us is your page and you define the view function of it's pagetype controller like this:
function view($name) {
$this->set("name", $name);
}
... and call the URL http://www.domain_name.com/about-us/test – then "test" will be passed under $name to your page view.
Note that controllers for page types must be in controllers/page_types/ and called BlablaPageTypeController ... with "PageType" literally being in there.
You can use it in a template. For instance, you can grab a variable...
$sort_by = $_GET['sort'];
And then use that variable in a PageList lookup, similar to:
$pl = new PageList();
$ctHandle = "teaching";
// Available Filters
$pl->filterByCollectionTypeHandle($ctHandle); //Filters by page type handles.
// Sorting Options
if ($sort_by == "name") {
$pl->sortByName();
} else {
$pl->sortBy('teaching_date', 'desc'); // Order by a page attribute
}
// Get the page List Results
$pages = $pl->getPage(); //Get all pages that match filter/sort criteria.
$pages = $pl->get($itemsToGet = 100, $offset = 0);
Then you can iterate over that array to print stuff out...eg
if ($pages) {
foreach ($pages as $page){
echo ''.$page->getCollectionName() . '<br />';
}
}
Props to the C5 Cheatsheet for the PageList code.

Detect locale and alter url (redirect) to include locale

What i want to do is, to detect the language of a users browser and redirect him to a page containing the locale in url.
I thought, the easiest way would be, to register a kernel listener. So that is what i did:
services:
kernel__request_listener:
class: Me\MainBundle\Listener\KernelRequestListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
calls:
- [ setContainer, [ #service_container ] ]
KernelRequestListener.php
...
/**
* #Service
*/
class KernelRequestListener
{
/**
* #Observe("kernel.request")
*/
public function onKernelRequest( GetResponseEvent $response )
{
if( $newLocale = $this->newLocale() )
{
$parmArray = $request->get('_route_params');
$parmArray['_locale'] = $newLocale;
$redirectResponse = new RedirectResponse( $this->getContainer()->get('router')->generate($request->get('_route'), $parmArray) );
$redirectResponse->headers->setCookie( new Cookie('b_locale', $newLocale, time() + 2592000) );
$response->setResponse( $redirectResponse );
}
}
...
}
The method $this->newLocale() just detects if the user should be redirected to another language and returns the new language code (i.e. DE or FR).
Here comes the problem:
I am using assetics to compress the js files and jms/i18n-routing-bundle to do the locale-based routing. When the kernel listener switches locale, the page starts loading the js files over and over again. also, there are several pages (i.e. the profiler, login/logout etc.) where no redirect should take place as it makes no sense or breaks smthing.
Is a kernel listener the right place to do such a redirection or is there any better place. How to resolve the problems above?
Add, before your code:
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
if ($request->getRequestFormat() !== 'html') {
return;
}
[CODE]

Resources