Can I display pictures outside backend web folder in yii2? - yii2

I have a little problem. I can’t view images outside the backend web folder.
Aliases in common\config\main:
'aliases' => [
'#upload' => dirname(dirname(__DIR__)).'/upload',
],
View Dataprovider:
[
'format' => 'raw',
'label' => 'Immagine',
'value' => function ($data) {
return Html::img(Yii::getAlias('#upload') . $data->codice_prodotto . '/' . $data->immagine, ['width' => '70px', 'class' => 'img-thumbnail']);
},
],
Can I resolve? Thanks.

If your file is not accessible for http server, so you can't directly download it.
You can:
Move uploads directory to directory accessible for the http-server
Create action that will read the file from private directory and stream it to the browser (you can use yii\web\Response::sendFile() function for that)
Streaming file to the browser
Please read this official docs article to understand this deeply: https://www.yiiframework.com/doc/api/2.0/yii-web-response#sendFile()-detail
Action code example for your case: *
public function actionFile($filename)
{
$storagePath = Yii::getAlias('#upload');
// check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new \yii\web\NotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
And view Dataprovider configuration: *
[
'format' => 'raw',
'label' => 'Immagine',
'value' => function ($data) {
return Html::img(Url::to(['/path/to-streaming-action/file', 'filename' => $data->codice_prodotto . '/' . $data->immagine]), ['width' => '70px', 'class' => 'img-thumbnail']);
},
],
* Notice that this code is not ready to copy-paste, please read it carefully and try to understand the principle before implement it in your code.

Related

Yii2: Override 3rd party mail views

How do we override mail view files of a 3rd party module/component?
Let's assume a module is using the following code to send an email:
Yii::$app->mailer->compose([
'html' => '#myvendor/mymodule/mail/email-html',
'text' => '#myvendor/mymodule/mail/email-text',
])
->setTo([$email => $name])
->setSubject('Hi');
->send();
How would we override these individual email views #myvendor/mymodule/mail/email-html and #myvendor/mymodule/mail/email-text?
You can override these two aliases in your config:
'aliases' => [
'#myvendor/mymodule/mail/email-html' => '#app/views/mail/email-html',
'#myvendor/mymodule/mail/email-text' => '#app/views/mail/email-text',
],
Configure and rewrite the $viewPath property in the mail file in the module.
example:
public $viewPath = '#myvendor/mymodule/mail';
First, create new html and text files. Create both files.
Create both files.
mail/newHTML
mail/trxt/NewTEXT
$mailer = Yii::$app->mailer;
$mailer->viewPath = $this->viewPath;
$mailer->getView()->theme = Yii::$app->view->theme;
return $mailer->compose(['html' => $view, 'text' => 'text/' . $view], $params)
->setTo($to)
->setFrom($this->sender)
->setSubject($subject)
->send();
If you want to change the path for only one:
Use before code:
Yii :: $ app-> mailer-> viewPath = '# myvendor / newPath';
Yii::$app->mailer->compose([ #code...
  If the VIEW file: Only need to change the name for HTML and TEXT file, (both)
Update:
It can be override or through a component and ...
//new file: path\widgets\Mailer.php
namespace path\widgets;
use yourpath\Mailer as DefaultMailer; //path:mymodule/mail
class Mailer extends DefaultMailer{
public $viewPath = '#myvendor/mymodule/mail';
public function changeviewPath($_path){
$this->viewPath; = $_path;
}
}
// for use. Changes
use path\widgets\Maile; // New path
// Use before the usual code
$mailer->changeviewPath('newpath\mail');
To change the address of the files in the component. Depending on your email module, it varies
example:
'modules' => [
'myMudul' => [
'class' => 'PathModule\Module',
'mailer' => [
#code ..
],
],
...

Yii2 Pagination + PrettyURL Cannot Find site/index

I have pagination setup in site/index, with pretty url working. But my site/index is hidden by either the rewrite engine of Apache, or by UrlManager. In any case, my index page address is simply "X.COM' and pagination wishes to redirect a page change to "X.COM/index?PAGINATIONQUERY", so it always returns a 404.
Example Pagination Request (Returns 404):
x.com/index?page=2&per-page=12
Here is my UrlManager
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// '<alias:\w+>' => 'site/<alias>',
'<action:\w+>' => 'site/<action>',
],
],
How would I either remove the 'index' portion from pagination requests, or allow myself to see /index in Url again?
Thank you!
Edit:
This is my Index action
public function actionIndex()
{
$query = Shout::find()->orderBy(['id' => SORT_DESC]);
$countQuery = $query->count();
$pagination = new Pagination(['totalCount' => $countQuery, 'pageSize' => 12]);
$shouts = $query->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'shouts' => $shouts,
'pagination' => $pagination,
]);
}
Use Yii2 Gii for Generating Crud Modules with Inbuilt Pagination & Searching.
Yii2 Gii - https://www.yiiframework.com/doc/guide/2.0/en/start-gii
Make Sure Pjax enable when create crud with Gii.

All Yii2 controller not allow action without login or guest must need login

I'm using Yii2 Advance application and i am new in yii2 so how make
all yii2 controller not allow action without login or guest must me login
i mean controllers can not open without login if user not login so redirect in login page this not for one controller i need many controller
You need to add below code in common/main.php after components part.
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
You could simply create a super controller for this :
class Controller extends \yii\web\Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => false,
'roles' => ['?'],
],
],
],
];
}
}
And of course all your controllers should extend this one.
Read more about Access Control Filter.
You can try write in index.php in your backed public directory
No need to repeat in controllers
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../../config/web.php';
$config["controllerNamespace"]='app\controllers\backend';
(new yii\web\Application($config))->run();
if(Yii::$app->user->isGuest){
$request_headers = apache_request_headers();
$srv=$request_headers['Host'];
header("Location: https://".$srv);
die();
}
use RBAC Manager for Yii 2 you can Easy to manage authorization of user.
https://github.com/mdmsoft/yii2-admin.
You could inherit from the yii Controller class where you can override the beforeAction method and in that function you can redirect the user if there is no active logged in session.
Make sure that all of the other controllers what you are using inherited from your new controller class.
EDIT:
In the SuperController beforeAction you can check if the current call is your site/index, if not then redirect to there like:
if($action->controller != "site" && $action->id != "index" ) {
$this->goHome();
}
Make sure that the goHome() take you to your site/index.
And you can split your Site actionIndex() method to an authenticated or not part like:
public function actionIndex() {
if(Yii::$app->user->isGuest) {
return $this->redirect(Url::toRoute('site/login'));
}
else {
...
}
}
Hope this helps.

Yii2 render database content

There is a textarea where user can edit some templates and can use variables like:
{{model.user.name}}
Application need to replace this variables with data and display HTML output.
We can write a small function that will replace variables from template with data but we need to use a template engine like Twig or Smarty.
https://github.com/yiisoft/yii2-twig
https://github.com/yiisoft/yii2-smarty
Now we can use ViewRenderer from Smarty or Twig.
$render = new ViewRenderer();
$content = $render->render($this->view,'template.twig',[
'model' => $model,
]);
But I see this error:
Unable to find template "template.twig" (looked into: .).
How can I use Smarty or Twig to render a template with the content from database in Yii2 ?
I found Mustache ( https://github.com/bobthecow/mustache.php ) and I'm using like this:
$m = new \Mustache_Engine();
echo $m->render("Hello {{model.client.firma}}",['model' => $model]);
You don't create a renderer manually, you configure your application components, like this:
[
'components' => [
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => ['html' => '\yii\helpers\Html'],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
]
You are telling Yii that there is a renderer to handle templates with the .twig extension.
Then, all you need to do is add the .twigextension when calling render in your controller actions:
public function actionIndex()
{
return $this->render('index.twig');
Then put your twig templates in the view folders where the views normally go.
Read the documentation for the twig extension: Twig Extension for Yii 2
If you want to only use twig templates, you can avoid specifying the extension (.twig) if you set the default extension:
'components' => [
'view' => [
'defaultExtension' => 'twig',
You should create a twig component which will wrap around Twig_Environment. You can add yii\twig\Extension extension if you need. Then you should use it like this:
$renderedTemplate = Yii::$app->twig->render($template, $context);
If you really need to render a template from a string variable you may implement your own Twig_LoaderInterface. There is a Twig_Loader_String, but it's deprecated and you should not use it.

Displaying subdirectory name in the url in Yii2 for static pages

Iam creating static pages for a client using Yii2. I am using yii2 because the client has some other requirements to scale up the web later. I use Yii2 Basic app. The yii2 basic has default pages like about, contact etc.
The url for those pages after enabling pretty url is
www.example.com/about
etc
Now i need to create pages
"xyz.php"
under a sub directory like
"abc"
. So i need my url to be www.example.com/abc/xyz
How do i achieve this? to be informed iam a learner, I followed url rules, helpers but did not find a strong solution.
create a controller like StaticController.php and use the yii\web\ViewAction
http://www.yiiframework.com/doc-2.0/yii-web-viewaction.html
As an example:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
/**
* StaticController is only for displaying static pages.
*/
class StaticController extends Controller
{
public $defaultAction = 'page';
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['page'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
public function actions()
{
return [
'page'=>array(
'class'=>'yii\web\ViewAction',
'viewPrefix'=>null, // or set a specific directory e.g. 'static-pages' if you want to store the static pages in a subdirectory
),
];
}
}
And add this Rule to your UrlManager (where static is your controller name)
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:static>/<view:.*>' => '<controller>',
...
]
]
Now you can store your static pages in the directory /view/static/
e.g. index.php, test.php or even in subdirectories /sub/test2.php
The urls would be like /static (or /static/index), /static/test1, /static/sub/test2
The 1st pathname is of course the controller name, but you can also change the url rule to something else or rename the controller.
config/web.php
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'abc/<view:\S+>' => 'site/page',
]
]
I had a situation where I wanted the URL to indicate a sub page (like 'website/page/sub-page) but I didn't think it made sense to have a separate controller. (At the moment I just have one controller; SiteController.php.)
I am recreating the site structure of an existing site in a new Yii2 Basic site.
Client has a page called 'laptop-repair' in their existing site with a number of pages linked from it, e.g. 'laptop-overheating'. So the URI needed to look like 'laptop-repair/laptop-overheating'.
The solution:
In urlManager in config>web.php I add a new rule (Nb. the order of rules is important, the earlier rules are prioritised):
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
[
'pattern' => 'laptop-repair/<page:.*>',
'route' => 'site/laptop-repair',
'defaults' => ['page' => 'index'],
],
...
],
],
In SiteController.php I already had an action for the page which I wanted to make into a parent page:
public function actionLaptopRepair()
{
return $this->render('laptop-repair');
}
which I replaced with:
public function actionLaptopRepair($page)
{
return $this->render("/site/laptop-repair/$page");
}
The leading slash is necessary to override the default behaviour of the Yii application, which is to look for the view in 'views>{controllerName}'. For example with render('laptop-repair'); the view file laptop-repair.php would need to be in 'views>site' since the name of the controller is SiteController, whereas render("/site/laptop-repair/$page"); corresponds to a view file ($page) in 'views>site>laptop-repair'. This allows you to organise your views in subdirectories.
I created a new folder called 'laptop-repair' in 'views>site', moved the view for the parent page (laptop-repair.php) into the new directory and renamed it index.php. I put the new sub pages' view files in that new directory ('views>site>laptop-repair'), alongside the parent view (index.php).
Everything worked except for the URL creation in my nav widget. Where the following worked fine before, the 'laptop-repair' link broke after I implemented the above:
echo Nav::widget([
'options' => ['class' => 'navbar-nav ml-auto'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
[
'label' => 'Repair Services',
'items' => [
['label' => 'Desktop PC Repairs', 'url' => ['/site/pc-repair']],
['label' => 'Laptop Repairs', 'url' => ['site/laptop-repair']],
['label' => 'Mobile Phone Repairs', 'url' => ['/site/mobile-phone-repair']],
...
The fix was simply changing the relevant line to:
['label' => 'Laptop Repairs', 'url' => ['/laptop-repair']],
Creating a link from the parent page to a sub page looks like this:
<?= Html::a('Laptop overheating?', ['laptop-repair/laptop-overheating'], ['class' => '', 'title' => 'Laptop overheating']) ?>
To add a link to the parent page to the breadcrumbs of the sub page, I replaced:
$this->title = 'Laptop Over Heating?';
$this->params['breadcrumbs'][] = $this->title;
with:
$this->title = 'Laptop Over Heating?';
$this->params['breadcrumbs'][] = ['label' => 'Laptop repair', 'url' => ['/laptop-repair']];
$this->params['breadcrumbs'][] = $this->title;
in the view file of the sub page.