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

[extension] yiisoft/yii2-rest

$
0
0

993323

REST Extension for Yii 2


This extension provides the REST API for the Yii framework 2.1.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-rest

or add

"yiisoft/yii2-rest": "~1.0.0"

to the require section of your composer.json.


[wiki] Configuring PhpStorm IDE for Yii 2

$
0
0

There are a few settings and plugins that can enhance the development experience with Yii in PHPStorm or IntelliJ IDEA. This article explains how to get the most out of your IDE.

This arcticle is valid for Yii 2 and above, there is an older article for Yii 1.1.

Plugins

  • Yii2 Support adds many useful tools that improve working with Yii. It makes working with class configuration, DI and views easier.

  • Yii2 Inspections is a very useful plugin that adds Yii specific code inspections to PHPStorm. It helps for example to manage @property annotations for getters and setters as well as translation messages.

  • Php Inspections (EA Extended) is not directly Yii related but has a lot of additional code inspections that help you write better code. There is also a payed version that has even more features, especially security related inspections.

Project Setup

  • Exclude runtime directories from code search. Debug toolbar stores a lot of stuff that clutters search results.

    runtime - right click - Mark Directory As - Excluded

  • Enable composer integration to tell PHPStorm to separate vendor files from project files.

    composer.json - right click - Composer - Init Composer ...

PHPUnit and Codeception

PHPStorm has integrations for PHPUnit as well as Codeception, so you can run your tests directly from the IDE.

Settings for that can be found at Run - Edit Configurations....

To add your Codeception tests, click the + button, select Codeception. Then enter the following details:

  • Name: "Codeception tests" - or whatever you want to name it
  • Test Scope: Defined in the Configuration file
  • Use alternative configuration file: "codeception.yml"
  • In case PHPStorm asks you to do it, configure a PHP Interpreter in PHPStorm settings
  • Configure Codeception binary as vendor/bin/codecept

You can now run your tests directly from PHPStorm.

For PHPUnit the steps are similar but Yii application templates do not provide PHPUnit tests by default so the options depend on your setup.

[extension] kosoukhov/ldap

$
0
0

Yii2 extension for LDAP

  1. Installation
  2. Application configuration example:
  3. Usage example:

Authorize, search users, get user groups and other from LDAP

Yii2 Latest Stable Version Total Downloads Latest Unstable Version License

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist kosoukhov/ldap

or add

"kosoukhov/ldap": "*"

to the require section of your composer.json file.

Application configuration example:

In config/main.php add:
`php return [

'components' => [
    'ldap' => [
        'class' => 'kosoukhov\ldap\Connector',
        'useCache' => YII_ENV_DEV ? false : true,
    ],
],
// ...

]; `

In config/main-local.php add:

return [
    'components' => [
        'ldap' => [
            'host' => 'ldap.example.com',
            'port' => '389',
            'baseDN' => 'OU=...,DC=...,DC=...,DC=net',
            'userDN' => '@....corp.net',
            'groupDN' => '',
            //Input your AD login/pass on dev or sys login/pass on test/prod servers
            'sysUserLogin' => '',
            'sysUserPassword' => '',
        ],
    ],
    // ...
];

Usage example:

if (!Yii::$app->ldap->validateUserCredentials('SAMAccountName', 'password')) {
    throw new ErrorException('Incorrect username or password.');
}
echo Yii::$app->ldap->getUserAttributesBySAMAccountName('SAMAccountName', ['mail', 'sn', 'givenname', 'middlename']);
echo kosoukhov\ldap\widgets\UserImage::widget([
    'login' => Yii::$app->user->identity->username,
    'options' => [
        'class' => 'img-circle',
        'alt' => 'User Image',
    ]
]);

[extension] antkaz/yii2-ajax

$
0
0

yii2-ajax

This extension allows you to create forms in the Twitter Bootstrap modal window.

Installation

The preferred way to install this extension is through composer.

Run

php composer.phar require antkaz/yii2-ajax

or add

"antkaz/yii2-ajax": "dev-master"

to the require section of your composer.json file.

Usage

1 Register asset bundle with a view by calling the antkaz\ajax\modalBundle::register() method. For example:

<?php
use antkaz\ajax\ModalBundle;
ModalBundle::register($this); // $this represents the view object
?>

2 Аdd the modal widget to your view file:

<?= yii\bootstrap\Modal::widget([
    'id' => 'modal',
]); ?>

3 Add a link that will open the modal window:

<?= \yii\helpers\Html::a('Create', ['create'], [
    'class' => 'btn btn-success',
    'data-toggle' => 'ajax-modal', // outputs the result to the modal window
    'data-target' => '#modal', // ID modal
    'data-title' => 'Create item' // custom modal title
]); ?>

4 Add the data-ajax attribute in the ActiveForm options:

<?php $form = ActiveForm::begin([
    'options' => [
        'data-ajax' => 1
    ],
]); ?>

// . . .

<?php ActiveForm::end() ?>

5 Create an action in your controller that will handle this request:

public function actionCreate()
{
    $model = new Model();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['index']);
    }

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

}

protected function renderView($view, $params = [])
{
    if (Yii::$app->request->isAjax) {
        return $this->renderAjax($view, $params);
    }
    return $this->render($view, $params);
}

[extension] antkaz/yii2-vue

$
0
0

68747470733a2f2f7675656a732e6f72672f696d616765732f6c6f676f2e706e67

Vue.js Extension for Yii2


This is the Vue.js extension for Yii2.

Installation

The preferred way to install this extension is through composer.

Run

php composer.phar require antkaz/yii2-vue

or add

"antkaz/yii2-vue": "~1.0"

to the require section of your composer.json file.

Usage

After installing the extension, just use it in your code:

<?php

use antkaz\vue\Vue;
use \yii\web\JsExpression;
?>
<div class="vue">
    <?php Vue::begin([
        'clientOptions' => [
            'data' => [
                'message' => 'Hello Vue!'
            ],
            'methods' => [
                'reverseMessage' => new JsExpression("function() {this.message = this.message.split('').reverse().join('')}")
            ]
        ]
    ]) ?>

    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">Reverse Message</button>

    <?php Vue::end() ?>
</div>

Alternative method without using a widget:

<?php

use antkaz\vue\VueAsset;
VueAsset::register($this); // register VueAsset
?>

<div id="app" class="vue">

    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">Reverse Message</button>

</div>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Hello Vue.js!'
        },
        methods: {
            reverseMessage: function () {
                this.message = this.message.split('').reverse().join('')
            }
        }
    })
</script>

[extension] yiisoft/yii2-jquery

$
0
0

70142

JQuery Extension for Yii 2


This extension provides the JQuery for the Yii framework 2.1.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-jquery

or add

"yiisoft/yii2-jquery": "~1.0.0"

to the require section of your composer.json.

[extension] yiisoft/yii2-captcha

$
0
0

993323

CAPTCHA Extension for Yii 2


This extension provides the CAPTCHA for the Yii framework 2.1.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-captcha

or add

"yiisoft/yii2-captcha": "~1.0.0"

to the require section of your composer.json.

[extension] yiisoft/yii2-mssql

$
0
0

6154722

MSSQL Server Extension for Yii 2


This extension provides the MSSQL Server support for the Yii framework 2.1.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-mssql

or add

"yiisoft/yii2-mssql": "~1.0.0"

to the require section of your composer.json.


[extension] yiisoft/yii2-oracle

$
0
0

4430336

Oracle Extension for Yii 2


This extension provides the Oracle database support for the Yii framework 2.1.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-oracle

or add

"yiisoft/yii2-oracle": "~1.0.0"

to the require section of your composer.json.

[extension] cebe/yii2-gravatar

$
0
0

yii2-gravatar

  1. How to install?
  2. Usage

Gravatar Widget for Yii Framework 2

How to install?

Get it via composer by adding the package to your composer.json:

{
  "require": {
    "cebe/yii2-gravatar": "*"
  }
}

Alternatively just run composer require cebe/yii2-gravatar.

You may also check the package information on packagist.

Usage

<?= \cebe\gravatar\Gravatar::widget([
    'email' => 'mail@cebe.cc',
    'options' => [
        'alt' => 'Carsten Brandt'
    ],
    'size' => 32
]) ?>

[extension] hosannahighertech/yii2-oauth2-server

$
0
0

Yii2 Oauth2 Server

A wrapper for implementing an OAuth2 Server(https://github.com/bshaffer/oauth2-server-php). This is a fork of https://github.com/Filsh/yii2-oauth2-server. I decided to fork it after a long standing issue of branches not being resolved at original repo. There is no guarantee that the two will remain compartible so check out things to see if there is anything broke while transiting.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist hosannahighertech/yii2-oauth2-server "*"

or add

"hosannahighertech/yii2-oauth2-server": "1.0.*"

to the require section of your composer.json.

To use this extension, simply add the following code in your application configuration:

'bootstrap' => ['oauth2'],
'modules' => [
    'oauth2' => [
        'class' => 'filsh\yii2\oauth2server\Module',
        'tokenParamName' => 'accessToken',
        'tokenAccessLifetime' => 3600 * 24,
        'storageMap' => [
            'user_credentials' => 'common\models\User',
        ],
        'grantTypes' => [
            'user_credentials' => [
                'class' => 'OAuth2\GrantType\UserCredentials',
            ],
            'refresh_token' => [
                'class' => 'OAuth2\GrantType\RefreshToken',
                'always_issue_new_refresh_token' => true
            ]
        ]
    ]
]
Configure User class

1.  `public function checkUserCredentials($username, $password)` which Checks the supplied username and password for validity and returns TRUE if the username and password are valid, and FALSE if it isn't.

2. `public function getUserDetails($username)`  which returns array of the associated "user_id" and optional "scope" values something like this: 

```php
[ 
    "user_id"  => USER_ID,    // REQUIRED user_id to be stored with the authorization code or access token
    "scope"    => SCOPE       // OPTIONAL space-separated list of restricted scopes
] 

```

Additional OAuth2 Flags:

`enforceState` - Flag that switch that state controller should allow to use "state" param in the "Authorization Code" Grant Type

`allowImplicit` - Flag that switch that controller should allow the "implicit" grant type

The next step your shold run migration

```php
 yii migrate --migrationPath=@vendor/hosannahighertech/yii2-oauth2-server/migrations
```

this migration create the oauth2 database scheme and insert test user credentials ```testclient:testpass``` for ```http://fake/```

add url rule to urlManager

```php
'urlManager' => [
    'rules' => [
        'POST oauth2/<action:\w+>' => 'oauth2/rest/<action>',
        ...
    ]
]
```

Usage
-----

To use this extension,  simply add the behaviors for your base controller:

```php
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;

class Controller extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                    ['class' => HttpBearerAuth::className()],
                    ['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
                ]
            ],
            'exceptionFilter' => [
                'class' => ErrorToExceptionFilter::className()
            ],
        ]);
    }
}
```

Create action authorize in site controller for Authorization Code

`https://api.mysite.com/authorize?response_type=code&client_id=TestClient&redirect_uri=https://fake/`

```php
/**
 * SiteController
 */
class SiteController extends Controller
{
    /**
     * @return mixed
     */
    public function actionAuthorize()
    {
        if (Yii::$app->getUser()->getIsGuest())
            return $this->redirect('login');
    
        /** @var $module \filsh\yii2\oauth2server\Module */
        $module = Yii::$app->getModule('oauth2');
        $response = $module->handleAuthorizeRequest(!Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId());
    
        /** @var object $response \OAuth2\Response */
        Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON;
    
        return $response->getParameters();
    }
}
```

For More on Requests and responses as well as explanations for Oauth Grant types see excellet tutorial by Jenkov here: http://tutorials.jenkov.com/oauth2/

[see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/authorization-code/)

Also if you set ```allowImplicit => true```  you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/)

Request example:

`https://api.mysite.com/authorize?response_type=token&client_id=TestClient&redirect_uri=https://fake/cb`

With redirect response:

`https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600`

### JWT Tokens
If you want to get Json Web Token (JWT) instead of convetional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: 
`'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'OAuth2\Storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php). The Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great. Just use it and everything will be fine.

Here is a sample class for public key implementing `PublickKeyInterface`. Make sure that paths to private and public keys are correct. You can generate them with OpenSSL tool with two steps (Thanks to (Rietta)[https://rietta.com/blog/2012/01/27/openssl-generating-rsa-key-from-command/]):

1. ```openssl genrsa -des3 -out privkey.pem 2048```

2. ```openssl rsa -in privkey.pem -outform PEM -pubout -out pubkey.pem```

**Note that** you can copy contents of the files and paste the long strings in class variables. It is nasty but it works fine if that is what you want.

```php
<?php
namespace app\security\storage;

class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{


    private $pbk =  null;
    private $pvk =  null; 

    public function __construct()
    {
        $pvkText =  file_get_contents(dirname(__FILE__).'/../keys/privkey.pem');        
        $this->pvk = openssl_get_privatekey($pvkText, 'YOUR_PASSPHRASE_IF_ANY');
        
        $this->pbk =  file_get_contents(dirname(__FILE__).'/../keys/pubkey.pem'); 
    }

    public function getPublicKey($client_id = null){ 
        return  $this->pbk;
    }

    public function getPrivateKey($client_id = null){
        return  $this->pvk;
    }

    public function getEncryptionAlgorithm($client_id = null){
        return "RS256";
    }

}

``` 


For more, see https://github.com/bshaffer/oauth2-server-php

[extension] hosannahighertech/yii2-light-bootstrap

$
0
0

Light Bootstrap Admin Template

  1. Installation
  2. Usage

Yii2 Extension for Free Bootstrap Admin Template by Tim Creative. More details at https://www.creative-tim.com/product/light-bootstrap-dashboard

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist hosannahighertech/yii2-light-bootstrap "*"

or add

"hosannahighertech/yii2-light-bootstrap": "*"

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your layout code as you wish. Below is an example that can be copied and pasted into your views/layouts/main.php of Yii2 Basic Template.

<?php

/* @var $this \yii\web\View */
/* @var $content string */

use app\widgets\Alert;
use yii\helpers\Html;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>


<div class="wrapper">

    <?= \hosannahighertech\lbootstrap\widgets\SideBar::widget([
        'bgImage'=>'@web/img/sidebar-5.jpg', //Don't define it if there is none
        'header'=>[
            'title'=>'Hosanna is Great!',
            'url'=>['/default/index']
        ],
        'links'=>[
            ['title'=>'Some URL', 'url'=>['/controller/action'], 'icon'=>'users']
        ]
    ]) ?>
    
    <div class="main-panel">
		 <?= \hosannahighertech\lbootstrap\widgets\NavBar::widget([
				'theme'=>'red',
				'brand'=>[
					'label'=>'Nasafiri'
				],
				'links'=>[
					['label' => 'Home', 'url' => ['/site/index']],
					['label' => 'About', 'url' => ['/site/about']],
				],
			]) ?>
                
		<div class="content">
			<div class="container-fluid">
				<?= $content ?>
			</div>
		</div>

        <footer class="footer">
            <div class="container-fluid">
                <nav class="pull-left">
                    <ul>
                        <li>
                            <a href="#">
                                Home
                            </a>
                        </li>
                        <li>
                            <a href="#">
                                Company
                            </a>
                        </li>
                        <li>
                            <a href="#">
                                Portfolio
                            </a>
                        </li>
                        <li>
                            <a href="#">
                               Blog
                            </a>
                        </li>
                    </ul>
                </nav>
                <p class="copyright pull-right">
                    &copy; <?= date('Y') ?> <a href="http://www.creative-tim.com">Creative Tim</a>, made with love for a better web
                </p>
            </div>
        </footer>

    </div>
</div>

<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

To-Do-List
  1. Convert footer to a widget
  2. Convert Panel to Container widget with sidebar, navbar and, content and footer as attributes.

[extension] yiisoft/yii2-maskedinput

$
0
0

993323

Masked Input Extension for Yii 2

  1. Installation
  2. Usage

This is the Masked Input extension for Yii framework 2.1. It provides a masked input widget based on jQuery Input Mask plugin.

For license information check the LICENSE-file.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-maskedinput

or add

"yiisoft/yii2-maskedinput": "~1.0.0"

to the require section of your composer.json file.

Note that this package contains the MaskedInput widget for Yii versions 2.1 or above, in 2.0 the widget is bundled with the framework package, so no additional install is needed.

Usage

To use MaskedInput, you must set the mask property. The following example shows how to use MaskedInput to collect phone numbers:

echo MaskedInput::widget([
    'name' => 'phone',
    'mask' => '999-999-9999',
]);

You can also use this widget in an ActiveForm using the ActiveField::widget() method, for example like this:

<?= $form->field($model, 'from_date')->widget(yii\widgets\MaskedInput::class, [
    'mask' => '999-999-9999',
]) ?>

[extension] roslov/yii2-compact-file-target

$
0
0

CompactFileTarget

  1. Installation
  2. Usage

Ignores traces in FileTarget log.

Even if traceLevel is set greater than 0, the trace data will not be written to a log file.

This is needed to have more clean logs on development environment.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist roslov/yii2-compact-file-target "*"

or add

"roslov/yii2-compact-file-target": "*"

to the require section of your composer.json file.

Usage

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

Let’s imagine you have such configuration:

return [
    'bootstrap' => ['log'],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['info'],
                    'categories' => ['analytics'],
                    'logVars' => [],
                ],
            ],
        ],
    ],
];

After Yii::info($text, 'analytics'); your log will have such output:

2017-10-30 12:11:41 [172.18.0.1][43][-][info][analytics] User 123 updated.
    in /var/www/html/components/analytics/Analytics.php:110
    in /var/www/html/components/analytics/Analytics.php:75
    in /var/www/html/modules/api/v2/behaviors/EventTracker.php:40
2017-10-30 12:11:42 [172.18.0.1][43][-][info][analytics] Notification sent to user 123.
    in /var/www/html/components/analytics/Analytics.php:110
    in /var/www/html/components/analytics/Analytics.php:75
    in /var/www/html/modules/api/v2/behaviors/ActivityTracker.php:85
2017-10-30 12:11:55 [172.18.0.1][43][-][info][analytics] User 456 logged out.
    in /var/www/html/components/analytics/Analytics.php:110
    in /var/www/html/components/analytics/Analytics.php:41
    in /var/www/html/modules/api/v2/behaviors/ActivityTracker.php:57

For just logging events you may not need any trace information.

So you can change class from yii\log\FileTarget to roslov\log\CompactFileTarget:

return [
    'bootstrap' => ['log'],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'roslov\log\CompactFileTarget',
                    'levels' => ['info'],
                    'categories' => ['analytics'],
                    'logVars' => [],
                ],
            ],
        ],
    ],
];

In this case the log will look more clean.

2017-10-30 12:11:41 [172.18.0.1][43][-][info][analytics] User 123 updated.
2017-10-30 12:11:42 [172.18.0.1][43][-][info][analytics] Notification sent to user 123.
2017-10-30 12:11:55 [172.18.0.1][43][-][info][analytics] User 456 logged out.

[extension] akiraz2/yii2-blog

$
0
0

Yii2 Super Blog Packagist Version Total Downloads Software License

  1. Features:
  2. Installation
  3. Usage
  4. Support
  5. Contributing
  6. Licensing

Yii2 Super Blog is simple, configured yii2 Module with frontend and backend, cloned from unmaintained repo funson86/yii2-blog, fully reorganized and improved.

Features:

  • Blog Post with image banner, seo tags
  • Blog Category (nested) with image banner, seo tags
  • Blog Tags
  • Blog Comment (can be disabled), with standard yii2 captcha (can be ReCaptcha2)
  • email in comments are masked (a*i*a*@bk.ru)
  • all models has Status (Inactive, Active, Archive)
  • Inactive comments are truncated (and strip tags)
  • also added semantic OpenGraph (via yii2 component dragonjet/yii2-opengraph), Schema.org
  • backendControllers can be protected by your CustomAccessControl (roles or rbac)
  • frontend and backend are translated (i18n)
  • url rules with slug (for seo)

NOTE: Module is in initial development. Anything may change at any time.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist akiraz2/yii2-blog "dev-master"

or add

"akiraz2/yii2-blog": "dev-master"

to the require section of your composer.json file.

Migration

Migration run

yii migrate --migrationPath=@akiraz2/blog/migrations
Config url rewrite in /common/config/main.php
    'timeZone' => 'Europe/Moscow', //time zone affect the formatter datetime format
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [               
            ],
        ],
        'formatter' => [ //for the showing of date datetime
            'dateFormat' => 'yyyy-MM-dd',
            'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
            'decimalSeparator' => '.',
            'thousandSeparator' => ' ',
            'currencyCode' => 'EUR',
        ],
    ],
Config common modules in common/config/main.php
    'modules' => [
        'blog' => [
            'class' => akiraz2\blog\Module::class,
            'urlManager' => 'urlManagerFrontend',
            'imgFilePath' => '@frontend/web/img/blog/',
            'imgFileUrl' => '/img/blog/',
            'adminAccessControl' => 'common\components\AdminAccessControl',        
        ],
     ],    
Config backend modules in backend/config/main.php
    'modules' => [
        'blog' => [
            'class' => 'akiraz2\blog\Module',
            'controllerNamespace' => 'akiraz2\blog\controllers\backend'
        ],
    ],
Config frontend modules in frontend/config/main.php
    //'defaultRoute' => 'blog', //set blog as default route
    'modules' => [
        'blog' => [
            'class' => 'akiraz2\blog\Module',
            'controllerNamespace' => 'akiraz2\blog\controllers\frontend',
            'blogPostPageCount' => 6,
            'blogCommentPageCount' => 10, //20 by default
            'enableComments' => true, //true by default
            'schemaOrg' => [ // empty array [] by default! 
                'publisher' => [
                    'logo' => '/img/logo.png',
                    'logoWidth' => 191,
                    'logoHeight' => 74,
                    'name' => 'My Company',
                    'phone' => '+1 800 488 80 85',
                    'address' => 'City, street, house'
                ]
            ]
        ],
    ],
Access Url
  1. backend : http://backend.you-domain.com/blog
  2. frontend : http://you-domain.com/blog

Usage

Overriding views

When you start using Yii2-blog you will probably find that you need to override the default views provided by the module. Although view names are not configurable, Yii2 provides a way to override views using themes. To get started you should configure your view application component as follows:

...
'components' => [
    'view' => [
        'theme' => [
            'pathMap' => [
                '@akiraz2/yii2-blog/views/frontend/default' => '@app/views/blog'
            ],
        ],
    ],
],
...

In the above pathMap means that every view in @akiraz2/yii2-blog/views/frontend/default will be first searched under @app/views/blog and if a view exists in the theme directory it will be used instead of the original view.

NOTE: Just copy all necessary views from @akiraz2/yii2-blog/views/frontend/default to @app/views/blog and change!

How to change captcha in Comments

Not yet...

User model

Module Yii2-Blog use common\models\User, so if you use custom user component or Module like dektrium/yii2-user, you should create model under path common\models\User with overriding your user-model.

For example, `php
namespace common\models;

use dektrium\user\models\User as BaseUser;

class User extends BaseUser {

} `

CustomAdminAccessControl for backend

For example, using dektrium/yii2-user

`php

'modules' => [
     'blog' => [
         'class' => akiraz2\blog\Module::class,
         ...
         'adminAccessControl' => 'common\components\AdminAccessControl',  
         ...      
     ],
 ], 

`

Create file common\components\AdminAccessControl.php

`php

namespace common\components;

use yii\filters\AccessControl;

class AdminAccessControl extends AccessControl
{

    public function init()
    {
        $this->rules[] =[
            'allow' => true,
            'roles' => ['@'],
            'matchCallback' => function () {
                return \Yii::$app->user->identity->getIsAdmin();
            }
        ];
        parent::init();
    }
}

`

Opengraph

Please, add component dragonjet/yii2-opengraph to your project. php composer.phar require --prefer-dist dragonjet/yii2-opengraph "dev-master"

Configuration common/config/main.php or frontend/config/main.php

`php

'components' => [
    'opengraph' => [
        'class' => 'dragonjet\opengraph\OpenGraph',
    ],
    //....
],

`

Support

If you have any questions or problems with Yii2-Blog you can ask them directly by using following email address: akiraz@bk.ru.

Contributing

If you'd like to contribute, please fork the repository and use a feature branch. Pull requests are warmly welcome. +PSR-2 style coding. I can apply patch, PR in 2-3 days! If not, please write me akiraz@bk.ru

Licensing

Yii2-Blog is released under the MIT License. See the bundled LICENSE.md for details.


[extension] softark/yii2-mb-captcha

$
0
0

yii2-mb-captcha

  1. Description
  2. Requirements
  3. Usage
  4. Properties of softark\mbcaptcha\Captcha
  5. Properties of softark\mbcaptcha\CaptchaAction
  6. How to Customize
  7. History
  8. Acknowledgment

Multibyte captcha widget for Yii framework 2.0.

Multibyte Captcha in Action

Multibyte Captcha using Chinese characters

日本語の README

Description

softark\mbcaptcha\Captcha is an extension to yii\captcha\Captcha.

While yii\captcha\Captcha renders a CAPTCHA image only with English alphabets, softark\mbcaptcha\Captcha can render it with multibyte characters ... Japanese Hirakana by default, but you may use any multibyte characters by providing the appropriate font.

Optionally softark\mbcaptcha\Captcha may render a link next to the CAPTCHA image which will enable you to toggle the CAPTCHA type from the multibyte character to English alphabet, and vice versa.

softark\mbcaptcha\Captcha must be used together with softark\mbcaptcha\CaptchaAction to provide its feature.

Requirements

  • Yii Version 2.0.0 or later
  • PHP GD + FreeType extension or ImageMagick extension

Usage

  1. Add softark/yii2-mb-captcha in your project's composer.json, and let Composer configure your project.

    `php "require": {

     "php": ">=5.4.0",
     "yiisoft/yii2": "*",
     "yiisoft/yii2-bootstrap": "*",
     "yiisoft/yii2-swiftmailer": "*",
     "softark/yii2-mb-captcha": "dev-master"
    

    }, `

  2. Use softark\mbcaptcha\Captcha in place of yii\captcha\Captcha in your view.

    `php / use yii\captcha\Captcha; / use softark\mbcaptcha\Captcha; ... <?=

     $form->field($model, 'verifyCode')->widget(Captcha::className(), [
         'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
     ]) ?>
    

    `

    Optionally you may want to include {link} token in your template. `php / use yii\captcha\Captcha; / use softark\mbcaptcha\Captcha; <?=

     $form->field($model, 'verifyCode')->widget(Captcha::className(), [
         'template' => '<div class="row"><div class="col-lg-3">{image} {link}</div><div class="col-lg-6">{input}</div></div>',
     ]) ?>
    

    `

  3. Use softark\mbcaptcha\CaptchaAction in place of yii\captcha\CaptchaAction in your controller.

    `php public function actions() {

     return [
         'captcha' => [
             /* 'class' => 'yii\captcha\CaptchaAction', */
             'class' => 'softark\mbcaptcha\CaptchaAction',
             'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
         ],
         ...
     ];
    

    } `

Properties of softark\mbcaptcha\Captcha

softark\mbcaptcha\Captcha supports all the properties of yii\captcha\Captcha and the following ones. The items with *()** are the basic options that you may want to configure.

  1. *template ()** @var string

    The template for arranging the CAPTCHA widget. Defaults to '{image} {link} {input}'.

    This property is inherited from the parent and is extended to support the type toggling link tag. In this template, the tokens {image}, {link} and {input} will be replaced with the actual image tag, the type toggling link tag and the text input tag respectively.

    Note that {link} must be a sibling of {image} in the DOM tree, otherwise the toggling link won't work.

    You may omit {link} token if you don't want the type toggling link tag.

  2. *toggleLinkLabel ()** @var string

    The label of the type toggling link. Defaults to "かな/abc" ("Japanese Hirakana/lower-case alphabet").

    You may want to change this label when you use non-Japanese characters.

Properties of softark\mbcaptcha\CaptchaAction

softark\mbcaptcha\CaptchaAction supports all the properties of yii\captcha\CaptchaAction and the following additional ones. The items with *()** are the basic options that you may want to configure.

  1. *mbFontFile ()** @var string

    The font to be used for multibyte characters. Defaults to seto-mini.ttf.

    Note that the default font only supports standard ASCII and Japanese Hirakana and Katakana.

    You have to provide an appropriate font file if you want to render your choice of characters.

  2. *seeds ()** @var string

    The string used for generating the random word. Several characters randomly selected from this string will make up the captcha word.

    Defaults to a series of Japanese Hirakana characters: "あいうえおかきくけこがぎぐげごさしすせそざじずぜぞたちつてとだぢづでどなにぬねのはひふへほはひふへほはひふへほばびぶべぼぱぴぷぺぽまみむめもやゆよらりるれろわをん".

    You may set your own. Make sure that your mbFontFile can render all the characters in the seeds.

  3. mbMinLength @var integer

    The minimum length for randomly generated multibyte character word. Defaults to 5

  4. mbMaxLength @var integer

    The maximum length for randomly generated multibyte character word. Defaults to 5

  5. mbOffset @var integer

    The offset between characters. Defaults to 2. You can adjust this property in order to decrease or increase the readability of the multibyte character captcha.

  6. fixedAngle @var boolean

    Whether to render the multibyte character captcha image with a fixed angle. Defaults to false. You may want to set this to true if you have trouble rendering your font.

How to Customize

The following is a sample code that shows how to customize softark\mbcaptcha\Captcha and softark\mbcaptcha\CaptchaAction. It shows Chinese characters for the captcha.

In the view script:

use softark\mbcaptcha\Captcha;
...
<?=
    $form->field($model, 'verifyCode')->widget(Captcha::className(), [
        'template' => '<div class="row"><div class="col-lg-3">{image} {link}</div><div class="col-lg-6">{input}</div></div>',
        'toggleLinkLabel' => '漢字/abc',
    ]) ?>

And in the controller:

public function actions()
{
    return [
        'captcha' => [
            'class' => 'softark\mbcaptcha\CaptchaAction',
            'seeds' => '几乎所有的应用程序都是建立在数据库之上虽然可以非常灵活的' .
                '操作数据库但有些时候一些设计的选择可以使它更便于使用首先应用程序' .
                '广泛使用了设计的考虑主要围绕优化使用而不是组成复杂语句实际上大多' .
                '的设计是使用友好的模式来解决实践中的问题最常用的方式是创建易于被' .
                '人阅读和理解的代码例如使用命名来传达意思但是这很难做到',
            'mbFontFile' => '@frontend/fonts/gbsn00lp.ttf',
        ],
        ...
    ];
}

Note that the sample code assumes that you have placed your choice of font file in the 'fonts' sub-directory of your frontend application directory.

You have to be careful not to include the characters in seeds that are not supported by your font.

History

  • Version 1.0.0 (2014-11-15)
    • Tested on Yii 2.0.0
    • Adopted the code style of the core (spaces for indentation)
  • Version 0.9.0 (2014-04-22)
    • Update for Yii 2.0 beta
  • Version 0.8.0 (2014-02-08)
    • Initial release
    • Ported from JCaptcha 1.0.3, which is for Yii 1.1.x.
    • Developed under Yii 2.0 alpha

Acknowledgment

Many thanks to the author of the wonderful work of setofont.ttf. The default font "seto-mini.ttf" is a subset of setofont.ttf.

[extension] softark/creole

$
0
0

creole parser extended from cebe/markdown

  1. What is this?
  2. Installation
  3. Usage
  4. Acknowledgements
  5. FAQ
  6. Contact

Build Status Code Coverage Scrutinizer Code Quality

What is this?

This is a Creole Wiki parser for PHP built upon cebe/markdown parser for PHP.

Installation

PHP 5.4 or higher is required to use it. It will also run on facebook's hhvm.

Installation is recommended to be done via composer by running:

composer require softark/creole "~1.2"

Alternatively you can add the following to the require section in your composer.json manually:

"softark/creole": "~1.2"

Run composer update afterwards.

Note that the installation automatically includes the dependent packages, especially "cebe/markdown", to make the creole parser functional.

Usage

The usage of the creole parser is similar to that of cebe/markdown parser.

In your PHP project

To parse your wiki text you need only two lines of code. The first one is to create the creole parser instance:

$parser = new \softark\creole\Creole();

The next step is to call the parse()-method for parsing the text using the full wiki language or calling the parseParagraph()-method to parse only inline elements:

$parser = new \softark\creole\Creole();
$outputHtml = $parser->parse($wikiText);

// parse only inline elements (useful for one-line descriptions)
$parser = new \softark\creole\Creole();
$outputHtml = $parser->parseParagraph($wikiText);

You may optionally set the following option on the parser object:

  • $parser->html5 = true to enable HTML5 output instead of HTML4.

And you should set the following properties when you are using the wiki style links, i.e. link for an internal link and WikiName:link for an external link:

  • $parser->wikiUrl = 'http://www.example.com/wiki/' for the url of the current wiki.
  • $parser->externalWikis = ['Wiki-A' => 'http://www.wiki-a.com/', 'Wiki-B' => 'http://www.wiki-b.net/'] for the external wikis. It should be an array in which the keys are the name of the wiki and the value the urls of them.

It is recommended to use UTF-8 encoding for the input strings. Other encodings are currently not tested.

Using raw html blocks

In the version 1.2.0 and later, you may optionally include raw html blocks in the source wiki text, although this feature is disabled by default because it's not in the Creole 1.0 specification.

You can enable this feature by specifying the following option:

  • $parser->useRawHtml = true

A raw html block should start with a line that only contains <<< and end with a corresponding closing line which should be >>>, for example: <<< <p>This is a raw html block.</p> <ul> <li>You can do whatever you want.</li> <li>You have to be responsible for the consequence.</li> </ul> >>>

Note that the output of the raw html blocks SHOULD BE CLEANSED with $parser->rawHtmlFilter. A recommendation is to use HTML Purifier for the filter. For example:

$parser->rawHtmlFilter = function($input) {
    $config = \HTMLPurifier_Config::createDefault();
    $purifier = \HTMLPurifier::getInstance($config);
    return $purifier->purify($input);
};

// Or, if you are Yii 2 user
$parser->rawHtmlFilter = function($input) {
    return \yii\helpers\HtmlPurifier::process($input);
};

As you see in the example, the rawHtmlFilter should be a callable that accepts the possibly unclean html text string and output the sanitized version of it.

The command line script

You can use it to convert a wiki text to a html file:

bin/creole some.txt > some.html

Here is the full Help output you will see when running bin/creole --help:

PHP Creole to HTML converter
----------------------------

by Nobuo Kihara <softark@gmail.com>

Usage:
    bin/creole [--full] [file.txt]

    --full    ouput a full HTML page with head and body. If not given, only the parsed markdown will be output.

    --help    shows this usage information.

    If no file is specified input will be read from STDIN.

Examples:

    Render a file with original creole:

        bin/creole README.txt > README.html

Convert the original creole description to html using STDIN:

    curl http://www.wikicreole.org/attach/Creole1.0TestCases/creole1.0test.txt | $cmd > creole.html

Acknowledgements

I'd like to thank @cebe for creating cebe/markdown library on which this work depends.

As its name describes, cebe/markdown is a markdown parser, but is also a well designed general purpose markup language parser at the bottom on which you can implement parsers not only for different "flavors" of markdown but also for different markup languages, Creole for instance.

FAQ

Where do I report bugs or rendering issues?

Just open an issue on github, post your creole code and describe the problem. You may also attach screenshots of the rendered HTML result to describe your problem.

Am I free to use this?

This library is open source and licensed under the MIT License. This means that you can do whatever you want with it as long as you mention my name and include the license file. Check the license for details.

Contact

Feel free to contact me using email or twitter.

[extension] maks757/yii2-friendly-url

$
0
0

Friendly url

  1. Installation
  2. Usage
  3. Model
  4. Configuration
  5. View
  6. Action from Product Controller

Friendly url for your library or module

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist maks757/yii2-friendly-url "*"

or add

"maks757/yii2-friendly-url": "*"

to the require section of your composer.json file.

Usage

Model

// implements IUrlRules !!!
class ProductModel extends \yii\db\ActiveRecord implements maks757\friendly\components\IUrlRules
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'products';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //...
            // seo data
            [['seoUrl', 'seoTitle', 'seoDescription', 'seoKeywords'], 'string']
        ];
    }
    
    // Exemple: $key = 'my-first-product' -> return id
    /**
     * @param mixed $key
     * @return boolean|integer model id
     */
    public function fiendKey($key)
    {
        $model = ProductModel::findOne(['seoUrl' => $key]);
        return empty($model) ? false : $model->id;
    }

    // Exemple: $id = 10 -> return seoUrl
    /**
     * @param integer $id
     * @return string
     */
    public function seoUrl($id)
    {
        return ProductModel::findOne($id)->seoUrl;
    }
}

Configuration

'components' => [
    //...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            'news' => 'product/show',
            [
                    'class' => \maks757\friendly\UrlRules::className(),
                    'action' => 'product/show', // View 'product/show' or news
                    'controller_and_action' => 'product/show', // Action news show
                    //param: (action_key) - Action param get product id
                    //param: (url_key) - // View set product id
                    'routes' => [
                        ['model' => \common\models\ProductGroupModel::class, 'url_key' => 'group_id', 'action_key' => 'group',],
                        ['model' => \common\models\ProductModel::class, 'url_key' => 'product_id', 'action_key' => 'product',],
                    ]
                ],
        ],
    ],
    //...
],

View

<a href="Url::toRoute(['/product/show', 'group_id' => $group, 'product_id' => $product->id])">Go to product</a>

example url: https://tise/product/show/water/colla<br> water = group seo url
colla = product seo url

Action from Product Controller

public function actionShow($group, $product)
{
    //...
}

[extension] yiisoft/yii2-queue

$
0
0

993323

Yii2 Queue Extension

  1. Installation
  2. Basic Usage

An extension for running tasks asynchronously via queues.

It supports queues based on DB, Redis, RabbitMQ, AMQP, Beanstalk and Gearman.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-queue

or add

"yiisoft/yii2-queue": "~2.0.0"

to the require section of your composer.json file.

Basic Usage

Each task which is sent to queue should be defined as a separate class. For example, if you need to download and save a file the class may look like the following:

class DownloadJob extends BaseObject implements \yii\queue\JobInterface
{
    public $url;
    public $file;
    
    public function execute($queue)
    {
        file_put_contents($this->file, file_get_contents($this->url));
    }
}

Here's how to send a task into the queue:

Yii::$app->queue->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

To push a job into the queue that should run after 5 minutes:

Yii::$app->queue->delay(5 * 60)->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

The exact way a task is executed depends on the used driver. Most drivers can be run using console commands, which the component automatically registers in your application.

This command obtains and executes tasks in a loop until the queue is empty:

yii queue/run

This command launches a daemon which infinitely queries the queue:

yii queue/listen

See the documentation for more details about driver specific console commands and their options.

The component also has the ability to track the status of a job which was pushed into queue.

// Push a job into the queue and get a message ID.
$id = Yii::$app->queue->push(new SomeJob());

// Check whether the job is waiting for execution.
Yii::$app->queue->isWaiting($id);

// Check whether a worker got the job from the queue and executes it.
Yii::$app->queue->isReserved($id);

// Check whether a worker has executed the job.
Yii::$app->queue->isDone($id);

For more details see the guide.

[extension] hoaaah/yii2-startbootstrap-agency

$
0
0

YII2 Startbootstrap-Agency Library

  1. Installation
  2. Usage
  3. Creator

This extensions is library for Startbootstrap Stylish-Portofolio Themes

Agency is a responsive, one page portfolio theme for Bootstrap created by Start Bootstrap. This theme features several content sections, a responsive portfolio grid with hover effects, full page portfolio item modals, a responsive timeline, and a working PHP contact form.

Start Bootstrap was created by and is maintained by David Miller, Owner of Blackrock Digital.

Start Bootstrap is based on the Bootstrap framework created by Mark Otto and Jacob Thorton.

Installation

The preferred way to install this extension is through composer.

Either run

composer require hoaaah/yii2-startbootstrap-agency:dev-master

or add

"hoaaah/yii2-startbootstrap-agency": "*"

to the require section of your composer.json file.

Usage

You can use an example views in views-example and copy it to your view.

Don't forget to use this in your view

use hoaaah\agency\AgencyAsset;

AgencyAsset::register($this);

and just in case you want to use vendor image, to call any content of vendor image you can use this

$image = hoaaah\agency\AgencyAsset::register($this);

<img src=<?= $agency->baseUrl.'/img/portfolio/startup-framework.png' ?> class="img-responsive" alt="">

it will call startup-framework.png from /vendor/hoaaah/yii2-startbootstrap-agency/assets/img/portofolio/startup-framework.png

Creator

This startbootstrap-agency library for Yii2 was created by and is maintained by Heru Arief Wijaya.

Viewing all 3375 articles
Browse latest View live