Quantcast
Channel: Live News for Yii Framework
Viewing all 2940 articles
Browse latest View live

[wiki] change default date format in oracle

$
0
0

Default date format in oracle is DD-MON-RR (25-JAN-18). With that output, we can't using date formatting. Too solve this issue, we must change date format oracle like date commonly using ALTER SESSION SET NLS_DATE_FORMAT=...

For complete script ` return [

'class' => 'yii\db\Connection',
'dsn' => 'oci:host=127.0.0.1:1521/XE',
'username' => 'YOUR_USERNAME',
'password' => 'YOUR_PASSWORD',
'charset' => 'utf8',

// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',

'on afterOpen' => function($event) {
    // $event->sender refers to the DB connection
    $event->sender->createCommand("ALTER SESSION SET NLS_DATE_FORMAT='DD-MM-YYYY hh24:mi:ss'")->execute();
}

]; `


[extension] crazyteea/yii2-beautyfiles

$
0
0

yii2-beautyfiles

удобная работа с файлами

[extension] dropdown-for-gridview

$
0
0
  1. Requirements
  2. Installation
  3. Usage

In place editable dropdown for Yii2 GridView This is extansion of DataColumn of Yii2. Allows to edit data of integer type directly in GridView column.

Requirements

Yii 2.0

Installation

Create folder "jz" in "vendor" in your project. Place JZDropDownColumn.php in "jz" folder. Or any other reachable one. Place jzgridviewcolumn.js in you JavaScript folder. Place jzgridviewcolumn.css in your CSS folder. Make necessary changes to AppAsset.php.

Usage

//Example for usage in GridView


Pjax::begin(['id' => 'pjax_id_1', 'options'=> ['class'=>'pjax', 'loader'=>'loader_id_1', 'neverTimeout'=>true]]);

    echo GridView::widget([

        'dataProvider' => $dp,

        'filterModel' => $model,

        'options'=>['class'=>'grid-view','id'=>'grid_id_1'],

        'summaryOptions'=>['style'=>'text-align:right;'],

        'columns' => [

            [
		      'class' => 'vendor\jz\JZDropDownColumn',
                'className' => 'Payment',
                'attribute' => 'payment_method',
                'editable' => true,
                'list' => $model::$paymentMethodArr,
		      'editUrl' => Url::to(['payment/intedit']),
		      'emptyLabel' => Yii::t('msg','Click me to change'),
		      'denyLabel' => Yii::t('msg','CANCEL'),
		      'loaderPath' => Yii::getAlias('@jzCssImgWeb').'/img_loader.gif',
                'headerOptions' => ['style'=>'width:200px; text-align:center;'],
            ],

        ],

    ]); 

Pjax::end();

//Example of action for edit attribute


    public function actionIntedit(){		
        if(isset($_GET['data'])){
            $json = json_decode($_GET['data']);
            if(isset($json->class) && isset($json->id) && isset($json->attribute) && isset($json->value)){
                $className = $json->class;
                if($className == 'Payment'){
                    $model = Payment::findOne(intval($json->id));
                    if(isset($model)){
                        $attribute = $json->attribute;
                        $model->$attribute = intval($json->value);//variable variable!!!
                        if($model->save()){
                            return json_encode(['msg'=>1,'val'=>$model->$attribute]);
                        } else {return json_encode(['msg'=>0,'val'=>$this->firstErrorMessage($model)]);}
                    } else {return json_encode(['msg'=>0,'val'=>'No model found.']);}
                }
            } else {return json_encode(['msg'=>0,'val'=>'No correct data set provided.']);}
        } else {return json_encode(['msg'=>0,'val'=>'No data provided.']);}
    }
    

[news] Debug extension 2.1.9 released

[news] Yii 2.0.27

$
0
0

We are very pleased to announce the release of Yii Framework version 2.0.27. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.

Version 2.0.27 is a minor release of Yii 2.0. This release includes bug fixes accumulated since last release and a two enhancements from old pull requests:

  • When using incorrect alias or option in console it now lists correct ones.
  • appendTimestamp support was added to View methods registerCssFile() and registerJsFile().

Thanks to all Yii community members who contribute to the framework, translators who keep documentation translations up to date and community members who answer questions at forums.

There are many active Yii communities so if you need help or want to share your experience, feel free to join them.

A complete list of changes can be found in the CHANGELOG.

[extension] neoacevedo/yii2-storage

$
0
0

Yii2 Storage

  1. Instalación
  2. Uso

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads

Gestión de almacenamiento para Yii2.

Instalación

La forma preferida de instalar esta extensión es a través de composer.

Luego ejecute

php composer.phar require --prefer-dist neoacevedo/yii2-storage

o agregue

"neoacevedo/yii2-storage": "^18.08"

a la sección require de su archivo composer.json.

Uso

Una vez que la extensión está instalada, configure las credenciales para el servicio de almacenamiento en el archivo de configuración de su aplicación Yii :

<?php

'components' => [
	/**
	 * Amazon S3
	 */ 
	'storageAWS' => [
	    'class' => 'neoacevedo\yii2\Storage',
	    'service' => 's3',
	    'config' => [
	        'key' => 'YOUR_IAM_ACCESS_KEY',
	        'secret' => 'YOUR_IAM__SECRET_ACCESS_KEY',
	        'bucket' => 'your-bucket',
	        'region' => 'your-region',
	        'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
	    ],
	    'prefix' => '', // ruta al directorio de imágenes. Ej: images/ (Opcional)
	]


	/**
	 * Azure Storage Blob
	 */
	'storageAzure' => [
	    'class' => 'neoacevedo\yii2\Storage',
	    'service' => 'azure',
	    'config' => [
	        'accountName' => 'ACCOUNT_NAME',
	        'accountKey' => 'ACCOUNT_KEY',
	        'container' => 'your-container',
	        'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
	    ],
	    'prefix' => '' // ruta al directorio de imágenes. Ej: images/ (Opcional)
	]

	/**
	 * Google Storage Cloud
	 */
	'storageGoogle' => [
	    'class' => 'neoacevedo\yii2\Storage',
	    'service' => 'gsc',
	    'config' => [
	        'projectId' => 'YOUR_PROJECT_ID',
	        'bucket' => 'your-bucket'
	        'keyFile' => '', // Contenido del archivo JSON generado en la consola de Google
	        'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
	    ],
	    'prefix' => '', // ruta al directorio de imágenes. Ej: images/ (Opcional)
	]

	/**
	 * Almacenamiento local
	 */ 
	'storageLocal' => [
	    'class' => 'neoacevedo\yii2\Storage',
	    'service' => 'local',
	    'config' => [
	        'baseUrl' => Yii::$app->request->hostInfo, // ej: http://example.com/
	        'directory' => '@webroot/web/uploads/', // reemplace @webroot por @frontend o @backend según sea el caso. La ruta debe terminar con una barra diagonal
	        'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
	    ],
	    'prefix' => '', // ruta al directorio de imágenes. Ej: images/ (Opcional) (Opcional)
]

Ahora puede llamarlo desde su aplicación :

/**
 * Sube el archivo de imagen.
 * @param yii\web\UploadedFile $imageFile
 * @return boolean
 */
public function upload($imageFile)
{
    if (null !== $imageFile) {
        Yii::$app->storage->uploadedFile = $imageFile;
        return Yii::$app->storage->save();
    } else {
        return false;
    }
}

...
// obtener la URL generada
echo Yii::$app->storage->getUrl(Yii::$app->storage->prefix.$model->image_file); 

O simplemente en su código :

<?php 
use neoacevedo\yii2\Storage;

public function upload()
{
	$storage = new Storage([
		'service' => Storage::AWS_S3,
		'config' => [
			'key' => 'YOUR_IAM_ACCESS_KEY',
			'secret' => 'YOUR_IAM_SECRET_ACCESS_KEY',
			'bucket' => 'your-bucket',
			'region' => 'your-region',
			'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
		],
		'prefix' => '' // opcional
	]);
	
	$storage->uploadedFile = \yii\web\UploadedFile::getInstanceByName("file");
	return $storage->save();
}

Puede usar el modelo del componente en su formulario de las siguientes maneras en su controlador:

...
// Constructor de clase
	$storage = new Storage([
		'service' => Storage::AWS_S3,
		'config' => [
			'key' => 'YOUR_IAM_ACCESS_KEY',
			'secret' => 'YOUR_IAM_SECRET_ACCESS_KEY',
			'bucket' => 'your-bucket',
			'region' => 'your-region',
			'extensions' => 'pdf, jpg, jpeg, gif, png, bmp'
		],
		'prefix' => '' // opcional
	]);
	return $this->render('create', [
                'model' => $model,
                'fileModel' => $storage->getModel()
    ]);	
...
// Como componente
	return $this->render('create', [
                'model' => $model,
                'fileModel' => Yii::$app->storage->getModel()
    ]);
...
// Usando el modelo de manera directa
	return $this->render('create', [
                'model' => $model,
                'fileModel' => new neoacevedo\yii2\storage\models\FileManager()
    ]);

Dentro de la vista:

<?= $form->field($fileModel, 'uploadedFile')->fileInput() ?>

[wiki] Yii v2 for beginners

$
0
0
  1. Intro
  2. Prerequisities
  3. Yii demo app + GitLab
  4. User management + basic SQL commands
  5. Login via database + Session
  6. Access rights

Please give me a few days to add whole text

Intro

Skip this paragraph if you are in hurry :-) ... 8 years ago I started these two tutorials for Yii 1:

... and today I am beginning with Yii 2 so I will also gather my snippets and publish them here so we all can quickly setup the yii-basic-demo.

I have some experiences with Yii 1, but I havent used Yii for almost 5 years so many things are new for me again. Plus I was suprised that the Yii 2 demo application does not contain some basic functionalities (like DB login, translations etc) which must be implemented in the most of web projects so I will focus on them. Plus I will talk about GitLab.

Prerequisities

Skip this paragraph if you know how to run your Yii demo project...

I work with Win10 + XAMPP Server so I will expect this configuration. Do not forget to start the server and enable Apache + MySQL in the dialog. Then test that following 2 URLs work for you

You should also download the Yii basic demo application and place it into the htdocs folder. In my case it is here:

  • C:\xampp\htdocs

And your index.php should be here:

  • C:\xampp\htdocs\basic\web\index.php

If you set thing correcly up, following URL will open your demo application. Now it will probably throw an exception:

The Exception is removed by enterinng any text into attribute 'cookieValidationKey' in file:

  • C:\xampp\htdocs\basic\config\web.php

Dont forget to connect Yii to the DB. It is done in file:

  • C:\xampp\htdocs\basic\config\db.php

... but it should work out of the box if you use DB name "yii2basic" which is used below ...

Yii demo app + GitLab

... text ...

User management + basic SQL commands

To create DB with users, use following command. I recommend charset utf8_unicode_ci (or utf8mb4_unicode_ci) as it allows you to use more international characters.

CREATE DATABASE IF NOT EXISTS `yii2basic` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(45) NOT NULL,
  `password` VARCHAR(60) NOT NULL,
  `authKey`  VARCHAR(60),
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

INSERT INTO `user` (`id`, `username`, `password`, `authKey`) VALUES (NULL, 'user01', '0497fe4d674fe37194a6fcb08913e596ef6a307f', NULL);

If you must use MyISAM instead of InnoDB, just change the word InnoDB into MYISAM.

Then use GII to generate model, views and controller. The GII URL will probably be

  • http://localhost/basic/web/index.php?r=gii.
  • When creating the model, check this checkbox: Enable I18N ... we will need i18n later
  • Note that there already is a model named User in the demo app. You will not need it if you want to use login-via-DB so feel free to check "Overwrite" in GII. The newly created User model will now be usable only for table operations, not for login. But we will enhance it, keep reading.

Login via database + Session

... text ...

Access rights

... text ...

[wiki] Yii v2 snippet guide

$
0
0
  1. Intro
  2. Prerequisities
  3. Yii demo app + GitLab
  4. User management + DB creation + login via DB
  5. i18n translations
  6. Switching languages + session + dropdown in the top menu
  7. Access rights

Intro

Hi all!

This snippet guide continues in my series of simple Yii tutorials. Previous two contain basic info about MVC concept so read them as well, but they are meant for Yii v1. I started with them cca 8 years ago:

... and today I am beginning with Yii 2 so I will also gather my snippets and publish them here so we all can quickly setup the yii-basic-demo just by copying and pasting. This is my goal - to show how-to without long descriptions.

... technologies should not require users to study them deeply in order to run basic functionalities. Ordinary things should be copied and pasted so that one is happy that it works and thus motivated to study more ...

I have 4 years of experiences with Yii 1, but I havent used it for almost 5 years so many things in Yii 2 are new for me again. Plus I was suprised that the Yii 2 demo application does not contain some basic functionalities (like login via DB, translations etc) which must be implemented in the most of web projects so I will focus on them. Plus I will talk about GitLab.

If you find any problems in my snippets, let me know, please.

Prerequisities

Skip this paragraph if you know how to run your Yii demo project...

I work with Win10 + XAMPP Server so I will expect this configuration. Do not forget to start the server and enable Apache + MySQL in the dialog. Then test that following 2 URLs work for you

You should also download the Yii basic demo application and place it into the htdocs folder. In my case it is here:

  • C:\xampp\htdocs

And your index.php should be here:

  • C:\xampp\htdocs\basic\web\index.php

If you set thing correcly up, following URL will open your demo application. Now it will probably throw an exception:

The Exception is removed by enterinng any text into attribute 'cookieValidationKey' in file:

  • C:\xampp\htdocs\basic\config\web.php

Dont forget to connect Yii to the DB. It is done in file:

  • C:\xampp\htdocs\basic\config\db.php

... but it should work out-of-the-box if you use DB name "yii2basic" which is also used in examples below ...

Yii demo app + GitLab

Once I know more about GitLab I will add some info ... for example automatical copying from GitLab to your target web space.

Once you download and run the basic app, I recommend to push it into GitLab. You will probably need a SSH certificate which can be generated like this using PuTTYgen. When I work with Git I use TortoiseGIT which integrates all git functionalities into the context menu in Windows File Explorer.

First go to GitLab web and create a new project. Then you might need to fight a bit, because the process of connecting your PC to GIT seems to be quite complicated. At least for me.

Once things work, just create an empty folder, right click it and select Git Clone. Enter your git path, best is this format:

When cloned, copy the content of the "basic" folder into the new empty git-folder and push everything except for folder "vendor". (It contains 75MB and 7000 files so you dont want to have it in GIT)

Then you can start to modify you project, for example based on this "tutorial".

User management + DB creation + login via DB

To create DB with users, use following command. I recommend charset utf8_unicode_ci (or utf8mb4_unicode_ci) as it allows you to use more international characters.

CREATE DATABASE IF NOT EXISTS `yii2basic` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(45) NOT NULL,
  `password` VARCHAR(60) NOT NULL,
  `email`    VARCHAR(60) NOT NULL,
  `authKey`  VARCHAR(60),
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

INSERT INTO `user` (`id`, `username`, `password`, `email`, `authKey`) VALUES (NULL, 'user01', '0497fe4d674fe37194a6fcb08913e596ef6a307f', 'user01@gmail.com', NULL);

If you must use MyISAM instead of InnoDB, just change the word InnoDB into MYISAM.

Then replace existing model User with following snippet

  • The model was generated by Gii and originally had 3 methods: tableName(), rules(), attributeLabels()
  • In order to use the DB for login, we needed to implement IdentityInterface which requires 5 new methods.
  • Plus we add 2 methods because of the default LoginForm and 1 validator.
<?php

namespace app\models;

use Yii;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {

    // When user detail is being edited we will only modify attribute password_new
    // Why? We dont want to load password-hash from DB and display it to the user
    // We only want him to see empty field and if it is filled in, password is changed on background
    public $password_new;
    public $password_new_repeat;

    // Use this scenario in UserController->actionCreate() right after: $model = new User() like this:
    // $model->scenario = User::SCENARIO_CREATE;
    // This will force the user to enter the password when new user is created
    // When user is edited, new password is not needed
    const SCENARIO_CREATE = "user-create";

    // ----- Default 3 model-methods by GII:

    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'email'], 'required'],
            [['password_new_repeat', 'password_new'], 'required', "on" => self::SCENARIO_CREATE],
            [['username', 'email'], 'string', 'max' => 45],
            ['email', 'email'],
            [['password', 'authKey'], 'string', 'max' => 60],
            [['password', 'password_new_repeat', 'password_new'], 'safe'],
            ['password_new_repeat', 'compare', 'operator' => '==', 'compareAttribute' => 'password_new'],
            ['password_new_repeat', 'setPasswordWhenChanged'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', 'Username'),
            'password' => Yii::t('app', 'Password'),
            'password_new' => Yii::t('app', 'New password'),
            'password_new_repeat' => Yii::t('app', 'Repeat new password'),
            'authKey' => Yii::t('app', 'Auth Key'),
            'email' => Yii::t('app', 'Email'),
        ];
    }

    // ----- Password validator

    public function setPasswordWhenChanged($attribute_name, $params) {

        if (trim($this->password_new_repeat) === "") {
            return true;
        }

        if ($this->password_new_repeat === $this->password_new) {
            $this->password = sha1($this->password_new_repeat);
        }

        return true;
    }

    // ----- IdentityInterface methods:

    public static function findIdentity($id) {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        return static::findOne(['access_token' => $token]);
    }

    public function getId() {
        return $this->id;
    }

    public function getAuthKey() {
        return $this->authKey;
    }

    public function validateAuthKey($authKey) {
        return $this->authKey === $authKey;
    }

    // ----- Because of default LoginForm:

    public static function findByUsername($username) {
        return static::findOne(['username' => $username]);
    }

    public function validatePassword($password) {
        return $this->password === sha1($password);
    }

}

Validators vs JavaScript:

  • There are 2 types of validators. All of them are used in method rules, but as you can see, the validator setPasswordWhenChanged is my custom validator and needs a special method. (I just abused a validator to set the password value, no real validation happens inside)
  • If a validator does not need this special method, it is automatically converted into JavaScript and is used on the web page when you are typing.
  • If a validator needs the method, it cannot be converted into JavaScript so the rule is checked only in the moment when user sends the form to the server - after successful JavaScript validation.

Now you can also create CRUD using GII:

CRUD = Create Read Update Delete = views and controller. On the GII page enter following values:

  • Model Class = app\models\User
  • Search Model Class = app\models\UserSearch
  • Controller Class = app\controllers\UserController
  • View Path can be empty or you can set: views\user
  • Again enable i18n

And then you can edit users on this URL: http://localhost/basic/web/index.php?r=user ... but it is not all. You have to modify the view-files so that correct input fields are displayed!

Open folder views\user and do following:

  • _form.php - rename input password to password_new then duplicate it and rename to password_new_repeat. Remove authKey.
  • _search.php - remove password and authKey.
  • index.php - remove password and authKey.
  • view.php - remove password and authKey.

Plus do not forget to use the new scenario in UserController->actionCreate() like this:

public function actionCreate()
{
  $model = new User();
  $model->scenario = User::SCENARIO_CREATE; // the new scenario!
  // ...

i18n translations

Translations are fairly simple, but I probably didnt read manuals carefully so it took me some time.

First create following folders and file.

  • "C:\xampp\htdocs\basic\messages\cs-CZ\app.php"

(Note that cs-CZ is for Czech Lanuage. For German you should use de-DE etc. Use any other language if you want.)

The idea behind is that in the code ther are used only English texts and if you want to change from English to some other language this file will be used.

Now go to file config/web.php, find section "components" and paste this code:

    'components' => [
        'i18n' => [
          'translations' => [
            '*' => [
              'class' => 'yii\i18n\PhpMessageSource',
              'basePath' => '@app/messages',
              'sourceLanguage' => 'en-US',
              'fileMap' => [
                'app' => 'app.php'
              ],
            ],
          ],
        ], // end of 'i18n'

        // ... other configurations

    ], // end of 'components'
    

Explanation of the asterisk * can be found in article https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n

You surely saw that in views and models there are texts saved like this:

Yii::t('app', 'New password'),

It means that this text belongs to category "app" and its English version (and also its ID) is "New password". So this ID will be searched in the file you just created. In my case it was the Czech file:

  • "C:\xampp\htdocs\basic\messages\cs-CZ\app.php"

Therefore open the file and paste there following code:

<?php
return [
    'New password' => 'Nové heslo',
];
?>

Now you can open the page for adding a new user and you will see than so far nothing changed :-)

We must change the language ... For now let's do it in a primitive and permanent way again in file config/web.php

$config = [
    // use your language
    // also accessible via Yii::$app->language
    'language' => 'cs-CZ',
    
    // This attribute is not necessary.
    // en-US is default value
    'sourceLanguage' => 'en-US',
    
    // ... other configs

Switching languages + session + dropdown in the top menu

First lets add to file config/params.php attributes with list of supported languages:

<?php
return [
    // ...
    'allowedLanguages' => [
        'en-US' => "English",
        'cs-CZ' => "Česky",
    ],
    'langSwitchUrl' => '/site/set-lang',
];

This list can be displayed in the main menu. Edit file:

  • C:\xampp\htdocs\basic\views\layouts\main.php

And above the Nav::widget add few rows:

    $listOfLanguages = [];
    $langSwitchUrl = Yii::$app->params["langSwitchUrl"];
    foreach (Yii::$app->params["allowedLanguages"] as $langId => $langName) {
        $listOfLanguages[] = ['label' => Yii::t('app', $langName), 'url' => [$langSwitchUrl, 'langID' => $langId]];
    }

and then add one item into Nav::widge

    echo Nav::widget([
        // ...
        'items' => [
            // ...
            ['label' => Yii::t('app', 'Language'),'items' => $listOfLanguages],
            // ...

Now in the top-right corner you can see a new drop-down-list with list of 2 languages. If one is selected, action "site/setLang" is used so we have to create it in SiteController.

Note that this approach will always redirect user to the new action and his work will be lost. Nevertheless this approach is very simple so I am using it in small projects. More complex projects may require an ajax call when language is changed and then updating texts using javascript so reload is not needed and user's work is preserved. But I expect that when someone opens the web, he/she sets the language immediately and then there is no need for further changes.

The setLang action looks like this:

    public function actionSetLang($langID = "") {
        $allowedLanguages = Yii::$app->params["allowedLanguages"];
        $langID = trim($langID);
        if ($langID !== "" && array_key_exists($langID, $allowedLanguages)) {
            Yii::$app->session->set('langID', $langID);
        }
        return $this->redirect(['site/index']);
    }

As you can see when the language is changed, redirection to site/index happens. Also mind that we are not modifying the attribute from config/web.php using Yii::$app->language, but we are saving the value into the session. The reason is that PHP deletes memory after every click, only session is kept.

We then can use the langID-value in other controllers using new method beforeAction:

    public function beforeAction($action) {

        if (!parent::beforeAction($action)) {
            return false;
        }

        Yii::$app->language = Yii::$app->session->get('langID');

        return true;
    }

.. or you can create one parent-controller named for example BaseController. All other controllers will extend it.

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;

class BaseController extends Controller {

    public function beforeAction($action) {

        if (!parent::beforeAction($action)) {
            return false;
        }

        Yii::$app->language = Yii::$app->session->get('langID');

        return true;
    }

}

As you can see in the snippet above, other controllers must contain row "use app\controllers\BaseController" + "extends BaseController"

Access rights

... text ...


[extension] bizley/yii2-mercure

$
0
0

yii2-mercure

  1. Mercure Publisher as Yii 2 component
  2. What is Mercure?
  3. Installation
  4. Configuration
  5. Configuration Details
  6. Usage
  7. Client subscribing using JavaScript
  8. Discovery
  9. Authorization

Latest Stable VersionTotal Downloads License

Mercure Publisher as Yii 2 component

This package provides component to publish updates to the Mercure hub for Yii 2 framework.

What is Mercure?

Quoting dunglas/mercure: > Mercure is a protocol allowing to push data updates to web browsers and other HTTP clients in a convenient, fast, > reliable and battery-efficient way. It is especially useful to publish real-time updates of resources served through > web APIs, to reactive web and mobile apps.

See the linked repository to find out more about Mercure. There are also instructions how to set up the server and the client to establish connection using Mercure protocol.

Installation

Add the package to your composer.json:

{
    "require": {
        "bizley/yii2-mercure": "^1.0"
    }
}

and run composer update or alternatively run composer require bizley/yii2-mercure:^1.0

You will of course need Mercure Hub as well. Refer to dunglas/mercure for the instructions how to get one (I recommend using Docker image).

Configuration

Add the following in your configuration file:

'components' => [
    'mercure' => [
        'class' => \bizley\yii2\mercure\Publisher::class,
        'hubUrl' => 'http://mercure.local/hub', // URL of the Mercure hub
        'jwt' => '...', // string or anonymous function returning string with JWT (see details below)
        'httpClient' => '...', // HTTP client (see details below)
        'useYii2Client' => true, // HTTP client mode (see details below)            
    ],
],

Configuration Details

  • hubUrl The URL of Mercure hub.
  • jwt JSON Web Token or anonymous function returning it. See Authorization section to learn more.
  • httpClient String with the name of the registered HTTP client component, an array with the HTTP client configuration, or actual HTTP client object. When useYii2Client option is set to true (default) this option is expected to point to Yii 2 HTTP client component. If you want to use it you must install it like described in the link provided and register it in the configuration (so you can set it as 'httpClient' => 'name-of-the-client-component') or provide array configuration for it (like 'httpClient' => ['class' => \yii\httpclient\Client::class]).
  • useYii2Client Boolean flag indicating whether this component should expect Yii 2 HTTP client as HTTP client (true by default) or other custom HTTP client (false).

Usage

The application must bear a JSON Web Token (JWT) to the Mercure Hub to be authorized to publish updates.

This JWT should be stored in the jwt property mentioned earlier.

The JWT must be signed with the same secret key as the one used by the Hub to verify the JWT (default Mercure demo key is !ChangeMe! - not to be used on production). Its payload must contain at least the following structure to be allowed to publish:

{
    "mercure": {
        "publish": []
    }
}

Because the array is empty, the app will only be authorized to publish public updates (see the Authorization section for further information).

TIP: The jwt.io website is a convenient way to create and sign JWTs. Checkout this example JWT, that grants publishing rights for all targets (notice the star in the array). Don't forget to set your secret key properly in the bottom of the right panel of the form!

When you want to publish update to the Mercure hub simply call

\Yii::$app->mercure->publish($update);

where $update is an instance of \bizley\yii2\mercure\Update class. For example:

\Yii::$app->mercure->publish(
    new \bizley\yii2\mercure\Update(
        'http://example.com/books/1',
        \yii\helpers\Json::encode(['status' => 'OutOfStock'])
    )
);

The first parameter to pass to the Update constructor is the topic being updated. This topic should be an IRI (Internationalized Resource Identifier, RFC 3987): a unique identifier of the resource being dispatched.

Usually, this parameter contains the original URL of the resource transmitted to the client, but it can be any valid IRI, it doesn't have to be an URL that exists (similarly to XML namespaces).

The second parameter of the constructor is the content of the update. It can be anything, stored in any format. However, serializing the resource in a hypermedia format such as JSON-LD, Atom, HTML or XML is recommended.

Client subscribing using JavaScript

const eventSource = new EventSource(
    'http://localhost:3000/hub?topic=' + encodeURIComponent('http://example.com/books/1')
);
eventSource.onmessage = event => {
    // Will be called every time an update is published by the server
    console.log(JSON.parse(event.data));
}

Mercure also allows to subscribe to several topics, and to use URI Templates as patterns:

// URL is a built-in JavaScript class to manipulate URLs
const url = new URL('http://localhost:3000/hub');
url.searchParams.append('topic', 'http://example.com/books/1');
// Subscribe to updates of several Book resources
url.searchParams.append('topic', 'http://example.com/books/2');
// All Review resources will match this pattern
url.searchParams.append('topic', 'http://example.com/reviews/{id}');

const eventSource = new EventSource(url);
eventSource.onmessage = event => {
    console.log(JSON.parse(event.data));
}

Discovery

The Mercure protocol comes with a discovery mechanism. To leverage it, the application must expose the URL of the Mercure Hub in a Link HTTP header.

namespace app\controllers;

use yii\web\Controller;

class BookController extends Controller
{
    public function actionView($id)
    {
        $hubUrl = 'http://localhost:3000/hub';

        $response = $this->asJson([
            '@id' => '/books/' . $id,
            'availability' => 'https://schema.org/InStock',
        ]);
        $response->getHeaders()->set('Link', "<$hubUrl>; rel=mercure");
        
        return $response;
    }
}

Then, this header can be parsed client-side to find the URL of the Hub, and to subscribe to it:

// Fetch the original resource served by the web API
fetch('/books/1') // Has Link: <http://localhost:3000/hub>; rel=mercure
    .then(response => {
        // Extract the hub URL from the Link header
        const hubUrl = response.headers.get('Link').match(/<([^>]+)>;\s+rel=(?:mercure|"[^"]*mercure[^"]*")/)[1];

        // Append the topic(s) to subscribe as query parameter
        const hub = new URL(hubUrl);
        hub.searchParams.append('topic', 'http://example.com/books/{id}');

        // Subscribe to updates
        const eventSource = new EventSource(hub);
        eventSource.onmessage = event => console.log(event.data);
    });

Authorization

Mercure also allows to dispatch updates only to authorized clients. To do so, set the list of targets allowed to receive the update as the third parameter of the Update constructor:

\Yii::$app->mercure->publish(
    new \bizley\yii2\mercure\Update(
        'http://example.com/books/1',
        \yii\helpers\Json::encode(['status' => 'OutOfStock']),
        ['http://example.com/user/kevin', 'http://example.com/groups/admin'] // Here are the targets
    )
);

Publisher's JWT must contain all of these targets or * in mercure.publish or you'll get a 401.
Subscriber's JWT must contain at least one of these targets or * in mercure.subscribe to receive the update.

To subscribe to private updates, subscribers must provide a JWT containing at least one target marking the update to the Hub.

To provide this JWT, the subscriber can use a cookie, or a Authorization HTTP header. Cookies are automatically sent by the browsers when opening an EventSource connection. They are the most secure and preferred way when the client is a web browser. If the client is not a web browser, then using an authorization header is the way to go.

In the following example controller, the generated cookie contains a JWT, itself containing the appropriate targets. This cookie will be automatically sent by the web browser when connecting to the Hub. Then, the Hub will verify the validity of the provided JWT, and extract the targets from it.

To generate the JWT, we'll use the bizley/jwt which is Yii 2 component with lcobucci/jwt library. Install it:

composer require bizley/jwt

and configure:

'components' => [
    'jwt' => [
        'class' => \bizley\jwt\Jwt::class,
        'key' => '!ChangeMe!' // default Mercure demo key not to be used on production
    ],
],

Now the controller:

namespace app\controllers;

use bizley\jwt\JWT;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Yii;
use yii\web\Controller;
use yii\web\Cookie;
    
class BookController extends Controller
{
    public function actionView($id)
    {
        $hubUrl = 'http://localhost:3000/hub';
        
        $username = Yii::$app->user->name; // Retrieve the username of the current user
        
        $token = Yii::$app->jwt->getBuilder()
            // set other appropriate JWT claims, such as an expiration date
            ->set(
                'mercure',
                ['subscribe' => ["http://example.com/user/$username"]]
                // could also include the security roles, or anything else
            )
            ->sign(new Sha256(), Yii::$app->jwt->key)
            ->getToken();
                
        $response = $this->asJson([
            '@id' => '/books/' . $id,
            'availability' => 'https://schema.org/InStock',
        ]);
        $response->getHeaders()->set('Link', "<$hubUrl>; rel=mercure");
        $response->cookies->add(new Cookie([
            'name' => 'mercureAuthorization',
            'value' => $token,
            'path' => '/hub',
            'secure' => true,
            'sameSite' => Cookie::SAME_SITE_STRICT, // from PHP 7.3 and Yii 2.0.21
        ]));
        
        return $response;
    }
}

NOTE: To use the cookie authentication method, the app and the Hub must be served from the same domain (can be different sub-domains).

Some parts of this documentation are copied from Symfony's "Pushing Data to Clients Using the Mercure Protocol" page.

[extension] bizley/mercure-behavior

$
0
0

mercure-behavior

  1. Yii 2 Mercure behavior
  2. What is Mercure?
  3. Installation
  4. Usage
  5. Publishing the updates

Latest Stable VersionTotal Downloads License

Yii 2 Mercure behavior

This package provides Yii 2 behavior to automatically publish updates to the Mercure hub when resource is being modified.
The purpose of this behavior is to equip Yii application with the same Mercure functionality as given by API Platform.

What is Mercure?

Quoting dunglas/mercure: > Mercure is a protocol allowing to push data updates to web browsers and other HTTP clients in a convenient, fast, > reliable and battery-efficient way. It is especially useful to publish real-time updates of resources served through > web APIs, to reactive web and mobile apps.

See the linked repository to find out more about Mercure. There are also instructions how to set up the server and the client to establish connection using Mercure protocol.

Installation

Add the package to your composer.json:

{
    "require": {
        "bizley/mercure-behavior": "^1.0"
    }
}

and run composer update or alternatively run composer require bizley/mercure-behavior:^1.0

You will of course need Mercure Hub as well. Refer to dunglas/mercure for the instructions how to get one (I recommend using Docker image).

Usage

Add this behavior to the resource object you want to be subject of Mercure updates (usually it's an Active Record instance).

use \bizley\yii2\behaviors\mercure\MercureBehavior;

public function behaviors()
{
    return [
        MercureBehavior::class,
    ];
}

Resource object must implement \bizley\yii2\behaviors\mercure\MercureableInterface.
By default MercureBehavior will dispatch update to Mercure Hub in JSON format after the resource has been successfully created, updated, or deleted, using the Mercure publisher component registered under the 'publisher' name.

You can customize the configuration according to your needs, for example:

public function behaviors()
{
    return [
        [
            'class' => MercureBehavior::class,
            'publisher' => \bizley\yii2\mercure\Publisher::class,
            'format' => \yii\web\Response::FORMAT_XML
        ]
    ];
}

Publishing the updates

The behavior is using yii2-mercure package for publishing the updates.
Please follow the repository link to learn how to configure it properly.

[extension] raspina

$
0
0

http://raspina-cms.ir/

Powered by Yii2 The Fast, Secure and Professional PHP Framework. Yii is a high-performance PHP framework best for developing Web 2.0 applications.

Open Source Raspina is an free and open source project that is licensed under BSD 3.

Multi Language Allows you easily use english, russian and persian languages. You can add your own language.

Transparent, Reliable and Extensible you can easily develop the functionality of your website.

[extension] rsr/yii2-check-deps

$
0
0

yii2-check-deps

  1. Installation
  2. Usage
  3. Resources

Check for new migrations/dependencies of Yii 2 application when in development mode and apply them if user asked to.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --dev rsr/yii2-check-deps

or add

"rsr/yii2-check-deps" : "*"

to the require-dev section of your composer.json file.

Usage

Add the following to yii2 config/web.php file:

...
if (YII_ENV_DEV) {
    ... 
    $config['bootstrap'][] = 'checkDeps';
    $config['components']['checkDeps'] = [
        'class' => rsr\yii2\checkDeps\CheckDeps::class
    ];
    ...
}
...
return $config;

Resources

[extension] solutosoft/yii-linkmany

$
0
0

Yii LinkMany

  1. Installation
  2. Usage
  3. Credits

Load, validate and save automatically hasMany relations.

Build Status Scrutinizer Code Quality Code Coverage Total Downloads Latest Stable Version

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist solutosoft/yii-linkmany

or add

"solutosoft/yii-linkmany": "*"

to the require section of your composer.json.

Usage

This extension provides support for ActiveRecord hasMany relation saving. This support is granted via \solutosoft\linkmany\LinkManyBehavior ActiveRecord behavior. You'll need to attach it to your ActiveRecord class and point the target "has-many" relation for it:

class Post extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'linkManyBehavior' => [
                'class' => LinkManyBehavior::class,
                'relations' => [
                    'tags',
                    'messages' => [
                        'formName'  => 'Post[messages]',
                        'validate' => false,
                        'deleteOnUnlink' => false
                    ]
                ]
            ],
        ];
    }

    public function getMessages()
    {
        return $this->hasMany(Message::class, ['post_id' => 'id']);
    }

    public function getTags()
    {
        return $this->hasMany(Tag::class, ['id' => 'tag_id'])
            ->viaTable('post_tag', ['post_id' => 'id']);
    }
}

Being attached \solutosoft\linkmany\LinkManyBehavior you can load data using the method \solutosoft\linkmany\LinkManyBehavior::fill

use yii\web\Controller;

class PostController extends Controller
{
    public function actionCreate()
    {
        $model = new Post();

        if ($model->fill(Yii::$app->request->post())) {
            $model->save(); // save the model and relations
            return $this->redirect(['view']);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

Credits

This Package is inspired by:

I wanted to have a combination of both. Thanks to both authors.

[news] MongoDB extension 2.1.8 released

$
0
0

We are very pleased to announce the release of MongoDB extension version 2.1.8 that fixes Session component compatibility with Yii 2.0.17+.

[news] HTTP client extension 2.0.12 released

$
0
0

We are very pleased to announce the release of HTTP client extension version 2.0.12.

This release adds an ability to get time elapsed from request to response via Request::responseTime().

See the CHANGELOG for details.


[news] Bootstrap 4 extension version 2.0.8 released

[news] Yii 2.0.28

$
0
0

We are very pleased to announce the release of Yii Framework version 2.0.28. Please refer to the instructions at https://www.yiiframework.com/download/ to install or upgrade to this version.

Version 2.0.28 is a minor release of Yii 2.0. This release includes important security and PHP 7 compatibility fixes.

Thanks to all Yii community members who contribute to the framework, translators who keep documentation translations up to date and community members who answer questions at forums.

There are many active Yii communities so if you need help or want to share your experience, feel free to join them.

A complete list of changes can be found in the CHANGELOG.

[extension] vkabachenko/yii2-filepond

$
0
0

Filepond Yii2 extension

  1. Installation
  2. Usage

This extension allows you to use Filepond upload js library as a widget in yii2 projects.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require  vkabachenko/yii2-filepond

or add

"vkabachenko/yii2-filepond": "dev-master"

to the require section of your composer.json file.

Usage

Add the extension to the module section in your config file

    'modules' => [
       'filepond' => [
           'class' => \vkabachenko\filepond\Module::class
       ]
    ],

After that you can use Filepond library to upload files in your project.

Single file upload without model

Single file upload with model

Multiple files upload without model

Multiple files upload with model

Filepond options

Filepond options described at the documentation can be set by setting instanceOptions or settingsOptions.

This is the preferred way:

    <?= FilepondWidget::widget([
            'name' => 'file',
            'instanceOptions' => [
                'required' => true,
                'maxFiles' => 10,
                ... other options ...
            ]
         ]);
    ?>
Filepond plugins

If you want to add some of filepond plugins to the widget, set the allow plugin option to true. For example, to add file type validation plugin set allowFileSizeValidation:

    <?= FilepondWidget::widget([
            'name' => 'file',
            'instanceOptions' => [
                'allowFileSizeValidation' => true,
                'maxFileSize' => '10M',
                ... other options ...
            ]
         ]);
    ?>
Validation

Only client-side validation is available. This kind of validation is the part of filepond library. You can add file size and file type validation. Example of file type validation:

    <?= FilepondWidget::widget([
            'name' => 'file',
            'instanceOptions' => [
                'allowFileTypeValidation' => true,
                'acceptedFileTypes' => ['image/*']
            ]
                ... other options ...
            ]
         ]);
    ?>
Localization

Original library isn't localized and has only english labels. This widget has russian translations too. To apply the localization you have to set language option in Yii settings or directly in the widget:

    <?= FilepondWidget::widget([
            'name' => 'file',
            'language' => 'ru-RU'
         ]);
    ?>

[extension] kekaadrenalin/yii2-module-recaptcha-v3

$
0
0

Total Downloads

Yii2 reCAPTCHA v3

  1. Installation
  2. Usage
  3. For tests

Adds recaptcha-v3 into yii2 project

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist kekaadrenalin/yii2-module-recaptcha-v3 "*"

or add

"kekaadrenalin/yii2-module-recaptcha-v3": "*"

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your code by :

add this to your components main.php

'components' => [
    ...
    'reCaptcha3' => [
        'class'      => 'kekaadrenalin\recaptcha3\ReCaptcha',
        'site_key'   => 'site_key_###',
        'secret_key' => 'secret_key_###',
    ],

and in your model

acceptance_score the minimum score for this request (0.0 - 1.0) or null

public $reCaptcha;
 
public function rules()
{
 	return [
 		...
 		 [['reCaptcha'], \kekaadrenalin\recaptcha3\ReCaptchaValidator::className(), 'acceptance_score' => 0]
 	];
}
<?= $form->field($model, 'reCaptcha')->widget(\kekaadrenalin\recaptcha3\ReCaptchaWidget::class) ?>

For tests

When use `YII_ENV_TESTinindex-test.phpthen disabled recaptcha's validate:php defined('YII_ENV') or define('YII_ENV', 'test'); `

[extension] kekaadrenalin/yii2-imap

$
0
0

yii2 Imap

Total Downloads

This library is a fork of https://github.com/yiioverflow/yii2-imap

Installation by composer

{
    "require": {
       "kekaadrenalin/yii2-imap": "dev-master"
    }
}

Or

$ composer require kekaadrenalin/yii2-imap "dev-master"

Use as compnent

Connection details define in component

'components' => [
      ...
      'imap' => [
         'class' => 'kekaadrenalin\imap\Imap',
         'connection' => [
              'imapPath' => '{imap.gmail.com:993/imap/ssl}INBOX',
              'imapLogin' => 'username',
              'imapPassword' => 'password',
              'serverEncoding'=>'encoding', // utf-8 default.
              'attachmentsDir'=>'/'
        ],
    ],
    ...
 ],


//4th Param _DIR_ is the location to save attached files 
//Eg: /path/to/application/mail/uploads.
$mailbox = new kekaadrenalin\Mailbox(yii::$app->imap->connection);

Usage as library

Connection details set on fly


$imapConnection = new kekaadrenalin\imap\ImapConnection

$imapConnection->imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$imapConnection->imapLogin = 'username';
$imapConnection->imapPassword = 'password';
$imapConnection->serverEncoding = 'encoding'; // utf-8 default.
$imapConnection->attachmentsDir = '/';


//4th Param _DIR_ is the location to save attached files 
//Eg: /path/to/application/mail/uploads.
$mailbox = new kekaadrenalin\Mailbox($imapConnection);

To get all mails and its index

$mailbox->searchMailBox(ALL)// Prints all Mail ids.
print_r($mailIds);

Do not read attachments

$mailbox->readMailParts = false;

To read Inbox contents

foreach($mailIds as $mailId)
{
    // Returns Mail contents
    $mail = $mailbox->getMail($mailId); 

    if(alreadyProcesedMessage($mail->messageId)){
        continue;
    }

    // Use, if $mailbox->readMailParts = false; 
    // Read mail parts (plain body, html body and attachments
    $mail = $mailbox->getMailParts($mail);

    // Returns mail attachements if any or else empty array
    $attachments = $mail->getAttachments(); 
    foreach($attachments as $attachment){
        echo ' Attachment:' . $attachment->name . PHP_EOL;
        
        // Delete attachment file
        unlink($attachment->filePath);

    }
}

To Mark and delete mail from IMAP server.

//Mark a mail to delete</span></span> 
$mailbox->deleteMail($mailId); // Deletes all marked mails
$mailbox->expungeDeletedMails();

Contribute

Feel free to contribute. If you have ideas for examples, add them to the repo and send in a pull request.

Apreciate

Dont forgett o Leave me a "star" if you like it. Enjoy coding!

Viewing all 2940 articles
Browse latest View live