Commit a56bce93 authored by Олег Гиммельшпах's avatar Олег Гиммельшпах

Merge branch 'testing'

parents 1bced7a2 feb69412
...@@ -18,6 +18,7 @@ return [ ...@@ -18,6 +18,7 @@ return [
'faq' => ['class' => 'common\modules\faq\Module'], 'faq' => ['class' => 'common\modules\faq\Module'],
'reviews' => ['class' => 'common\modules\reviews\Module'], 'reviews' => ['class' => 'common\modules\reviews\Module'],
'users' => ['class' => 'common\modules\users\users'], 'users' => ['class' => 'common\modules\users\users'],
'testings' => ['class' => 'common\modules\testings\Module'],
'main' => ['class' => 'common\modules\main\main'], 'main' => ['class' => 'common\modules\main\main'],
'rbac' => ['class' => 'common\modules\rbac\rbac'], 'rbac' => ['class' => 'common\modules\rbac\rbac'],
'utility' => ['class' => 'c006\utility\migration\Module'], 'utility' => ['class' => 'c006\utility\migration\Module'],
......
/index.php /index.php
/index-test.php /index-test.php
/uploads/temp/*
\ No newline at end of file
...@@ -7,8 +7,8 @@ Website: http://www.seantheme.com/color-admin-v1.6/admin/ ...@@ -7,8 +7,8 @@ Website: http://www.seantheme.com/color-admin-v1.6/admin/
var handleDataTableColVis = function() { var handleDataTableColVis = function() {
"use strict"; "use strict";
$('table.table.table-striped.table-bordered .empty').closest('tr').remove(); $('.dataTable .empty').closest('tr').remove();
if ($('table.table.table-striped.table-bordered').length !== 0) { if ($('.dataTable').length !== 0) {
var table = $('table.table.table-striped.table-bordered').DataTable({ var table = $('table.table.table-striped.table-bordered').DataTable({
dom: 'C<"clear">lfrtip', dom: 'C<"clear">lfrtip',
paging: false, paging: false,
......
...@@ -10,7 +10,7 @@ abstract class AdminController extends \common\components\BaseController ...@@ -10,7 +10,7 @@ abstract class AdminController extends \common\components\BaseController
public static function getLocalId() { public static function getLocalId() {
return str_replace('Controller','',self::className()); return str_replace('Controller', '', self::className());
} }
public function init() public function init()
...@@ -32,69 +32,8 @@ abstract class AdminController extends \common\components\BaseController ...@@ -32,69 +32,8 @@ abstract class AdminController extends \common\components\BaseController
$this->redirect($admin_url); $this->redirect($admin_url);
} }
$this->initTabs();
$this->view->registerJsFile('/js/packages/adminBaseClasses/buttonSet.js'); $this->view->registerJsFile('/js/packages/adminBaseClasses/buttonSet.js');
$this->view->registerJsFile('/js/packages/adminBaseClasses/gridBase.js'); $this->view->registerJsFile('/js/packages/adminBaseClasses/gridBase.js');
} }
private function initTabs()
{
/* $tabs = array();
$actions_titles = call_user_func(array(get_class(Yii::app()->controller), 'actionsTitles'));
foreach ($actions_titles as $action => $title)
{
if (in_array($action, array('Delete', 'Update', 'View')))
{
continue;
}
$tabs[$title] = $this->createUrl($action);
}
$this->tabs = $tabs;*/
}
private function initAssets()
{
/* $assets_dir = MODULES_PATH . Yii::app()->controller->module->id . '/assets/';
if (!is_dir($assets_dir))
{
return;
}
$dir_names = array('css', 'js');
foreach ($dir_names as $dir_name)
{
$dir = $assets_dir . $dir_name . '/';
if (!is_dir($dir))
{
continue;
}
$asset_dir = Yii::app()->getAssetManager()->publish($dir) . '/';
$scripts = scandir($dir);
foreach ($scripts as $script)
{
if ($script[0] == '.')
{
continue;
}
if ($dir_name == 'js')
{
echo $asset_dir . $script . "<br>";
Yii::app()->clientScript->registerScriptFile($asset_dir . $script);
}
else if ($dir_name == 'css')
{
Yii::app()->clientScript->registerCssFile($asset_dir . $script);
}
}
}*/
}
} }
...@@ -35,8 +35,8 @@ class BaseForm extends \yii\widgets\ActiveForm ...@@ -35,8 +35,8 @@ class BaseForm extends \yii\widgets\ActiveForm
// $view->registerJsFile('/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js', ['position' => \yii\web\View::POS_END ]); // $view->registerJsFile('/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js', ['position' => \yii\web\View::POS_END ]);
// $view->registerJsFile('/plugins/bootstrap-datepicker/js/locales/bootstrap-datepicker.ru.js', ['position' => \yii\web\View::POS_END ]); // $view->registerJsFile('/plugins/bootstrap-datepicker/js/locales/bootstrap-datepicker.ru.js', ['position' => \yii\web\View::POS_END ]);
// $view->registerJsFile('/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js', ['position' => \yii\web\View::POS_END ]); $view->registerJsFile('/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js', ['position' => \yii\web\View::POS_END ]);
// $view->registerJsFile('/plugins/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.ru.js', ['position' => \yii\web\View::POS_END ]); $view->registerJsFile('/plugins/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.ru.js', ['position' => \yii\web\View::POS_END ]);
$view->registerJsFile('/plugins/switchery/switchery.min.js', ['position' => \yii\web\View::POS_HEAD ]); $view->registerJsFile('/plugins/switchery/switchery.min.js', ['position' => \yii\web\View::POS_HEAD ]);
$view->registerJsFile('/plugins/powerange/powerange.min.js', ['position' => \yii\web\View::POS_HEAD ]); $view->registerJsFile('/plugins/powerange/powerange.min.js', ['position' => \yii\web\View::POS_HEAD ]);
...@@ -68,11 +68,12 @@ $js = <<<JS ...@@ -68,11 +68,12 @@ $js = <<<JS
todayBtn: true todayBtn: true
}); });
$('.datetimepicker-autoClose').datepicker({ $('.datetimepicker-autoClose').datetimepicker({
todayHighlight: true, todayHighlight: true,
language: 'ru', language: 'ru',
autoclose: true, autoclose: true,
format: 'dd.mm.yyyy hh:ii:ss' todayBtn: true,
format: 'dd.mm.yyyy hh:ii'
}); });
FormSliderSwitcher.init(); FormSliderSwitcher.init();
...@@ -234,12 +235,17 @@ JS; ...@@ -234,12 +235,17 @@ JS;
'captchaAction' => 'captcha', 'captchaAction' => 'captcha',
] ]
); );
break; break;
case 'date': case 'date':
$config['options'][] = '<div style="padding-left: 0;" class="col-md-6" data-date-format="dd.mm.yyyy hh:ii:ss" data-date-start-date="Date.default">'. $config['options'][] = '<div style="padding-left: 0;" class="col-md-6" data-date-format="dd.mm.yyyy hh:ii:ss" data-date-start-date="Date.default">'.
$this->field($this->model, $key, $optEl)->input('text', ['class'=>'datepicker-autoClose form-control']). $this->field($this->model, $key, $optEl)->input('text', ['class'=>'datepicker-autoClose form-control']).
'</div>'; '</div>';
break; break;
case 'datetime':
$config['options'][] = '<div style="padding-left: 0;" class="col-md-6" data-date-format="dd.mm.yyyy hh:ii" data-date-start-date="Date.default">'.
$this->field($this->model, $key, $optEl)->input('text', ['class'=>'datetimepicker-autoClose form-control']).
'</div>';
break;
case 'file': case 'file':
$config['options'][] = $this->field($this->model, $key, $optEl)->fileInput(); $config['options'][] = $this->field($this->model, $key, $optEl)->fileInput();
break; break;
......
<?php
namespace common\modules\languages;
class Module extends \common\components\WebModule
{
public $controllerNamespace = 'common\modules\languages\controllers';
public $menu_icons = 'fa fa-language';
public static $active = true;
public static $base_module = true;
public static function name()
{
return 'Управление языками';
}
public static function description()
{
return 'Данный модуль позволяет настраивать отображение на сайте текстового материалов на различных языках. Для добавления нового языка нажмите «Добавить новый язык».';
}
public static function version()
{
return '1.0';
}
public function init()
{
parent::init();
// custom initialization code goes here
}
public static function adminMenu()
{
return array(
'Список языков' => '/languages/language-admin/manage',
);
}
}
<?php
namespace common\modules\languages\controllers;
use Yii;
use common\modules\languages\models\Languages;
use common\modules\languages\models\SearchLanguages;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* LanguageAdminController implements the CRUD actions for Languages model.
*/
class LanguageAdminController extends AdminController
{
public static function actionsTitles(){
return [
'Manage' => 'Управление языками',
'Create' => 'Добавить язык',
'Update' => 'Редактированть язык',
'View' => 'Просмотр языка',
];
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Languages models.
* @return mixed
*/
public function actionManage()
{
\yii::$app->controller->breadcrumbs = [
'Управление языками',
];
\yii::$app->controller->page_title = 'Управление языками';
$searchModel = new SearchLanguages();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Languages model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Languages model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Languages();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Languages model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Languages model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Languages model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Languages the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Languages::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<?php
namespace common\modules\languages\models;
use Yii;
/**
* This is the model class for table "languages".
*
* @property integer $id
* @property string $code
* @property string $codeFull
* @property string $name
*/
class Languages extends \common\components\ActiveRecordModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'languages';
}
public function name()
{
return "Языки";
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['code', 'codeFull', 'name'], 'required'],
[['code'], 'string', 'max' => 2],
[['codeFull'], 'string', 'max' => 5],
[['name'], 'string', 'max' => 15],
[['name'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('languages', 'ID'),
'code' => Yii::t('languages', 'Language Code'),
'codeFull' => Yii::t('languages', 'Locale Code'),
'name' => Yii::t('languages', 'Name'),
];
}
}
<?php
namespace common\modules\languages\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\modules\languages\models\Languages;
/**
* SearchLanguages represents the model behind the search form about `common\modules\languages\models\Languages`.
*/
class SearchLanguages extends Languages
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['code', 'codeFull', 'name'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Languages::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
]);
$query->andFilterWhere(['like', 'code', $this->code])
->andFilterWhere(['like', 'codeFull', $this->codeFull])
->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\modules\languages\models\Languages */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="languages-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'code')->textInput(['maxlength' => 2]) ?>
<?= $form->field($model, 'codeFull')->textInput(['maxlength' => 5]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 15]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('content', 'Create') : Yii::t('content', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\modules\languages\models\SearchLanguages */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="languages-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'code') ?>
<?= $form->field($model, 'codeFull') ?>
<?= $form->field($model, 'name') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('content', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('content', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\modules\languages\models\Languages */
$this->title = Yii::t('content', 'Create Languages');
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Languages'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="languages-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel common\modules\languages\models\SearchLanguages */
/* @var $dataProvider yii\data\ActiveDataProvider */
?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('languages', 'Create Languages'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= \common\components\zii\AdminGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'code',
'codeFull',
'name',
[
'class' => 'common\components\ColorActionColumn',
'template' => '{update} {delete}',
],
],
]); ?>
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\modules\languages\models\Languages */
$this->title = Yii::t('content', 'Update {modelClass}: ', [
'modelClass' => 'Languages',
]) . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Languages'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('content', 'Update');
?>
<div class="languages-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\modules\languages\models\Languages */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Languages'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="languages-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('content', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('content', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('content', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'code',
'codeFull',
'name',
],
]) ?>
</div>
<?php
namespace common\modules\testings;
class Module extends \common\components\WebModule
{
public $controllerNamespace = 'common\modules\testings\controllers';
public $menu_icons = 'fa fa-question';
public static $active = true;
public static $base_module = true;
public static function name()
{
return 'Тестирование';
}
public static function description()
{
return 'Тестирование';
}
public static function version()
{
return '1.0';
}
public function init()
{
parent::init();
// custom initialization code goes here
}
public static function adminMenu()
{
return array(
'Список сессий' => '/testings/testing-session-admin/manage',
'Список тестов' => '/testings/testing-test-admin/manage',
'Список вопросов' => '/testings/testing-question-admin/manage',
);
}
}
$(function()
{
var $answers_forms = $('#answers_forms');
var $form = $('#testing-question-form');
$('#add_answer').click(function()
{
var $inputs = $('#answers_forms input');
var num = 0;
if ($inputs.length)
{
var max_num = 0;
$inputs.each(function()
{
var reg = new RegExp('([0-9]+)');
var curr_num = reg.exec($(this).attr('name'))[0];
if (curr_num > max_num)
{
max_num = curr_num;
}
});
num = ++max_num;
}
var params = {
'sub_form' : 'add',
'num' : num
};
$.post('/testings/testingQuestionAdmin/GetAnswerForm', params , function(form)
{
$answers_forms.append(form);
});
return false;
});
$form.submit(function()
{
if ($('#answers_forms input').length)
{
$.post('/testings/testingQuestionAdmin/ValidateAnswerForm', $(this).serialize(), function(res)
{
if (res.done)
{
alert('valid');
}
else
{
$answers_forms.html(res.html);
}
},
'json'
);
//return true;
}
return false;
});
});
<?php
class AnswersBehavior extends CActiveRecordBehavior
{
public function getFileManagerRelation($tag)
{
$model = $this->getOwner();
return array(
CActiveRecord::HAS_MANY,
'ImageManager',
'object_id',
'condition' => "{$tag}.model_id = '". get_class($model) ."' AND {$tag}.tag='images'",
'order' => "{$tag}.order DESC"
);
}
public function afterSave($event)
{
$model = $this->getOwner();
if ($model->isNewRecord)
{
$files = ImageManager::model()->findAllByAttributes(array(
'object_id' => 'tmp_' . Yii::app()->user->id,
'model_id' => get_class($model)
));
foreach ($files as $file)
{
$file->object_id = $model->id;
$file->save();
}
}
return parent::beforeSave($event);
}
public function beforeDelete($event)
{
$model = $this->getOwner();
$files = ImageManager::model()->findAllByAttributes(array(
'model_id' => get_class($model),
'object_id' => $model->id
));
foreach ($files as $file)
{
$file->delete();
}
return parent::beforeDelete($event);
}
}
<?php
Yii::import('zii.widgets.grid.CGridColumn');
class MarkBoxColumn extends CGridColumn
{
public $checked;
/**
* @var array the HTML options for the data cell tags.
*/
public $htmlOptions=array('class'=>'checkbox-column');
/**
* @var array the HTML options for the header cell tag.
*/
public $headerHtmlOptions=array('class'=>'checkbox-column');
/**
* @var array the HTML options for the footer cell tag.
*/
public $footerHtmlOptions=array('class'=>'checkbox-column');
/**
* @var array the HTML options for the checkboxes.
*/
public $checkBoxHtmlOptions=array();
/**
* @var string the template to be used to control the layout of the header cell.
* The token "{item}" is recognized and it will be replaced with a "check all" checkbox.
* By default if in multiple checking mode, the header cell will display an additional checkbox,
* clicking on which will check or uncheck all of the checkboxes in the data cells.
* See {@link selectableRows} for more details.
* @since 1.1.11
*/
public $headerTemplate='{item}';
public $updateUrl;
/**
* Initializes the column.
* This method registers necessary client script for the checkbox column.
*/
public function init()
{
if(isset($this->checkBoxHtmlOptions['name']))
$name=$this->checkBoxHtmlOptions['name'];
else
{
$name=$this->id;
if(substr($name,-2)!=='[]')
$name.='[]';
$this->checkBoxHtmlOptions['name']=$name;
}
$name=strtr($name,array('['=>"\\[",']'=>"\\]"));
$js=<<<CBALL
$(document).delegate('#{$this->id}_all','click',function() {
//групповой выбор/сброс
var th = this, checked=this.checked, data = {};
th.disabled = true;
$("input[name='$name']:not(:disabled)").each(function() {
data[this.value] =checked ? 1:0;
this.checked=checked;
this.disabled = true;
});
$.ajax({
type: 'POST',
url: '{$this->updateUrl}',
data: {data: data},
dataType: 'json',
success: function(data){
var el = $("#sendMarkup").html(data.title);
if(data.qty) {
el.show();
$("#resetMarkup").show();
} else {
el.hide();
$("#resetMarkup").hide();
}
},
complete: function(){
th.disabled = false;
$("input[name='$name']").each(function() {
this.disabled = false;
});
}
});
});
$(document).delegate("input[name='$name']", 'click',function() {
var checked=this.checked, data = {}, th = this;
$('#{$this->id}_all').prop('checked', $("input[name='$name']").length==$("input[name='$name']:checked").length);
th.disabled = true;
data[this.value] =checked ? 1:0;
$.ajax({
type: 'POST',
url: '{$this->updateUrl}',
data: {data: data},
dataType: 'json',
success: function(data){
var el = $("#sendMarkup").html(data.title);
if(data.qty) {
el.show();
$("#resetMarkup").show();
} else {
el.hide();
$("#resetMarkup").hide();
}
},
complete: function(){
th.disabled = false;
}
});
});
$(document).delegate("#resetMarkup", 'click', function(){
$("#{$this->id}_all, input[name='$name']").prop('checked', false);
$("#sendMarkup").hide();
$("#resetMarkup").hide();
$.ajax({
type: 'POST',
url: $(this).attr('href')
});
return false;
});
CBALL;
Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$this->id,$js);
}
/**
* Renders the header cell content.
* This method will render a checkbox in the header when {@link selectableRows} is greater than 1
* or in case {@link selectableRows} is null when {@link CGridView::selectableRows} is greater than 1.
*/
protected function renderHeaderCellContent()
{
if(trim($this->headerTemplate)==='')
{
//echo $this->grid->blankDisplay;
return;
}
$item = CHtml::checkBox($this->id.'_all',false);
echo strtr($this->headerTemplate,array(
'{item}'=>$item,
));
}
/**
* Renders the data cell content.
* This method renders a checkbox in the data cell.
* @param integer $row the row number (zero-based)
* @param mixed $data the data associated with the row
*/
protected function renderDataCellContent($row,$data)
{
$value=$this->grid->dataProvider->keys[$row];
/*
$checked = false;
if($this->checked!==null)
$checked=$this->evaluateExpression($this->checked,array('data'=>$data,'row'=>$row));
*/
$marked = $this->grid->controller->getMarked(Yii::app()->request->getQuery('session'));
$checked = in_array($data->id, $marked);
$options=$this->checkBoxHtmlOptions;
$name=$options['name'];
unset($options['name']);
$options['value']=$value;
$options['id']=$this->id.'_'.$row;
echo CHtml::checkBox($name,$checked,$options);
}
}
\ No newline at end of file
<?php
/**
* API UniSender
*
* @see http://www.unisender.com/ru/help/api/
* @version 1.3
*/
class UniSenderApi {
/**
* @var string
*/
protected $ApiKey;
/**
* @var string
*/
protected $Encoding = 'UTF8';
/**
* @var int
*/
protected $RetryCount = 0;
/**
* @var float
*/
protected $Timeout;
/**
* @var bool
*/
protected $Compression = false;
/**
* @param string $ApiKey
* @param string $Encoding
* @param int $RetryCount
*/
function __construct($ApiKey = '5m4bpdgrrzwpczgdibnnpuo919u8eeb5zm54qn4y', $Encoding = 'UTF8', $RetryCount = 4, $Timeout = null, $Compression = false) {
$this->ApiKey = $ApiKey;
if (!empty($Encoding)) {
$this->Encoding = $Encoding;
}
if (!empty($RetryCount)) {
$this->RetryCount = $RetryCount;
}
if (!empty($Timeout)) {
$this->Timeout = $Timeout;
}
if ($Compression) {
$this->Compression = $Compression;
}
}
/**
* @param string $Name
* @param array $Arguments
* @return string
*/
function __call($Name, $Arguments) {
if (!is_array($Arguments) || empty($Arguments)) {
$Params = array();
} else {
//$Params = $Arguments[0];
$Params = $Arguments;
}
return $this->callMethod($Name, $Params);
}
/**
* @param array $Params
* @return string
*/
function subscribe($Params) {
$Params = (array)$Params;
if (empty($Params['request_ip'])) {
$Params['request_ip'] = $this->getClientIp();
}
return $this->callMethod('subscribe', $Params);
}
/**
* @param string $JSON
* @return mixed
*/
protected function decodeJSON($JSON) {
return json_decode($JSON);
}
/**
* @return string
*/
protected function getClientIp() {
$Result = '';
if (!empty($_SERVER["REMOTE_ADDR"])) {
$Result = $_SERVER["REMOTE_ADDR"];
} else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$Result = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$Result = $_SERVER["HTTP_CLIENT_IP"];
}
if (preg_match('/([0-9]|[0-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[0-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])){3}/', $Result, $Match)) {
return $Match[0];
}
return $Result;
}
/**
* @param string $Value
* @param string $Key
*/
protected function iconv(&$Value, $Key) {
$Value = iconv($this->Encoding, 'UTF8//IGNORE', $Value);
}
/**
* @param string $Value
* @param string $Key
*/
protected function mb_convert_encoding(&$Value, $Key) {
$Value = mb_convert_encoding($Value, 'UTF8', $this->Encoding);
}
/**
* @param string $MethodName
* @param array $Params
* @return array
*/
protected function callMethod($MethodName, $Params = array()) {
if ($this->Encoding != 'UTF8') {
if (function_exists('iconv')) {
array_walk_recursive($Params, array($this, 'iconv'));
} else if (function_exists('mb_convert_encoding')) {
array_walk_recursive($Params, array($this, 'mb_convert_encoding'));
}
}
$Url = $MethodName . '?format=json';
if ($this->Compression) {
$Url .= '&api_key=' . $this->ApiKey . '&request_compression=bzip2';
$Content = bzcompress(http_build_query($Params));
} else {
$Params = array_merge((array)$Params, array('api_key' => $this->ApiKey));
$Content = http_build_query($Params);
}
$ContextOptions = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $Content,
)
);
if ($this->Timeout) {
$ContextOptions['http']['timeout'] = $this->Timeout;
}
$RetryCount = 0;
$Context = stream_context_create($ContextOptions);
do {
$Host = $this->getApiHost($RetryCount);
$Result = file_get_contents($Host . $Url, false, $Context);
$RetryCount++;
} while ($Result === false && $RetryCount < $this->RetryCount);
return $Result;
}
/**
* @param int $RetryCount
* @return string
*/
protected function getApiHost($RetryCount = 0) {
if ($RetryCount % 2 == 0) {
return 'http://api.unisender.com/ru/api/';
} else {
return 'http://www.api.unisender.com/ru/api/';
}
}
public function getApiKey() {
return $this->ApiKey;
}
public function checkErrors($result) {
$jsonObj = json_decode($result);
if(null===$jsonObj) {
// Ошибка в полученном ответе
return array('status'=>false, 'data'=>'Неверный формат JSON');
}
elseif(!empty($jsonObj->error)) {
return array('status'=>false, 'data'=>"Ошибка при получении данных: " . $jsonObj->error . "(code: " . $jsonObj->code . ")");
} else
return array('status'=>true, 'data'=>$jsonObj);
}
}
\ No newline at end of file
<?php
class UploadHtml
{
public static function url($url, $params = array())
{
return Yii::app()->createUrl("/imageManager/" . $url, $params);
}
public static function link($text, $url, $urlParams = array(), $htmlOptions = array())
{
return CHtml::link($text, self::url($url, $urlParams), $htmlOptions);
}
public static function editableLink($text, $model, $attr, $url, $htmlOptions = array())
{
$name = CHtml::resolveName($model, $attr);
$htmlOptions = CMap::mergeArray($htmlOptions, array('name' => $name));
return CHtml::link($text, self::url($url, array('id' => $model->id, 'attr' => $attr)), $htmlOptions);
}
}
\ No newline at end of file
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\testings\models\TestingAnswer;
use common\modules\testings\models\SearchTestingAnswer;
class TestingAnswerAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр ответа',
'Create' => 'Создание ответа',
'Update' => 'Редактирование ответа',
'Delete' => 'Удаление ответа',
'Manage' => 'Управление ответами',
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new TestingAnswer;
Yii::$app->controller->page_title = 'Добавить ответ';
Yii::$app->controller->breadcrumbs = [
['Список ответов' => '/testings/testing-question-admin/manage'],
'Добавить ответ'
];
if ($model->load(Yii::$app->request->post()) && $model->save())
{
if(Yii::$app->request->get('question'))
{
return $this->redirect(['manage', 'question' => Yii::$app->request->get('question')]);
}
else
{
return $this->redirect(['manage']);
}
}
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingAnswerForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionUpdate($id)
{
Yii::$app->controller->page_title = 'Редактировать ответ';
Yii::$app->controller->breadcrumbs = [
['Список ответов' => '/testings/testing-answer-admin/manage'],
'Редактировать ответ'
];
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
if(Yii::$app->request->get('question'))
{
return $this->redirect(['manage', 'question' => Yii::$app->request->get('question')]);
}
else
{
return $this->redirect(['manage']);
}
}
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingAnswerForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
public function actionManage()
{
$searchModel = new SearchTestingAnswer();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список ответов';
Yii::$app->controller->breadcrumbs = [
'Список ответов',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestingAnswer::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
This diff is collapsed.
<?php
class TestingBulkmailAccountAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр аккаунта рассылки',
'Create' => 'Создание аккаунта рассылки',
'Update' => 'Редактирование аккаунта рассылки',
'Delete' => 'Удаление аккаунта рассылки',
'Manage' => 'Управление аккаунтами рассылки',
);
}
public function actionView($id)
{
$this->render('view', array(
'model' => $this->loadModel($id),
));
}
public function actionCreate()
{
$model = new TestingBulkmailAccount;
$form = new BaseForm('testings.TestingBulkmailAccountForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingBulkmailAccount']))
{
$model->attributes = $_POST['TestingBulkmailAccount'];
if($model->save()) {
$this->redirect(array('/testings/testingBulkmailAccountAdmin/manage'));
}
}
$this->render('create', array(
'form' => $form,
));
}
public function actionUpdate($id)
{
$model = $this->loadModel($id);;
$form = new BaseForm('testings.TestingBulkmailAccountForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingBulkmailAccount']))
{
$model->attributes = $_POST['TestingBulkmailAccount'];
if($model->save())
{
$this->redirect(array('/testings/testingBulkmailAccountAdmin/manage'));
}
}
$this->render('update', array(
'form' => $form,
));
}
public function actionManage()
{
$model=new TestingBulkmailAccount('search');
$model->unsetAttributes();
if(isset($_GET['TestingBulkmailAccount']))
{
$model->attributes = $_GET['TestingBulkmailAccount'];
}
$this->render('manage', array(
'model' => $model,
));
}
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
{
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
else
{
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
}
public function loadModel($id)
{
$model = TestingBulkmailAccount::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'bulkmail-account-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
class TestingFaqAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'Create' => 'Создание справки',
'Update' => 'Редактирование справки',
'Delete' => 'Удаление',
'Manage' => 'Управление справкой',
);
}
public function actionCreate()
{
$model = new TestingFaq;
$form = new BaseForm('testings.TestingFaqForm', $model);
if(isset($_POST['TestingFaq']))
{
$model->attributes = $_POST['TestingFaq'];
if($model->save())
{
$this->redirect(array('manage'));
}
}
$this->render('create', array(
'form' => $form,
));
}
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$form = new BaseForm('testings.TestingFaqForm', $model);
if(isset($_POST['TestingFaq']))
{
$model->attributes = $_POST['TestingFaq'];
if($model->save())
{
$this->redirect(array('manage'));
}
}
$this->render('update', array(
'form' => $form,
));
}
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
{
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
else
{
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
}
public function actionManage()
{
$model=new TestingFaq('search');
$model->unsetAttributes();
if(isset($_GET['TestingFaq']))
{
$model->attributes = $_GET['TestingFaq'];
}
$this->render('manage', array(
'model' => $model,
));
}
public function loadModel($id)
{
$model = TestingFaq::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-faq-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
class TestingFaqController extends BaseController
{
const AUTH_COOKIE = 'test_user_cookie';
const PASS_COOKIE = 'test_pass_cookie';
public $layout = '/layouts/testing';
public $page_subtitle;
public $logined_user;
public function filters() {
return CMap::mergeArray(parent::filters(), array(
'checkAuth - login',
));
}
public function filterCheckAuth($filterChain) {
// проверим для начала наличие куков
if (!isset(Yii::app()->request->cookies[self::AUTH_COOKIE])
|| !isset(Yii::app()->request->cookies[self::PASS_COOKIE]))
{
$this->redirect('/testings/testingTest/login');
}
// во вторую очередь проверим, есть ли такой юзер с таким айди
$id = (int) Yii::app()->request->cookies[self::AUTH_COOKIE]->value;
$pass = Yii::app()->request->cookies[self::PASS_COOKIE]->value;
$user = TestingUser::model()->findByPk($id);
if (!$user) {
$this->redirect('/testings/testingTest/login');
}
// в конце проверим, совпадает ли пароль
if ($this->encodePassword($user->password) <> $pass) {
$this->redirect('/testings/testingTest/login');
}
$this->logined_user = $user;
$filterChain->run();
}
private function encodePassword($pass) {
return md5($pass.'the.longest.salt.ever.dont.even.try.to.decode.lol');
}
public static function actionsTitles()
{
return array(
'View' => 'Справка',
);
}
public function actionView($url)
{
$model = $this->loadModel($url);
$this->render('view', array(
'model' => $model,
));
}
public function loadModel($url)
{
$model = TestingFaq::model()->findByAttributes(array('url' => $url));
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
}
<?php
class TestingFaqStageAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'Create' => 'Создание пункта справки',
'Update' => 'Редактирование пункта справки',
'Delete' => 'Удаление пункта',
'Manage' => 'Управление пунктами справки',
);
}
public function actionCreate($faq)
{
if(!$faq)
{
$this->pageNotFound();
}
$model = new TestingFaqStage;
$form = new BaseForm('testings.TestingFaqStageForm', $model);
if(isset($_POST['TestingFaqStage']))
{
$model->attributes = $_POST['TestingFaqStage'];
$model->faq_id = $faq;
if($model->save())
{
$this->redirect(array('manage', 'faq' => $faq));
}
}
$this->render('create', array(
'form' => $form,
));
}
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$form = new BaseForm('testings.TestingFaqStageForm', $model);
if(isset($_POST['TestingFaqStage']))
{
$model->attributes = $_POST['TestingFaqStage'];
if($model->save())
{
$this->redirect(array('manage', 'faq' => $model->faq_id));
}
}
$this->render('update', array(
'form' => $form,
'model' => $model
));
}
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
{
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
else
{
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
}
public function actionManage()
{
if(!Yii::app()->request->getQuery('faq'))
{
$this->pageNotFound();
}
$model = new TestingFaqStage('search');
$model->unsetAttributes();
if(isset($_GET['TestingFaqStage']))
{
$model->attributes = $_GET['TestingFaqStage'];
}
$this->render('manage', array(
'model' => $model,
));
}
public function loadModel($id)
{
$model = TestingFaqStage::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-faq-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
class TestingGammaAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр гаммы продукции',
'Create' => 'Создание гаммы продукции',
'Update' => 'Редактирование гаммы продукции',
'Delete' => 'Удаление гаммы продукции',
'Manage' => 'Управление гаммами продукции',
);
}
public function actionView($id)
{
$this->render('view', array(
'model' => $this->loadModel($id),
));
}
public function actionCreate()
{
$model = new TestingGamma;
$form = new BaseForm('testings.TestingGammaForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingGamma']))
{
$model->attributes = $_POST['TestingGamma'];
if($model->save())
{
$this->redirect(array('manage'));
}
}
$this->render('create', array(
'form' => $form,
));
}
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$form = new BaseForm('testings.TestingGammaForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingGamma']))
{
$model->attributes = $_POST['TestingGamma'];
if($model->save())
{
$this->redirect(array('manage'));
}
}
$this->render('update', array(
'form' => $form,
));
}
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
{
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
else
{
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
}
public function actionManage()
{
$model=new TestingGamma('search');
$model->unsetAttributes();
if(isset($_GET['TestingGamma']))
{
$model->attributes = $_GET['TestingGamma'];
}
$this->render('manage', array(
'model' => $model,
));
}
public function loadModel($id)
{
$model = TestingGamma::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-gamma-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
class TestingMistakeAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр ошибки',
'Create' => 'Создание ошибки',
'Update' => 'Редактирование ошибки',
'Delete' => 'Удаление ошибки',
'Manage' => 'Управление ошибками',
);
}
public function actionView($passing)
{
$this->render('view', array(
'model' => TestingMistake::model()->find('passing_id = :passing',array(':passing'=>$passing)),
));
}
public function actionCreate($passing)
{
$model = new TestingMistake;
$form = new BaseForm('testings.TestingMistakeForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingMistake']))
{
$model->attributes = $_POST['TestingMistake'];
$model->passing_id = $passing;
if($model->save()) {
// назначение повторного тестирования
if (isset($_POST['retest'])) {
$pass = new TestingPassing;
$oldpass = TestingPassing::model()->findByPk($model->passing_id);
$pass->attributes = $oldpass->attributes;
$pass->is_passed = null;
$pass->pass_date = null;
$pass->attempt = 0;
$pass->pass_date_start = '';
$pass->save();
}
$this->redirect(array('/testings/testingPassingAdmin/manage','session'=>$model->passing->test->session_id));
}
}
$this->render('create', array(
'form' => $form,
));
}
public function actionUpdate($passing)
{
$model = TestingMistake::model()->find('passing_id = :passing',array(':passing'=>$passing));;
$form = new BaseForm('testings.TestingMistakeForm', $model);
// $this->performAjaxValidation($model);
if(isset($_POST['TestingMistake']))
{
$model->attributes = $_POST['TestingMistake'];
if($model->save())
{
// назначение повторного тестирования
if (isset($_POST['retest'])) {
$pass = new TestingPassing;
$oldpass = TestingPassing::model()->findByPk($model->passing_id);
$pass->attributes = $oldpass->attributes;
$pass->is_passed = null;
$pass->pass_date = null;
$pass->attempt = 0;
$pass->pass_date_start = '';
$pass->save();
}
$this->redirect(array('/testings/testingPassingAdmin/manage','session'=>$model->passing->test->session_id));
}
}
$this->render('update', array(
'form' => $form,
));
}
public function loadModel($id)
{
$model = TestingMistake::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-mistake-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\testings\models\TestingTest;
use common\modules\testings\models\TestingPassing;
use common\modules\testings\models\SearchTestingPassing;
use common\modules\testings\models\TestingSession;
use common\modules\testings\models\SearchTestingQuestionPassing;
use common\modules\testings\models\TestingQuestionPassing;
class TestingPassingAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр прохождения',
'Create' => 'Создание прохождения',
'Delete' => 'Удаление прохождения',
'Manage' => 'Управление прохождениями',
'Mistake' => 'Ошибка',
'Change-status' => 'Изменить статус',
'Change-answer-status' => 'Изменить статус ответа',
'Statistics' => 'Статистика прохождений',
'Re-attempt' => 'Переназначение теста'
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionView($id)
{
$searchModel = new SearchTestingQuestionPassing();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, null, null, $id);
return $this->render('view', [
'model' => $this->findModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'time' => $this->showPeriod($model->time),
]);
}
public function actionCreate($session)
{
$model = new TestingTest;
Yii::$app->controller->page_title = 'Добавить прохождение';
Yii::$app->controller->breadcrumbs = [
['Список прохождений' => '/testings/testing-passing-admin/manage'],
'Добавить прохождение'
];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['manage', 'session' => $session]);
} else {
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingPassingForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionMistake($id)
{
$model = $this->findModel($id);
if ($model->mistake)
{
return $this->redirect(['/testings/testingMistakeAdmin/view', 'passing' => $id]);
}
else
{
return $this->redirect(['/testings/testingMistakeAdmin/create', 'passing' => $id]);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
public function actionManage($session)
{
$searchModel = new SearchTestingPassing();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список прохождений';
Yii::$app->controller->breadcrumbs = [
'Список прохождений',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'session' => TestingSession::findOne($session),
]);
}
public function actionStatistics($session)
{
$searchModel = new SearchTestingPassing();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список прохождений';
Yii::$app->controller->breadcrumbs = [
'Список прохождений',
];
return $this->render('statistics', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'session' => TestingSession::findOne($session),
]);
}
private function showPeriod($time)
{
return sprintf("%02d:%02d:%02d", (int)($time / 3600), (int)(($time % 3600) / 60), $time % 60);
}
public function actionReAttempt($id)
{
$passing = $this->loadModel($id);
$passing->attempt = 0;
$passing->save(false, array('attempt'));
$subject = 'Тестирование - переназначение теста';
$body = Setting::getValue('email_reattempt_body');
$mailer_letter = MailerLetter::model();
$body = $mailer_letter->compileText($body, array(
'test_name' => $passing->test->name,
));
unset($mailer_letter);
$result = MailerModule::sendMailUniSender($passing->user->email, $subject, $body);
$this->render('reattempt', array(
'result' => $result
));
}
public function actionChangeAnswerStatus($qp_id)
{
$qp = TestingQuestionPassing::findOne($qp_id);
if ($qp)
{
if ($qp->user_answer == $qp->answer_text)
{
$qp->user_answer = 'Заведомо неправильный ответ';
}
else
{
$qp->user_answer = $qp->answer_text;
}
$qp->save();
$passing = $this->findModel($qp->passing_id);
if ($passing)
{
$passing->recountPassResult();
$passing->save();
}
}
$this->redirect($_SERVER['HTTP_REFERER']);
}
public function actionChangeStatus($user, $test)
{
$tp = TestingPassing::find()->where([
'user_id' => $user,
'test_id' => $test
])->one();
if ($tp)
{
$tp->delete();
}
else
{
$tp = new TestingPassing;
$tp->user_id = $user;
$tp->test_id = $test;
$tp->save();
}
$this->redirect($_SERVER['HTTP_REFERER']);
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestingPassing::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<?php
class TestingPassingController extends BaseController
{
public $layout = '/layouts/testing';
public $page_subtitle;
public static function actionsTitles()
{
return array(
'Index' => 'Просмотр прохождения',
'Session' => 'Прохождение сессии',
);
}
public function filters() {
return CMap::mergeArray(parent::filters(), array(
'checkAuth - login',
));
}
public function filterCheckAuth($filterChain) {
$data = explode('.', $_SERVER['SERVER_NAME']);
if(!in_array('www',$data))
$this->redirect('http://www.partnersnet.schneider-electric.ru/testings/testingPassing/');
if (!in_array(Yii::app()->user->role, array('schneider_electric', 'admin'))) {
$this->redirect('/login/');
}
$filterChain->run();
}
public function actionIndex() {
$sessions = TestingSession::model()->findAll();
$user = User::model()->findByPk(Yii::app()->user->id);
$cr = new CDbCriteria;
$cr->with = array('user', 'test');
$name = trim(implode(' ', array($user->last_name, $user->first_name, $user->patronymic)));
//echo $name = 'Алешин Алексей Евгеньевич';
//$cr->addCondition('user.tki = "'.$user->last_name.' '.$user->first_name.' '.$user->patronymic.'"');
$cr->compare('user.tki', $name, true);
//$cr->compare('user.manager_id', Yii::app()->user->id);
//$cr->limit = 300;
$cr->together = true;
$passings = TestingPassing::model()->findAll($cr);
//соотнесем тесты с сессиями
$tests_list = array();
$tests = TestingTest::model()->findAll();
foreach ($tests as $test) {
$tests_list[$test->id] = $test->session_id;
}
$tests = $tests_list;
//отсортируем сдачи тестов по сессиям
$passings_list = array();
foreach ($passings as $p) {
$session_id = $tests[$p->test_id];
$passings_list[$session_id][] = $p;
}
$passings = $passings_list;
$this->render('index', array('sessions' => $sessions, 'passings' => $passings));
}
}
<?php
class TestingPassingTKIController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр прохождения',
'Manage' => 'Управление прохождениями',
);
}
private function showPeriod($time) {
return sprintf("%02d:%02d:%02d", (int)($time / 3600), (int)(($time % 3600) / 60), $time % 60);
}
public function actionView($id)
{
$model = $this->loadModel($id);
$questions = new TestingQuestionPassing('search');
$questions->unsetAttributes();
$this->render('view', array(
'model' => $model,
'questions' => $questions,
'time' => $this->showPeriod($model->time),
));
}
public function actionManage($session=null)
{
$model = new TestingPassing('search');
$model->unsetAttributes();
if(isset($_GET['TestingPassing']))
{
$model->attributes = $_GET['TestingPassing'];
}
$this->render('manage', array(
'model' => $model,
'session' => $session ? TestingSession::model()->findByPk($session) : '',
'sessions' => TestingSession::model()->findAll(),
));
}
public function loadModel($id)
{
$model = TestingPassing::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-passing-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\testings\models\TestingQuestion;
use common\modules\testings\models\SearchTestingQuestion;
class TestingQuestionAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'View' => 'Просмотр вопроса',
'Create' => 'Создание вопроса',
'Update' => 'Редактирование вопроса',
'Delete' => 'Удаление вопроса',
'Manage' => 'Управление вопросами',
'UpdateAnswer' => 'Изменение ответов'
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new TestingQuestion;
Yii::$app->controller->page_title = 'Добавить вопрос';
Yii::$app->controller->breadcrumbs = [
['Список вопросов' => '/testings/testing-question-admin/manage'],
'Добавить вопрос'
];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['manage']);
} else {
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingQuestionForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionUpdate($id)
{
Yii::$app->controller->page_title = 'Редактировать вопрос';
Yii::$app->controller->breadcrumbs = [
['Список вопросов' => '/testings/testing-question-admin/manage'],
'Редактировать вопрос'
];
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['manage']);
} else {
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingQuestionForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
// public function actionManage()
// {
// $questions = array();//Вопросы с предупреждением о картинках
// //$param = 'карт, изобр, изображение, скриншот, картинка, схема, рисунок, рис';
// $param = trim(Setting::getValue('testings_questions_with_picture'));
// $words = empty($param) ? array() : explode(',', trim($param));
// $db = Yii::app()->db;
// if( isset($_GET['test']) && !empty($words)) {
// $where = array();
// for ($i = 0; $i < count($words); $i++) {
// $where[] = sprintf('%s LIKE trim(%s)',
// $db->quoteColumnName('text'),
// $db->quoteValue('%'.trim($words[$i]).'%'));
// }
// $where = implode(' OR ', $where);
// $sql = "SELECT id, `text` FROM testings_questions WHERE test_id = :test_id AND ($where)";
// $rows = $db->createCommand($sql)->queryAll(true, array('test_id' => $_GET['test']));
// foreach($rows as $row) {
// $questions[$row['id']] = $row['text'];
// }
// }
// $model=new TestingQuestion('search');
// $model->unsetAttributes();
// if(isset($_GET['TestingQuestion']))
// {
// $model->attributes = $_GET['TestingQuestion'];
// }
// $this->render('manage', array(
// 'model' => $model,
// 'questions' => $questions,
// 'questions_param' => $param,
// ));
// }
public function actionManage()
{
$searchModel = new SearchTestingQuestion();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список вопросов';
Yii::$app->controller->breadcrumbs = [
'Список вопросов',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionUpdateAnswer($id)
{
if (!Yii::app()->request->isAjaxRequest) {
throw new CException('Прямой доступ запрещен');
}
if (!isset($_POST['t']) && !isset($_POST['c']) && !isset($_POST['us']))
{
throw new CException('Не переданы необходимые параметры');
}
$user = unserialize($_POST['us']);
if ($user->getRole() != 'admin') {
throw new CException('Ошибка доступа');
}
if ((isset($_POST['q'])) && ($_POST['q'] == 'new')) {
$model = new TestingAnswer;
$model->question_id = $id;
echo $id;
}
else {
$model = TestingAnswer::model()->findByPk((int) $id);
if($model === null)
{
throw new CException('Запрошенный вопрос не существует');
}
}
$model->text = $_POST['t'];
$model->is_right = $_POST['c'];
if ($model->save())
{
echo $model->id;
}
else {
echo $model->id;
}
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestingQuestion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<?php
class TestingSendHistoryAdminController extends AdminController
{
public static function actionsTitles()
{
return array(
'Manage' => 'Управление пользователями',
'ResendDublicates' => '',
);
}
public function actionManage()
{
if(!Yii::app()->request->getQuery('session'))
{
$this->pageNotFound();
}
$model=new TestingSendHistory('search');
$model->unsetAttributes();
if(isset($_GET['TestingSendHistory']))
{
$model->attributes = $_GET['TestingSendHistory'];
}
$this->render('manage', array(
'model' => $model,
'session_id' => Yii::app()->request->getQuery('session')
));
}
public function actionResendDublicates()
{
if(Yii::app()->request->isAjaxRequest)
{
if(Yii::app()->request->getPost('email') && Yii::app()->request->getPost('id'))
{
$model = TestingSendHistory::model()->findByPK(Yii::app()->request->getPost('id'));
$path = Yii::getPathOfAlias('webroot') . TestingSendHistory::FOLDER_PATH;
$file = $path . $model->file;
if($model->file && file_exists($file))
{
$body = Setting::getValue('email_multiple_user_test_notice_body');
$subject = Setting::getValue('email_test_notice_head');
$mailer_letter = MailerLetter::model();
$body = $mailer_letter->compileText($body, array(
'test_link' => CHtml::link(Yii::app()->controller->createAbsoluteUrl('/testings/testingTest'), Yii::app()->controller->createAbsoluteUrl('/testings/testingTest')),
));
unset($mailer_letter);
$attachments = array(
$model->file => $file
);
MailerModule::sendMailUniSender(Yii::app()->request->getPost('email'), $subject, $body, $model, $attachments);
echo CJavaScript::jsonEncode(array(
'success' => true,
'message' => 'Отправка прошла успешно'
));
}
else
{
echo CJavaScript::jsonEncode(array(
'success' => false,
'message' => 'Файл возможно был удален!'
));
}
}
else
{
echo CJavaScript::jsonEncode(array(
'success' => false,
'message' => 'Данные введены не верно!'
));
}
}
else
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
public function loadModel($id)
{
$model = TestingSendHistory::model()->findByPk((int) $id);
if($model === null)
{
$this->pageNotFound();
}
return $model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax'] === 'testing-sendhistory-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\helpers\Html;
use common\modules\testings\models\TestingTest;
use common\modules\testings\models\SearchTestingTest;
use common\modules\testings\models\TestingQuestion;
use common\modules\testings\models\TestingTheme;
use common\modules\testings\models\TestingAnswer;
class TestingTestAdminController extends AdminController
{
public $errorSummaryCssClass = 'error-summary';
public $encodeErrorSummary;
public static function actionsTitles()
{
return array(
'View' => 'Просмотр теста',
'Create' => 'Создание теста',
'Update' => 'Редактирование теста',
'Delete' => 'Удаление теста',
'Manage' => 'Управление тестами',
'Import-tests' => 'Импорт вопросов и ответов к ним',
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new TestingTest;
Yii::$app->controller->page_title = 'Добавить тест';
Yii::$app->controller->breadcrumbs = [
['Список тестов' => '/testings/testing-test-admin/manage'],
'Добавить тест'
];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['manage']);
} else {
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingTestForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionUpdate($id)
{
Yii::$app->controller->page_title = 'Редактировать тест';
Yii::$app->controller->breadcrumbs = [
['Список тестов' => '/testings/testing-test-admin/manage'],
'Редактировать тест'
];
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['manage']);
} else {
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingTestForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
public function actionManage()
{
$searchModel = new SearchTestingTest();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список тестов';
Yii::$app->controller->breadcrumbs = [
'Список тестов',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionImportTests($id)
{
$model = new TestingTest;
$model->scenario = 'upload';
Yii::$app->controller->page_title = 'Импорт вопросов и ответов к ним';
Yii::$app->controller->breadcrumbs = [
'Импорт вопросов и ответов к ним',
];
$params = ['model' => $model];
if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post()))
{
$model->csv_file = UploadedFile::getInstance($model, 'csv_file');
if($model->upload())
{
try
{
$log = [];
set_time_limit(60*3); // Максимальное время выполнения скрипта - 3 минуты
$questionsCount = 0; // Кол-во загруженных вопросов
$themesCount = 0; // Кол-во тем (не только созданных)
$inputFileType = \PHPExcel_IOFactory::identify($model->file);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($model->file);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($i = 3; $i <= $highestRow; $i++)
{
// извлечение переменных из XLS
$theme_name = trim(preg_replace('/\s+/', ' ', $sheet->getCell('A' . $i)->getValue()));
$question_name = trim(preg_replace('/\s+/', ' ', $sheet->getCell('B' . $i)->getValue()));
$question_type = trim(preg_replace('/\s+/', ' ', $sheet->getCell('C' . $i)->getValue()));
$answer_name = trim(preg_replace('/\s+/', ' ', $sheet->getCell('D' . $i)->getValue()));
$answer_isright = trim($sheet->getCell('E' . $i)->getValue());
// поиск или создание темы
if ($theme_name <> '')
{
$themesCount++;
$theme = TestingTheme::find()->where(['name' => $theme_name])->one();
if(!$theme)
{
$theme = new TestingTheme;
$theme->name = $theme_name;
}
else
{
$log[] = 'Тема ' . $theme_name . ' уже существует.';
}
if(!$theme->save())
{
$log[] = 'Ошибка при сохранении темы "' . $theme_name . '"';
}
}
// создание вопроса
if ($question_name <> '')
{
$question = new TestingQuestion;
$question->text = $question_name;
$question->type = $question_type;
$question->test_id = $id;
$question->theme_id = $theme->id;
$question->is_active = TestingQuestion::ACTIVE;
if($question->save())
{
$questionsCount++;
}
else
{
$log[] = 'Ошибка при сохранении вопроса "' . $question_name . '"';
}
}
// создание ответа
$answer = new TestingAnswer;
$answer->text = $answer_name;
if (in_array($answer_isright, TestingAnswer::$xls_rights_list))
{
$answer->is_right = TestingAnswer::IS_RIGHT;
}
else
{
$answer->is_right = TestingAnswer::IS_NOT_RIGHT;
}
$answer->question_id = $question->id;
if (!$answer->save())
{
$log[] = 'Ошибка при сохранении ответа "' . $answer_name . '"';
}
}
// добавляем отчёт о кол-ве добавленных вопросов и гамм
Yii::$app->session->setFlash('flash', '<i>Всего добавлено <b>' . $questionsCount . '</b> вопросов в <b>' . $themesCount . '</b> темах. Перейти к ' . Html::a('списку загруженных вопросов', ['/testings/testing-question-admin/manage', 'test'=>$model->id]) . '.</i>');
$params['log'] = '<p>' . implode('</p><p>', $log) . '</p>';
}
catch (Exception $e)
{
$params['log'] = 'Импорт прошел неудачно: ' . $e->getMessage();
}
$model->deleteFile();
}
else
{
Yii::$app->session->setFlash('flash', 'Произошла ошибка при загрузке файла. Обратитесь к администратору!');
}
}
return $this->render('import-tests', $params);
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestingTest::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
This diff is collapsed.
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use common\modules\testings\models\TestingUser;
use common\modules\testings\models\SearchTestingUser;
use common\modules\testings\models\SearchTestingUserGroup;
class TestingUserAdminController extends AdminController
{
private $_marked;
public static function actionsTitles()
{
return array(
'View' => 'Просмотр пользователя',
'Create' => 'Создание пользователя',
'Update' => 'Редактирование пользователя',
'Delete' => 'Удаление пользователя',
'Manage' => 'Управление пользователями',
'Manage-group' => 'Управление группами',
'UpdateMark' => 'Пометка пользователй',
'ResetMark' => 'Сброс пометок',
);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new TestingUser;
Yii::$app->controller->page_title = 'Добавить пользователя';
Yii::$app->controller->breadcrumbs = [
['Список пользователей' => '/testings/testing-user-admin/manage'],
'Добавить пользователя'
];
if ($model->load(Yii::$app->request->post()))
{
$model->manager_id = Yii::app()->user->id;
if($model->validate())
{
$model->login = $model->generateLogin();
$model->password = PasswordGenerator::generate(6);
$model->save();
return $this->redirect(['manage']);
}
}
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingUserForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
public function actionUpdate($id)
{
Yii::$app->controller->page_title = 'Редактировать пользователя';
Yii::$app->controller->breadcrumbs = [
['Список пользователей' => '/testings/testing-user-admin/manage'],
'Редактировать пользователя'
];
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()))
{
$model->manager_id = Yii::app()->user->id;
if($model->validate())
{
$model->save();
return $this->redirect(['manage']);
}
}
$form = new \common\components\BaseForm('/common/modules/testings/forms/TestingAnswerForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['manage']);
}
public function actionManage()
{
$searchModel = new SearchTestingUser();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список назначений тестов пользователям';
Yii::$app->controller->breadcrumbs = [
'Список назначений тестов пользователям',
];
return $this->render('manage', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionManageGroup()
{
$searchModel = new SearchTestingUserGroup();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::$app->controller->page_title = 'Список групп';
Yii::$app->controller->breadcrumbs = [
'Список групп',
];
return $this->render('manage-group', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function getMarked($session)
{
$session = intval($session);
if(!isset($this->_marked[$session]))
{
$session_key = 'notify_session_'.$session;
if(isset(Yii::$app->session[$session_key]))
{
$data = unserialize(Yii::$app->session[$session_key]);
if($data === FALSE)
{
$data = [];
}
}
else
{
$data = [];
}
$this->_marked[$session] = $data;
}
return $this->_marked[$session];
}
public function setMarked($session, $data)
{
$session = intval($session);
$session_key = 'notify_session_'.$session;
$this->_marked[$session] = $data;
Yii::$app->session[$session_key] = serialize($data);
}
public function checkMark($data, $row)
{
return in_array($data->id, $this->getMarked());
}
public function actionUpdateMark($session)
{
if(!isset($_POST['data']) || !is_array($_POST['data']))
{
return;
}
$toggle = $_POST['data'];
$data = $this->getMarked($session);
$remove = []; $append = [];
foreach($toggle as $key => $value)
{
if($value)
{
$append[] = $key;
}
else
{
$remove[] = $key;
}
}
if(!empty($append))
{
$data = array_merge($data, $append);
}
$data = array_unique($data);
if(!empty($remove))
{
$data = array_diff($data, $remove);
}
$this->setMarked($session, $data);
$qty = count($data);
echo Json::encode([
'qty' => $qty,
'title' => "Разослать выделенным ($qty)",
]);
}
public function actionResetMark($session)
{
$this->setMarked($session, []);
echo Json::encode(array(
'qty' => 0,
'title' => "Разослать выделенным",
));
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestingUser::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
CREATE TABLE IF NOT EXISTS `bulkmail_accounts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server` varchar(50) NOT NULL COMMENT ' ',
`port` int(10) unsigned NOT NULL COMMENT ' ',
`email` varchar(50) NOT NULL COMMENT 'E-mail ',
`username` varchar(50) NOT NULL COMMENT ' ',
`password` varchar(50) NOT NULL COMMENT ' ',
`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `bulkmail_queue` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`emailTo` varchar(100) NOT NULL COMMENT 'Email ',
`subject` varchar(250) NOT NULL COMMENT ' ',
`body` text NOT NULL COMMENT ' ',
`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' ',
`send_date` timestamp NULL DEFAULT NULL COMMENT ' ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `bulkmail_state` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date_last` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' ',
`qtyTotal` int(11) NOT NULL COMMENT ' ',
`qtyMod` float NOT NULL COMMENT ' ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
\ No newline at end of file
INSERT INTO `settings` (`id`, `module_id`, `code`, `name`, `value`, `element`, `hidden`) VALUES
(39, 'testings', 'bulkmail_letters_per_hour', 'Количество отправляемых писем за 1 час', '40', 'text', 0),
(40, 'testings', 'bulkmail_cron_period', 'Период срабатывания CRON', '2', 'text', 0);
-- phpMyAdmin SQL Dump
-- version 3.3.7
-- http://www.phpmyadmin.net
--
-- : localhost
-- : 11 2011 ., 20:50
-- : 5.1.49
-- PHP: 5.3.3-1ubuntu9.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- : `schneider-electric`
--
-- --------------------------------------------------------
--
-- `testings`
--
CREATE TABLE IF NOT EXISTS `testings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL COMMENT '',
`minutes` tinyint(4) NOT NULL COMMENT ' ( )',
`percentage_passing` tinyint(4) NOT NULL COMMENT ' ( )',
`questions_count` tinyint(4) NOT NULL COMMENT ' ( )',
`date_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`date_update` datetime DEFAULT NULL COMMENT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- `testings`
--
-- --------------------------------------------------------
--
-- `testings_answers`
--
CREATE TABLE IF NOT EXISTS `testings_answers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) unsigned NOT NULL COMMENT '',
`text` text NOT NULL COMMENT '',
`is_correct` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '',
`date_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`date_update` datetime NOT NULL COMMENT '',
PRIMARY KEY (`id`),
KEY `question_id` (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- `testings_answers`
--
-- --------------------------------------------------------
--
-- `testings_questions`
--
CREATE TABLE IF NOT EXISTS `testings_questions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`section_id` int(11) unsigned DEFAULT NULL COMMENT '',
`difficulty` enum('hard','easy') NOT NULL COMMENT '',
`type` enum('one_option','several_options','own_version') NOT NULL COMMENT ' ',
`text` text NOT NULL COMMENT '',
`image` varchar(37) DEFAULT NULL COMMENT '',
`is_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT '',
`date_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`date_update` datetime NOT NULL COMMENT '',
PRIMARY KEY (`id`),
KEY `section_id` (`section_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- `testings_questions`
--
-- --------------------------------------------------------
--
-- `testings_sections`
--
CREATE TABLE IF NOT EXISTS `testings_sections` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(11) unsigned DEFAULT NULL COMMENT '',
`name` varchar(150) NOT NULL COMMENT '',
`is_active` tinyint(1) NOT NULL COMMENT '',
`date_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`date_update` datetime NOT NULL COMMENT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- `testings_sections`
--
--
--
--
--
-- `testings_answers`
--
ALTER TABLE `testings_answers`
ADD CONSTRAINT `testings_answers_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `testings_questions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- `testings_questions`
--
ALTER TABLE `testings_questions`
ADD CONSTRAINT `testings_questions_ibfk_1` FOREIGN KEY (`section_id`) REFERENCES `testings_sections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- `testings_sections`
--
ALTER TABLE `testings_sections`
ADD CONSTRAINT `testings_sections_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `testings_sections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
This diff is collapsed.
<?xml version="1.0" encoding="utf-8" ?>
<!--
-
- phpMyAdmin XML Dump
- version 2.11.10
- http://www.phpmyadmin.net
-
- Хост: localhost
- Время создания: Окт 12 2011 г., 21:06
- Версия сервера: 5.0.37
- Версия PHP: 5.2.5
-->
<!--
- База данных: 'partners_schneider'
-->
<partners_schneider>
<!-- Таблица gammas -->
<gammas>
<theme_id>1</theme_id>
<gamma_name>Кабеленесущие системы Thorsman, Wibe, Stago, Schneider Electric</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>1</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Низковольтные шкафы Prisma Plus и Prisma Pack</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>2</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Автоматические выключатели, УЗО и Дифференциальные автоматы серии Домовой</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>3</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Мини-контроллеры</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>4</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Вспомогательное оборудование автоматизации</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>5</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Компактные панели оператора Magelis</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>6</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Шкафы Spacial</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>7</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Датчики гаммы Global Detection</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>8</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Кнопки</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>9</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Устройства контроля и управления гамм Acti 9, Multi 9</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>10</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Автоматические выключатели, УЗО, щитки гамм Acti 9, Multi 9</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>11</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>ATV, ATS</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>12</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Автоматические выключатели Masterpact</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>13</gamma_id>
</gammas>
<gammas>
<theme_id>1</theme_id>
<gamma_name>Автоматические выключатели Compact и выключатели-разъединители Interpact</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>14</gamma_id>
</gammas>
<gammas>
<theme_id>2</theme_id>
<gamma_name>Контакторы</gamma_name>
<gamma_act>1</gamma_act>
<gamma_date></gamma_date>
<gamma_utime>0</gamma_utime>
<gamma_id>15</gamma_id>
</gammas>
</partners_schneider>
<?php
use yii\helpers\ArrayHelper;
use common\modules\testings\models\TestingQuestion;
use common\modules\testings\models\TestingAnswer;
$elements = [
'question_id' => [
'type' => 'dropdownlist',
'items' => ArrayHelper::map(TestingQuestion::find()->all(), 'id', 'text', 'test.name'),
],
'text' => ['type' => 'textarea'],
'is_right' => [
'type' => 'dropdownlist',
'items' => TestingAnswer::$type_list,
],
];
// если id указан одним из параметров запроса - не показываем это поле
if (\Yii::$app->request->get('question'))
{
$elements['question_id'] = [
'type' => 'hidden',
'value' => \Yii::$app->request->get('question'),
];
}
return [
'activeForm'=>[
'id' => 'testing-answer-form',
],
'elements' => $elements,
'buttons' => [
'submit' => ['type' => 'submit', 'value' => 'Cохранить']
]
];
<?php
$buttons = array(
'submit' => array(
'type' => 'submit',
'value' => 'сохранить',
),
);
return array(
'activeForm' => array(
'id' => 'bulkmail-account-form',
//'enableAjaxValidation' => true,
//'clientOptions' => array(
// 'validateOnSubmit' => true,
// 'validateOnChange' => true
//)
),
'elements' => array(
'server' => array('type' => 'text'),
'port' => array('type' => 'text'),
'smtp_secure' => array('type' => 'dropdownlist', 'items' => array('' => '', 'ssl' => 'SSL', 'tls' => 'TLS')),
'email' => array('type' => 'text'),
'username' => array('type' => 'text'),
'password' => array('type' => 'text'),
//'create_date' => array('type' => 'text'),
),
'buttons' => $buttons,
);
<?php
$crit = new CDbCriteria;
$crit->distinct = true;
$crit->select = "company_name";
$crit->order = "company_name";
$companies = TestingUser::model()->findAll($crit);
$list = '<dl class="dropdownlist">
<dd>
<label class="required" for="TestingPassing_company">Компания <span class="required">*</span></label>
<select id="TestingPassing_company" name="TestingPassing[company]" class="dropdownlist cmf-skinned-select">';
foreach ($companies as $comp)
{
$list.= '<option value="'.htmlspecialchars($comp->company_name).'">'.$comp->company_name.'</option>';
}
$list.= '</select></dd></dl>';
return array(
'activeForm' => array(
'id' => 'testing-passing-form',
),
'elements' => array(
$list,
'test_id' => array(
'type' => 'dropdownlist',
'items' => CHtml::listData(TestingTest::model()->findAll(),'id','name','session.name'),
),
'end_date' => array(
'type' => 'application.extensions.CJuiDateTimePicker.CJuiDateTimePicker',
'htmlOptions' => array('class'=>'text')
),
),
'buttons' => array(
'submit' => array(
'type' => 'submit',
'value' => 'Записать')
)
);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?php
return [
'activeForm'=>[
'id' => 'testing-test-form',
],
'elements' => [
'name' => ['type' => 'text'],
'start_date' => ['type' => 'datetime', 'htmlOptions' => ['class'=>'text']],
'end_date' => ['type' => 'datetime', 'htmlOptions' => ['class'=>'text']],
],
'buttons' => [
'submit' => ['type' => 'submit', 'value' => 'Cохранить']
]
];
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment