예제 #1
0
 /**
  * Sends an email to the specified email address using the information collected by this model.
  * @return boolean whether the model passes validation
  */
 public function add()
 {
     if ($this->validate()) {
         $code = new Code(['code' => $this->code, 'language' => $this->language, 'author' => $this->author, 'title' => $this->title, 'description' => $this->description, 'approved' => 0, 'ip' => ip2long(Yii::$app->request->userIP)]);
         if (!$code->save()) {
             return false;
         }
         $this->sendMails($code);
         return true;
     } else {
         return false;
     }
 }
예제 #2
0
 public static function generateCode($poll_id, $member_id)
 {
     $code = new Code();
     $code->member_id = $member_id;
     $code->poll_id = $poll_id;
     $length = 10;
     $code->token = Yii::$app->getSecurity()->generateRandomString($length);
     // Better safe than sorry, avoid collisions.
     while (!$code->validate(['token'])) {
         $code->token = Yii::$app->getSecurity()->generateRandomString($length);
     }
     return $code;
 }
 /**
  * Execute the job.
  *
  * @param Code $code
  * @return bool
  */
 public function handle(Code $code)
 {
     /** @var Code $result */
     $result = $code->whereCode($this->code)->firstOrFail();
     /**
      * Check if already there is an user associated with this code
      */
     if ($result->user) {
         return false;
     }
     $result->setAttribute('status', true);
     $result->user()->associate($this->user);
     $result->save();
     return true;
 }
 public function actionClean()
 {
     Code::updateAll(['used' => 0, 'status' => 0]);
     Meta::deleteAll();
     Result::deleteAll();
     return $this->redirect(['/system/statistic']);
 }
예제 #5
0
 public function getCode()
 {
     if ($this->_code === false) {
         $this->_code = Code::findCodeByToken($this->token);
     }
     return $this->_code;
 }
예제 #6
0
 public function search($params)
 {
     $query = Member::find()->indexBy('id');
     $query->poll_id($this->poll_id);
     $query->distinct();
     // also possible is to group by member.id to get only the unique member entries.
     //$query->addGroupBy($this->tableName().'.id');
     // $query->with('codes.vote'); // old join
     //$query->joinWith('codes', false, 'LEFT JOIN');
     //$query->joinWith('codes.vote', true, 'LEFT JOIN');
     // $query->joinWith(['relationname' => function ($query) {
     //     $query->from(['alias' => 'tablename']);
     // }]);
     // $query->joinWith(['codes' => function ($query) {
     //     $query->from(['codes' => 'code']);
     // }]);
     $query->joinWith(['codes.vote']);
     $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['name' => SORT_ASC]], 'pagination' => ['pageSize' => 20]]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'created_by' => $this->created_by, 'updated_by' => $this->updated_by]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'group', $this->group]);
     //if code CODE_STATUS_INVALID_UNUSED is searched also search for CODE_STATUS_INVALID_USED
     if ($this->getAttribute('codes.code_status') == Code::CODE_STATUS_INVALID_UNUSED) {
         $query->andWhere([Code::tableName() . '.code_status' => [Code::CODE_STATUS_INVALID_UNUSED, Code::CODE_STATUS_INVALID_USED]]);
     } else {
         $query->andFilterWhere(['=', Code::tableName() . '.code_status', $this->getAttribute('codes.code_status')]);
     }
     return $dataProvider;
 }
예제 #7
0
 public function beforeAction($action)
 {
     $request = Yii::$app->getRequest();
     $response = Yii::$app->getResponse();
     $token = $this->getToken();
     // if (!$token) {
     //     throw new HttpException(400, Yii::t('app', 'No Token given.'));
     // }
     $code = Code::findCodeByToken($token);
     // if (!$code) {
     //     throw new NotFoundHttpException(Yii::t('app', 'Code not found.'));
     // }
     $poll = $code->getPoll()->one();
     $now = new \DateTime('now', new \DateTimeZone('UTC'));
     $startTime = new \DateTime($poll->start_time, new \DateTimeZone('UTC'));
     $endTime = new \DateTime($poll->end_time, new \DateTimeZone('UTC'));
     if ($now < $startTime) {
         $this->handleNotStarted($response);
         return false;
     }
     if ($now >= $endTime) {
         $this->handleOver($response);
         return false;
     }
     return true;
 }
 /**
  * Creates a new Code model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Code();
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $count = $model->count;
         $codes = [];
         for ($i = 0; $i < $count; $i++) {
             $codeModel = clone $model;
             $codeModel->code = Code::generateCode();
             $codeModel->used = 0;
             $codeModel->save();
             $codes[] = $codeModel->z_b_id . str_pad($codeModel->z_p_id, 3, '0', STR_PAD_LEFT) . $codeModel->code;
         }
         return $this->render('create-summary', ['codes' => $codes, 'bank' => Bank::findOne($codeModel->z_b_id), 'count' => $count]);
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
예제 #9
0
 public function validateCode()
 {
     $code = substr($this->code, -4, 4);
     $bank = substr($this->code, 0, strlen($this->code) - 7);
     $code = Code::findOne(['z_b_id' => $bank, 'code' => $code]);
     if (!$code) {
         return false;
     } else {
         return $code;
     }
 }
예제 #10
0
 public function search($params)
 {
     $query = Code::find()->indexBy('id');
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 20]]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'poll_id' => $this->poll_id, 'member_id' => $this->member_id, 'code_status' => $this->code_status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'created_by' => $this->created_by, 'updated_by' => $this->updated_by]);
     $query->andFilterWhere(['like', 'token', $this->token]);
     return $dataProvider;
 }
예제 #11
0
 public function actionSubmit()
 {
     $token = Yii::$app->request->get('token');
     // Better way to get this?
     $code = Code::findCodeByToken($token);
     if (!$code || !$code->isValid()) {
         throw new UserException(Yii::t('app', 'Invalid voting code'));
     } elseif ($code->isUsed()) {
         throw new UserException(Yii::t('app', 'This voting code has already been used'));
     }
     $poll = $code->getPoll()->with('options')->one();
     $data = Yii::$app->request->getBodyParams();
     $optionIDs = $data['options'];
     if ($optionIDs === null || !is_array($optionIDs)) {
         throw new UserException(Yii::t('app', 'Bad Request'));
     }
     if (count($optionIDs) < $poll->select_min) {
         throw new UserException(Yii::t('app', 'Too few options selected'));
     }
     if (count($optionIDs) > $poll->select_max) {
         throw new UserException(Yii::t('app', 'Too many options selected'));
     }
     $transaction = Yii::$app->db->beginTransaction();
     $vote = new Vote();
     $vote->code_id = $code->id;
     if (!$vote->save()) {
         throw new UserException(Yii::t('app', 'Something went wrong'));
     }
     foreach ($optionIDs as $optionId) {
         $option = $poll->getOptions()->where(['id' => $optionId])->one();
         if (!$option) {
             $transaction->rollBack();
             throw new UserException(Yii::t('app', 'Invalid option'));
         }
         try {
             $vote->link('options', $option);
         } catch (Exception $e) {
             $transaction->rollBack();
             throw new UserException(Yii::t('app', 'Something went wrong'));
         }
     }
     $code->code_status = Code::CODE_STATUS_USED;
     if (!$code->save()) {
         $transaction->rollBack();
         throw new UserException(Yii::t('app', 'Something went wrong'));
     }
     $transaction->commit();
     // Log the vote in the vote log file.
     $arrayString = implode(", ", $optionIDs);
     $arrayString = "[{$arrayString}]";
     Yii::info("{$code->token} {$arrayString}", 'vote');
     return $data;
 }
예제 #12
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Code::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $query->andFilterWhere(['z_b_id' => $this->z_b_id]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     if (!$this->status) {
         $query->andFilterWhere(['status' => $this->status]);
     } else {
         $query->andFilterWhere(['>', 'status', $this->status]);
     }
     $query->andFilterWhere(['like', 'code', $this->code]);
     return $dataProvider;
 }
예제 #13
0
 public function actionChangeStatus()
 {
     $id = Yii::$app->request->getQueryParam('id');
     $status = Yii::$app->request->getQueryParam('status');
     $code = Code::findOne($id);
     if ($code == null) {
         throw new NotFoundHttpException(Yii::t('happycode', 'Given ID was not found in database.'));
     }
     $code->approved = $status;
     $code->save();
     $message = Yii::t('happycode', $status == 1 ? 'Paste <strong>#{id}</strong> was successfully approved.' : 'Paste <strong>#{id}</strong> was successfully declined.', ['id' => $id]);
     if (Yii::$app->request->isAjax) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ['id' => $id, 'status' => $status, 'message' => $message];
     } else {
         AlertHelper::appendAlert('success', $message);
         return $this->redirect(['admin/pending']);
     }
 }
예제 #14
0
 public function actionGet()
 {
     $token = Yii::$app->request->get('token');
     // Better way to get this?
     $code = Code::findCodeByToken($token);
     if (!$code || !$code->isValid()) {
         throw new UserException(Yii::t('app', 'Invalid voting code'));
     } elseif ($code->isUsed()) {
         throw new UserException(Yii::t('app', 'This voting code has already been used'));
     }
     $poll = $code->getPoll()->with(['options', 'organizer'])->one();
     $options = $poll->getOptions()->all();
     $organizer = $poll->getOrganizer()->one();
     $pollFields = ['title', 'question', 'info', 'select_min', 'select_max', 'start_time', 'end_time'];
     $data = ArrayHelper::merge($poll->toArray($pollFields), ['options' => ArrayHelper::getColumn($options, function ($option) {
         $optionFields = ['id', 'text'];
         return $option->toArray($optionFields);
     }), 'organizer' => $organizer->toArray(['name', 'email'])]);
     return $data;
 }
예제 #15
0
 public function validateCode()
 {
     $code = substr($this->code, -4, 4);
     $bank = substr($this->code, 0, strlen($this->code) - 7);
     $code = Code::findOne(['z_b_id' => $bank, 'code' => $code]);
     $original = $this->code;
     if (!$code) {
         $this->addError('z_b_id', 'Bank gesperrt, Code ungültig oder bereits verwendet. Anmeldung fehlgeschlagen');
         return false;
     } else {
         if (!$code->groupNotLocked('z_p_id') || !$code->bankNotLocked('z_b_id')) {
             $errors = $code->getFirstErrors();
             foreach ($errors as $error => $attribute) {
                 $this->addError($attribute, $error);
             }
             return false;
         } else {
             return array('code' => $code, 'original' => $original);
         }
     }
 }
예제 #16
0
 public function beforeAction($action)
 {
     $request = Yii::$app->getRequest();
     $response = Yii::$app->getResponse();
     if ($this->shouldBlockIP($request)) {
         // The IP is spamming invalid codes and should be blocked.
         $this->handleBlocked($response);
     }
     $token = $this->getToken();
     if ($token === null) {
         return true;
     }
     if (!is_string($token)) {
         // Value is not a string for whatever reason.
         $this->handleInvalid($request, $response);
     }
     $code = Code::findCodeByToken($token, get_class($this));
     if ($code === null || !$code->isValid()) {
         // The code is not valid.
         $this->handleInvalid($request, $response);
     }
     return true;
 }
예제 #17
0
 public function actionIndex()
 {
     $this->redirect('home/cqssc');
     $type = \Yii::$app->request->get('type') ? \Yii::$app->request->get('type') : 1;
     $data = Code::find()->where(['type' => $type])->orderBy('time DESC');
     $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '3']);
     $model = $data->offset($pages->offset)->limit($pages->limit)->all();
     if ($page = \Yii::$app->request->get('page')) {
         if (intval(ceil($data->count() / 3)) < $page) {
             return false;
         }
         return $this->renderAjax('_list', ['model' => $model]);
     }
     return $this->render('index', ['model' => $model]);
     /*
     $type = 1;
     if(\Yii::$app->request->get('type')){
         $type = \Yii::$app->request->get('type');
     }
     $model = Code::find()->where(['type'=>$type])->orderBy('time DESC')->all();
     return $this->render('index',['model'=>$model]);
     */
 }
예제 #18
0
 public function beforeAction($action)
 {
     $request = Yii::$app->getRequest();
     $response = Yii::$app->getResponse();
     $token = $this->getToken();
     if ($token === null) {
         // Query parameter not provided.
         $this->handleNoToken($response);
     }
     if (!is_string($token)) {
         // Value is not a string for whatever reason.
         $this->handleInvalid($request, $response);
     }
     $code = Code::findCodeByToken($token, get_class($this));
     if ($code === null || !$code->isValid()) {
         // The code is not valid.
         $this->handleInvalid($request, $response);
     } elseif ($code->isUsed()) {
         // The code has already been used.
         $this->handleUsed($response);
     }
     $this->handleSuccess($code);
     return true;
 }
예제 #19
0
 public function actionSendmultiple()
 {
     $poll = $this->getPoll();
     $email = new EmailForm(['scenario' => EmailForm::SCENARIO_MULTIPLE_EMAIL]);
     if ($email->load(Yii::$app->request->post()) && $email->validate()) {
         $members = [];
         if (intval($email->sendMode) === EmailForm::EMAIL_TO_ALL) {
             $members = Member::find()->where($this->getPollSearchOptions())->with('codes')->with('contacts')->all();
         } elseif (intval($email->sendMode) === EmailForm::EMAIL_TO_UNUSED) {
             $codes = Code::find()->where($this->getPollSearchOptions())->valid()->unused()->with('member.contacts')->all();
             $members = ArrayHelper::getColumn($codes, 'member');
         } elseif (intval($email->sendMode) === EmailForm::EMAIL_TO_USED) {
             $codes = Code::find()->where($this->getPollSearchOptions())->valid()->used()->with('member.contacts')->all();
             $members = ArrayHelper::getColumn($codes, 'member');
         }
         // Count successful and failed emails.
         $success = 0;
         $failure = 0;
         foreach ($members as $member) {
             set_time_limit(6);
             // 6 seconds for each email to render
             if ($this->sendEmailToMember($email, $member)) {
                 $success++;
             } else {
                 $failure++;
             }
         }
     }
     if ($success > 0) {
         Yii::$app->getSession()->addFlash('success', Yii::t('app', 'Successfully sent {n, plural, =0{no Email} =1{one Email} other{# Emails}}!', ['n' => $success]));
     }
     if ($failure > 0) {
         Yii::$app->getSession()->addFlash('error', Yii::t('app', 'Failed to send {n, plural, =0{no Email} =1{one Email} other{# Emails}}!', ['n' => $failure]));
     }
     return $this->redirect(['poll/view', 'id' => $poll->id, 'tab' => 'members']);
 }
 public function actionForm()
 {
     if (!isset(Yii::$app->session['anketData'])) {
         $this->redirect('/site/index');
     }
     $data = Yii::$app->session['anketData'];
     $form = Form::findOne($data['form']);
     $questions = $form->getQuestions();
     $status = Code::findOne($data['code']['z_id'])->status;
     if (Yii::$app->request->post('q')) {
         $userAnswers = Yii::$app->request->post('q');
         $status = $form->saveAnswers($data['code'], $userAnswers);
         $data['status'] = $status;
         $data['code']['status'] = $status;
     }
     Yii::$app->session['anketData'] = $data;
     if (!($status < $form->getQuestionsCount($questions))) {
         $code = Code::findOne($data['code']['z_id']);
         $code->used = 1;
         $code->save();
         $this->redirect('/site/end');
     }
     return $this->render('form', ['status' => $status, 'percent' => round($status / $form->getQuestionsCount($questions) * 100), 'questions' => $questions, 'anket' => $form, 'bank' => $data['bank']['b_id']]);
 }
예제 #21
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Code::find();
     $pageSize = Yii::$app->session->get('pageSize', Yii::$app->params['defaultPageSize']);
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $pageSize]]);
     $dataProvider->setSort(['attributes' => ['code', 'z_p_id', 'status', 'fillingDate' => ['asc' => ['{{%meta}}.time_start' => SORT_ASC], 'desc' => ['{{%meta}}.time_start' => SORT_DESC], 'label' => 'Filling Date'], 'duration' => ['asc' => ['{{%meta}}.time_end' => SORT_ASC], 'desc' => ['{{%meta}}.time_end' => SORT_DESC], 'label' => 'Duration']]]);
     /*$query->andFilterWhere([
     			'z_b_id' => $this->z_b_id,
     		]);*/
     if (!($this->load($params) && $this->validate())) {
         $query->joinWith(['meta']);
         return $dataProvider;
     }
     if (!$this->status) {
         $query->andFilterWhere(['status' => $this->status]);
     } else {
         $query->andFilterWhere(['>', 'status', $this->status]);
         if ($this->status == 1) {
             $query->andFilterWhere(['=', 'used', 0]);
         } else {
             $query->andFilterWhere(['=', 'used', 1]);
         }
     }
     if (isset($this->z_p_id) && !empty($this->z_p_id)) {
         $query->andFilterWhere(['z_p_id' => $this->z_p_id]);
     }
     $query->andFilterWhere(['like', 'CONCAT("' . $this->z_b_id . '", LPAD(`z_p_id`,3,"0"),`code`)', $this->code]);
     $query->joinWith(['meta' => function ($q) {
         if (isset($this->z_id) && !empty($this->z_id)) {
             $q->where('{{%meta}}.m_z_id = "' . $this->z_id . '"');
         }
     }]);
     //echo $query->createCommand()->getRawSql();
     //exit();
     return $dataProvider;
 }
 public function actionDeleteCode($bankId, $cid)
 {
     Code::findOne($cid)->delete();
     return $this->redirect(['bank/' . $bankId . '/codes']);
 }
예제 #23
0
 public function actionPaste()
 {
     $id = Yii::$app->request->getQueryParam('id');
     $model = Code::findOne($id);
     return $this->render('paste', ['model' => $model]);
 }
예제 #24
0
 public function afterSave($insert, $changedAttributes)
 {
     Code::recalculateScore($this->snippet_id);
     parent::afterSave($insert, $changedAttributes);
     // TODO: Change the autogenerated stub
 }
예제 #25
0
 /**
  * Efface la ressource de la bd en utilisant son Id.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     try {
         $code = Code::findOrFail($id);
         $code->delete();
     } catch (ModelNotFoundException $e) {
         App::abort(404);
     }
     return Redirect::action('CodesController@index');
 }
예제 #26
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getCodes()
 {
     return $this->hasMany(Code::className(), ['member_id' => 'id']);
 }
예제 #27
0
        ?>
</span>
                                    <?php 
    }
    ?>
                                    <span class="caret"></span>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-right">
                                    <li><a href="<?php 
    echo Url::to(['admin/pending']);
    ?>
"><?php 
    echo Yii::t('happycode', 'Pending');
    ?>
 <span class="badge"><?php 
    echo \app\models\Code::countPending();
    ?>
</span></a></li>
                                    <li><a href="<?php 
    echo Url::to(['admin/add-admin']);
    ?>
"><?php 
    echo Yii::t('happycode', 'Add admin');
    ?>
</a></li>
                                    <li><a href="<?php 
    echo Url::to(['admin/test-email']);
    ?>
"><?php 
    echo Yii::t('happycode', 'Test Email');
    ?>
예제 #28
0
파일: Analysis.php 프로젝트: aiyeyun/grab
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getCodi()
 {
     return $this->hasOne(Code::className(), ['id' => 'codi_id']);
 }
예제 #29
0
파일: Grab.php 프로젝트: aiyeyun/grab
 function find($qihao, $urlName, $codeArr, $code_id)
 {
     sort($codeArr);
     //数组从小到大排序 用户需求
     //数据分析
     $config = Configure::findOne(['type' => 1]);
     //系统报警配置
     //记录中奖与未中奖号码
     $model = Comparison::findOne(['type' => 1]);
     $data = $model->txt;
     $dataTxts = str_replace("\r\n", ' ', $data);
     //将回车转换为空格
     $dataArr = explode(' ', $dataTxts);
     $dataArr = array_filter($dataArr);
     $dataArr = array_chunk($dataArr, 5);
     //当前开奖号码 对比 数据库
     $lucky = array();
     //中奖号
     $regret = $dataArr;
     //未中奖号
     foreach ($dataArr as $key => $val) {
         sort($val);
         // 从小到大排序
         if ($codeArr == $val) {
             //中奖号组
             array_push($lucky, $val);
             unset($regret[$key]);
         }
     }
     //将中奖与未中奖的数组 转换为用户上传数据本的 格式 存入数据库
     $luckyStr = null;
     $regretStr = null;
     if (count($lucky) != 0) {
         //有中奖号码 记录数据库
         foreach ($lucky as $luc) {
             foreach ($luc as $l) {
                 $luckyStr .= $l . ' ';
             }
             $luckyStr .= "\r\n";
         }
     }
     if (count($regret) != 0) {
         //有未中奖号码 记录数据库
         foreach ($regret as $reg) {
             foreach ($reg as $r) {
                 $regretStr .= $r . ' ';
             }
             $regretStr .= "\r\n";
         }
     }
     //分析数据本与当前这期开奖号码 记录数据本里面 中奖号码与未中奖的号码 到数据库中
     $analysis = new Analysis();
     $analysis->codi_id = $code_id;
     $analysis->lucky_txt = $luckyStr;
     $analysis->regret_txt = $regretStr;
     $analysis->data_txt = $data;
     $analysis->time = time();
     $analysis->save();
     if ($config->state == 1) {
         //系统开启邮件 通知
         if (date('H', time()) > intval($config->start_time) && date('H', time()) < intval($config->end_time)) {
             //            if(true){
             //报警时间段内
             if ($config->forever == 1) {
                 //每一期 邮件通知打开
                 $cfg = array('type' => 1, 'qihao' => $qihao, 'codeArr' => $codeArr, 'urlName' => $urlName, 'luckyStr' => $luckyStr, 'regretStr' => $regretStr);
                 $this->send($cfg);
             }
             // 用户设置 几期都未中奖 报警通知
             $NewestCodes = Code::find()->orderBy('time DESC')->limit($config->regret_number)->all();
             if (count($NewestCodes) == $config->regret_number) {
                 //所有的最新的数据 必须 等于 用户设置的报警期数
                 $codeLucky = true;
                 foreach ($NewestCodes as $codeold) {
                     if (!empty($codeold->analysis->lucky_txt)) {
                         //N 期内有中奖 不发送报警
                         $codeLucky = false;
                         break;
                     }
                 }
                 if ($codeLucky) {
                     //发送报警通知 当前 $config->regret_number 内 都未中奖
                     $cfg = array('type' => 2, 'regret_number' => $config->regret_number, 'NewestCodes' => $NewestCodes);
                     $this->send($cfg);
                 }
             }
         }
     }
 }
예제 #30
0
 public static function countPending()
 {
     static $count = null;
     return $count === null ? $count = Code::find()->where(['approved' => 0])->count() : $count;
 }