Example #1
0
 /**
  * отправить письмо для отзыва по заказу
  */
 public function actionResponseReview()
 {
     // пройтись по всем response у который confirmation_date NOT NULL && > 5 day
     // из них выделить тех , у которых :
     //      не было отзыва со стороны from_company_id (site_review.response_id.from_company_id)
     //      не отсылалось письмо, с предложением об отзыве response.offer_to_review IS NULL
     Yii::app()->getModule('rbac');
     Yii::app()->getModule('dictionary');
     Yii::app()->getModule('cabinet');
     $arrResponse = Response::model()->with(['review' => ['select' => false, 'joinType' => 'LEFT JOIN', 'on' => 't.from_company_id = review.from_company_id', 'condition' => implode(' AND ', ['t.confirmation_date IS NOT NULL', '( DAY(NOW()) - DAY(t.confirmation_date) >= 5 )', 'review.review_id IS NULL', 't.offer_to_review IS NULL'])]])->findAll();
     //Yii::log("actionResponseReview arrResponse=[".print_r( $arrResponse , true )."]","info");
     if (count($arrResponse)) {
         if (isset(Yii::app()->params['site_url'])) {
             $domain = Yii::app()->params['site_url'];
         } else {
             $domain = "http://" . Yii::app()->getModule('yupe')->siteName;
         }
         foreach ($arrResponse as $Response) {
             $responseUrl = "{$domain}/response/{$Response->response_id}";
             $successSend = true;
             try {
                 Yii::app()->mailMessage->raiseMailEvent('USER_SUPPLIER_REVIEW', ['{user_email}' => $Response->user->email, '{site_name}' => Yii::app()->getModule('yupe')->siteName, '{site_response}' => "<a href=\"{$responseUrl}\">{$responseUrl}</a>", '{site_review}' => "<a href=\"{$domain}/cabinet/review/create/{$Response->response_id}\">сюда</a>"]);
             } catch (\Exception $e) {
                 $successSend = false;
                 Yii::log("actionResponseReview exception=[" . $e->getMessage() . "]", "error");
             }
             if ($successSend) {
                 // записать что письмо отправилось
                 $Response->offer_to_review = new \CDbExpression('NOW()');
                 $Response->save();
             }
         }
     }
 }
Example #2
0
 public function run()
 {
     if (!is_null($this->response_id) && !Yii::app()->getUser()->getIsGuest()) {
         $Response = Response::model()->findByPk($this->response_id);
         if (!is_null($Response) && !is_null($Response->confirmation_date)) {
             //$currentUserCompanyId = Yii::app()->user->getProfile()->company_id;
             //if ( $currentUserCompanyId == $Response->from_company_id ) {
             if ($this->isSendData($Response)) {
                 // только from_company может отправлять данные точек
                 // теперь можно выдать данные
                 if (Yii::app()->request->isAjaxRequest) {
                     // данные точек, берутся из cabinet TransportController::actionAvtoparkTrackingList
                     // тут ничего делать не надо
                 } else {
                     // текст и скрипты
                     $this->render('index', ['Response' => $Response]);
                 }
             }
         }
     }
 }
/**
* checkCompletedQuota() returns matched quotas information for the current response
* @param integer $surveyid - Survey identification number
* @param bool $return - set to true to return information, false do the quota
* @return array|void - nested array, Quotas->Members->Fields, includes quota information matched in session.
*/
function checkCompletedQuota($surveyid, $return = false)
{
    /* Check if session is set */
    if (!isset(App()->session['survey_' . $surveyid]['srid'])) {
        return;
    }
    /* Check is Response is already submitted : only when "do" the quota: allow to send information about quota */
    $oResponse = Response::model($surveyid)->findByPk(App()->session['survey_' . $surveyid]['srid']);
    if (!$return && $oResponse && !is_null($oResponse->submitdate)) {
        return;
    }
    static $aMatchedQuotas;
    // EM call 2 times quotas with 3 lines of php code, then use static.
    if (!$aMatchedQuotas) {
        $aMatchedQuotas = array();
        $quota_info = $aQuotasInfo = getQuotaInformation($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // $aQuotasInfo have an 'active' key, we don't use it ?
        if (!$aQuotasInfo || empty($aQuotasInfo)) {
            return $aMatchedQuotas;
        }
        // OK, we have some quota, then find if this $_SESSION have some set
        $aPostedFields = explode("|", Yii::app()->request->getPost('fieldnames', ''));
        // Needed for quota allowing update
        foreach ($aQuotasInfo as $aQuotaInfo) {
            if (count($aQuotaInfo['members']) === 0) {
                continue;
            }
            $iMatchedAnswers = 0;
            $bPostedField = false;
            // Array of field with quota array value
            $aQuotaFields = array();
            // Array of fieldnames with relevance value : EM fill $_SESSION with default value even is unrelevant (em_manager_helper line 6548)
            $aQuotaRelevantFieldnames = array();
            // To count number of hidden questions
            $aQuotaQid = array();
            foreach ($aQuotaInfo['members'] as $aQuotaMember) {
                $aQuotaFields[$aQuotaMember['fieldname']][] = $aQuotaMember['value'];
                $aQuotaRelevantFieldnames[$aQuotaMember['fieldname']] = isset($_SESSION['survey_' . $surveyid]['relevanceStatus'][$aQuotaMember['qid']]) && $_SESSION['survey_' . $surveyid]['relevanceStatus'][$aQuotaMember['qid']];
                $aQuotaQid[] = $aQuotaMember['qid'];
            }
            $aQuotaQid = array_unique($aQuotaQid);
            // For each field : test if actual responses is in quota (and is relevant)
            foreach ($aQuotaFields as $sFieldName => $aValues) {
                $bInQuota = isset($_SESSION['survey_' . $surveyid][$sFieldName]) && in_array($_SESSION['survey_' . $surveyid][$sFieldName], $aValues);
                if ($bInQuota && $aQuotaRelevantFieldnames[$sFieldName]) {
                    $iMatchedAnswers++;
                }
                if (in_array($sFieldName, $aPostedFields)) {
                    // Need only one posted value
                    $bPostedField = true;
                }
            }
            // Condition to count quota : Answers are the same in quota + an answer is submitted at this time (bPostedField) OR all questions is hidden (bAllHidden)
            $bAllHidden = QuestionAttribute::model()->countByAttributes(array('qid' => $aQuotaQid), 'attribute=:attribute', array(':attribute' => 'hidden')) == count($aQuotaQid);
            if ($iMatchedAnswers == count($aQuotaFields) && ($bPostedField || $bAllHidden)) {
                if ($aQuotaInfo['qlimit'] == 0) {
                    // Always add the quota if qlimit==0
                    $aMatchedQuotas[] = $aQuotaInfo;
                } else {
                    $iCompleted = getQuotaCompletedCount($surveyid, $aQuotaInfo['id']);
                    if (!is_null($iCompleted) && (int) $iCompleted >= (int) $aQuotaInfo['qlimit']) {
                        // This remove invalid quota and not completed
                        $aMatchedQuotas[] = $aQuotaInfo;
                    }
                }
            }
        }
    }
    if ($return) {
        return $aMatchedQuotas;
    }
    if (empty($aMatchedQuotas)) {
        return;
    }
    // Now we have all the information we need about the quotas and their status.
    // We need to construct the page and do all needed action
    $aSurveyInfo = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    $sClientToken = isset($_SESSION['survey_' . $surveyid]['token']) ? $_SESSION['survey_' . $surveyid]['token'] : "";
    // $redata for templatereplace
    $aDataReplacement = array('thissurvey' => $aSurveyInfo, 'clienttoken' => $sClientToken, 'token' => $sClientToken);
    // We take only the first matched quota, no need for each
    $aMatchedQuota = $aMatchedQuotas[0];
    // If a token is used then mark the token as completed, do it before event : this allow plugin to update token information
    $event = new PluginEvent('afterSurveyQuota');
    $event->set('surveyId', $surveyid);
    $event->set('responseId', $_SESSION['survey_' . $surveyid]['srid']);
    // We allways have a responseId
    $event->set('aMatchedQuotas', $aMatchedQuotas);
    // Give all the matched quota : the first is the active
    App()->getPluginManager()->dispatchEvent($event);
    $blocks = array();
    foreach ($event->getAllContent() as $blockData) {
        /* @var $blockData PluginEventContent */
        $blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()), $blockData->getContent());
    }
    // Allow plugin to update message, url, url description and action
    $sMessage = $event->get('message', $aMatchedQuota['quotals_message']);
    $sUrl = $event->get('url', $aMatchedQuota['quotals_url']);
    $sUrlDescription = $event->get('urldescrip', $aMatchedQuota['quotals_urldescrip']);
    $sAction = $event->get('action', $aMatchedQuota['action']);
    $sAutoloadUrl = $event->get('autoloadurl', $aMatchedQuota['autoload_url']);
    // Doing the action and show the page
    if ($sAction == "1" && $sClientToken) {
        submittokens(true);
    }
    // Construct the default message
    $sMessage = templatereplace($sMessage, array(), $aDataReplacement, 'QuotaMessage', $aSurveyInfo['anonymized'] != 'N', NULL, array(), true);
    $sUrl = passthruReplace($sUrl, $aSurveyInfo);
    $sUrl = templatereplace($sUrl, array(), $aDataReplacement, 'QuotaUrl', $aSurveyInfo['anonymized'] != 'N', NULL, array(), true);
    $sUrlDescription = templatereplace($sUrlDescription, array(), $aDataReplacement, 'QuotaUrldescription', $aSurveyInfo['anonymized'] != 'N', NULL, array(), true);
    // Construction of default message inside quotamessage class
    $sHtmlQuotaMessage = "<div class='quotamessage limesurveycore'>\n";
    $sHtmlQuotaMessage .= "\t" . $sMessage . "\n";
    $sHtmlQuotaUrl = $sUrl ? "<a href='" . $sUrl . "'>" . $sUrlDescription . "</a>" : "";
    // Add the navigator with Previous button if quota allow modification.
    if ($sAction == "2") {
        $sQuotaStep = isset($_SESSION['survey_' . $surveyid]['step']) ? $_SESSION['survey_' . $surveyid]['step'] : 0;
        // Surely not needed
        $sNavigator = CHtml::htmlButton(gT("Previous"), array('type' => 'submit', 'id' => "moveprevbtn", 'value' => $sQuotaStep, 'name' => 'move', 'accesskey' => 'p', 'class' => "submit button btn btn-default"));
        //$sNavigator .= " ".CHtml::htmlButton(gT("Submit"),array('type'=>'submit','id'=>"movesubmit",'value'=>"movesubmit",'name'=>"movesubmit",'accesskey'=>'l','class'=>"submit button"));
        $sHtmlQuotaMessage .= CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'class' => 'survey-form-container QuotaMessage'));
        $sHtmlQuotaMessage .= templatereplace(file_get_contents($sTemplateViewPath . "/navigator.pstpl"), array('NAVIGATOR' => $sNavigator, 'SAVE' => ''), $aDataReplacement);
        $sHtmlQuotaMessage .= CHtml::hiddenField('sid', $surveyid);
        $sHtmlQuotaMessage .= CHtml::hiddenField('token', $sClientToken);
        // Did we really need it ?
        $sHtmlQuotaMessage .= CHtml::endForm();
    }
    $sHtmlQuotaMessage .= "</div>\n";
    // Add the plugin message before default message
    $sHtmlQuotaMessage = implode("\n", $blocks) . "\n" . $sHtmlQuotaMessage;
    // Send page to user and end.
    sendCacheHeaders();
    if ($sAutoloadUrl == 1 && $sUrl != "") {
        if ($sAction == "1") {
            killSurveySession($surveyid);
        }
        header("Location: " . $sUrl);
    }
    doHeader();
    echo templatereplace(file_get_contents($sTemplateViewPath . "/startpage.pstpl"), array(), $aDataReplacement);
    echo templatereplace(file_get_contents($sTemplateViewPath . "/completed.pstpl"), array("COMPLETED" => $sHtmlQuotaMessage, "URL" => $sHtmlQuotaUrl), $aDataReplacement);
    echo templatereplace(file_get_contents($sTemplateViewPath . "/endpage.pstpl"), array(), $aDataReplacement);
    doFooter();
    if ($sAction == "1") {
        killSurveySession($surveyid);
    }
    Yii::app()->end();
}
Example #4
0
 function action()
 {
     global $surveyid;
     global $thissurvey, $thisstep;
     global $clienttoken, $tokensexist, $token;
     // only attempt to change session lifetime if using a DB backend
     // with file based sessions, it's up to the admin to configure maxlifetime
     if (isset(Yii::app()->session->connectionID)) {
         @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
     }
     $this->_loadRequiredHelpersAndLibraries();
     $param = $this->_getParameters(func_get_args(), $_POST);
     $surveyid = $param['sid'];
     Yii::app()->setConfig('surveyID', $surveyid);
     $thisstep = $param['thisstep'];
     $move = getMove();
     Yii::app()->setConfig('move', $move);
     $clienttoken = trim($param['token']);
     $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
     if (is_null($thissurvey) && !is_null($surveyid)) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     // unused vars in this method (used in methods using compacted method vars)
     @($loadname = $param['loadname']);
     @($loadpass = $param['loadpass']);
     $sitename = Yii::app()->getConfig('sitename');
     if (isset($param['newtest']) && $param['newtest'] == "Y") {
         killSurveySession($surveyid);
     }
     $surveyExists = $surveyid && Survey::model()->findByPk($surveyid);
     $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y";
     // collect all data in this method to pass on later
     $redata = compact(array_keys(get_defined_vars()));
     $this->_loadLimesurveyLang($surveyid);
     if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", array('token' => $clienttoken, 'lang' => App()->language, 'newtest' => 'Y'));
         $asMessage = array(gT('Token mismatch'), gT('The token you provided doesn\'t match the one in your session.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     if ($this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) {
         $aReloadUrlParam = array('lang' => App()->language, 'newtest' => 'Y');
         if ($clienttoken) {
             $aReloadUrlParam['token'] = $clienttoken;
         }
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", $aReloadUrlParam);
         $asMessage = array(gT('Previous session is set to be finished.'), gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     $previewmode = false;
     if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) {
         if (!$this->_canUserPreviewSurvey($surveyid)) {
             $asMessage = array(gT('Error'), gT("We are sorry but you don't have permissions to do this."));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         } else {
             if (intval($param['qid']) && $param['action'] == 'previewquestion') {
                 $previewmode = 'question';
             }
             if (intval($param['gid']) && $param['action'] == 'previewgroup') {
                 $previewmode = 'group';
             }
         }
     }
     Yii::app()->setConfig('previewmode', $previewmode);
     if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
         $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
         if ($bPreviewRight === false) {
             $asMessage = array(gT("Error"), gT("We are sorry but you don't have permissions to do this."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         }
     }
     // TODO can this be moved to the top?
     // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
     // can this be added in the first computation of $redata?
     if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
         $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
     }
     // recompute $redata since $saved_id used to be a global
     $redata = compact(array_keys(get_defined_vars()));
     if ($this->_didSessionTimeOut($surveyid)) {
         // @TODO is this still required ?
         $asMessage = array(gT("Error"), gT("We are sorry but your session has expired."), gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, null, $asMessage);
     }
     // Set the language of the survey, either from POST, GET parameter of session var
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     $sOldLang = isset($_SESSION['survey_' . $surveyid]['s_lang']) ? $_SESSION['survey_' . $surveyid]['s_lang'] : "";
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     if (!empty($param['lang'])) {
         $sDisplayLanguage = $param['lang'];
         // $param take lang from returnGlobal and returnGlobal sanitize langagecode
     } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $sDisplayLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
     } elseif (Survey::model()->findByPk($surveyid)) {
         $sDisplayLanguage = Survey::model()->findByPk($surveyid)->language;
     } else {
         $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
     }
     //CHECK FOR REQUIRED INFORMATION (sid)
     if ($surveyid && $surveyExists) {
         LimeExpressionManager::SetSurveyId($surveyid);
         // must be called early - it clears internal cache if a new survey is being used
         SetSurveyLanguage($surveyid, $sDisplayLanguage);
         if ($previewmode) {
             LimeExpressionManager::SetPreviewMode($previewmode);
         }
         if (App()->language != $sOldLang) {
             UpdateGroupList($surveyid, App()->language);
             // to refresh the language strings in the group list session variable
             UpdateFieldArray();
             // to refresh question titles and question text
         }
     } else {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     }
     // Get token
     if (!isset($token)) {
         $token = $clienttoken;
     }
     //GET BASIC INFORMATION ABOUT THIS SURVEY
     $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
     $event = new PluginEvent('beforeSurveyPage');
     $event->set('surveyId', $surveyid);
     App()->getPluginManager()->dispatchEvent($event);
     if (!is_null($event->get('template'))) {
         $thissurvey['templatedir'] = $event->get('template');
     }
     //SEE IF SURVEY USES TOKENS
     if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
         $tokensexist = 1;
     } else {
         $tokensexist = 0;
         unset($_POST['token']);
         unset($param['token']);
         unset($token);
         unset($clienttoken);
     }
     //SET THE TEMPLATE DIRECTORY
     global $oTemplate;
     $thistpl = $oTemplate->viewPath;
     $timeadjust = Yii::app()->getConfig("timeadjust");
     //MAKE SURE SURVEY HASN'T EXPIRED
     if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is no longer available."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //MAKE SURE SURVEY IS ALREADY VALID
     if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is not yet started."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //CHECK FOR PREVIOUSLY COMPLETED COOKIE
     //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
     $sCookieName = "LS_" . $surveyid . "_STATUS";
     if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("You have already completed this survey."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //LOAD SAVED SURVEY
     if (Yii::app()->request->getParam('loadall') == "reload") {
         $errormsg = "";
         $sLoadName = Yii::app()->request->getParam('loadname');
         $sLoadPass = Yii::app()->request->getParam('loadpass');
         if (isset($sLoadName) && !$sLoadName) {
             $errormsg .= gT("You did not provide a name") . "<br />\n";
         }
         if (isset($sLoadPass) && !$sLoadPass) {
             $errormsg .= gT("You did not provide a password") . "<br />\n";
         }
         // if security question answer is incorrect
         // Not called if scid is set in GET params (when using email save/reload reminder URL)
         if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha']) && is_null(Yii::app()->request->getQuery('scid'))) {
             $sLoadSecurity = Yii::app()->request->getPost('loadsecurity');
             if (empty($sLoadSecurity)) {
                 $errormsg .= gT("You did not answer to the security question.") . "<br />\n";
             } elseif (!isset($_SESSION['survey_' . $surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
                 $errormsg .= gT("The answer to the security question is incorrect.") . "<br />\n";
             }
         }
         if ($errormsg == "") {
             LimeExpressionManager::SetDirtyFlag();
             buildsurveysession($surveyid);
             if (loadanswers()) {
                 Yii::app()->setConfig('move', 'reload');
                 $move = "reload";
                 // veyRunTimeHelper use $move in $arg
             } else {
                 $errormsg .= gT("There is no matching saved survey");
             }
         }
         if ($errormsg) {
             Yii::app()->setConfig('move', "loadall");
             // Show loading form
         }
     }
     //Allow loading of saved survey
     if (Yii::app()->getConfig('move') == "loadall") {
         $redata = compact(array_keys(get_defined_vars()));
         Yii::import("application.libraries.Load_answers");
         $tmp = new Load_answers();
         $tmp->run($redata);
     }
     //Check if TOKEN is used for EVERY PAGE
     //This function fixes a bug where users able to submit two surveys/votes
     //by checking that the token has not been used at each page displayed.
     // bypass only this check at first page (Step=0) because
     // this check is done in buildsurveysession and error message
     // could be more interresting there (takes into accound captcha if used)
     if ($tokensexist == 1 && isset($token) && $token != "" && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance) && !$previewmode) {
             //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
             $asMessage = array(null, gT("This is a controlled survey. You need a valid token to participate."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     if ($tokensexist == 1 && isset($token) && $token != "" && tableExists("{{tokens_" . $surveyid . "}}") && !$previewmode) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance)) {
             $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
             if ($oToken) {
                 $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
                 if ($oToken->completed != 'N' && !empty($oToken->completed)) {
                     $sError = gT("This invitation has already been used.");
                 } elseif (strtotime($now) < strtotime($oToken->validfrom)) {
                     $sError = gT("This invitation is not valid yet.");
                 } elseif (strtotime($now) > strtotime($oToken->validuntil)) {
                     $sError = gT("This invitation is not valid anymore.");
                 } else {
                     $sError = gT("This is a controlled survey. You need a valid token to participate.");
                 }
             } else {
                 $sError = gT("This is a controlled survey. You need a valid token to participate.");
             }
             $asMessage = array($sError, gT("We are sorry but you are not allowed to enter this survey."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     //Clear session and remove the incomplete response if requested.
     if (isset($move) && $move == "clearall") {
         // delete the response but only if not already completed
         $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
         if (isset($_SESSION['survey_' . $surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
             // delete the response but only if not already completed
             $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
             if ($result->count() > 0) {
                 // Using count() here *should* be okay for MSSQL because it is a delete statement
                 // find out if there are any fuqt questions - checked
                 $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                 foreach ($fieldmap as $field) {
                     if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                         if (!isset($qid)) {
                             $qid = array();
                         }
                         $qid[] = $field['fieldname'];
                     }
                 }
                 // if yes, extract the response json to those questions
                 if (isset($qid)) {
                     $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                     $result = dbExecuteAssoc($query);
                     foreach ($result->readAll() as $row) {
                         foreach ($qid as $question) {
                             $json = $row[$question];
                             if ($json == "" || $json == NULL) {
                                 continue;
                             }
                             // decode them
                             $phparray = json_decode($json);
                             foreach ($phparray as $metadata) {
                                 $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                 // delete those files
                                 unlink($target . $metadata->filename);
                             }
                         }
                     }
                 }
                 // done deleting uploaded files
             }
             // also delete a record from saved_control when there is one
             dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
         }
         killSurveySession($surveyid);
         sendCacheHeaders();
         doHeader();
         $redata = compact(array_keys(get_defined_vars()));
         $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
         echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
         //Present the clear all page using clearall.pstpl template
         $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
         $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
         doFooter();
         exit;
     }
     //Check to see if a refering URL has been captured.
     if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
         $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
         // do not overwrite refurl
     }
     // Let's do this only if
     //  - a saved answer record hasn't been loaded through the saved feature
     //  - the survey is not anonymous
     //  - the survey is active
     //  - a token information has been provided
     //  - the survey is setup to allow token-response-persistence
     if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
         // load previous answers if any (dataentry with nosubmit)
         $oResponses = Response::model($surveyid)->findAllByAttributes(array('token' => $token), array('order' => 'id DESC'));
         if (!empty($oResponses)) {
             /**
              * We fire the response selection event when at least 1 response was found.
              * If there is just 1 response the plugin still has to option to choose
              * NOT to use it.
              */
             $event = new PluginEvent('beforeLoadResponse');
             $event->set('responses', $oResponses);
             $event->set('surveyId', $surveyid);
             App()->pluginManager->dispatchEvent($event);
             $oResponse = $event->get('response');
             // If $oResponse is false we act as if no response was found.
             // This allows a plugin to deny continuing a response.
             if ($oResponse !== false) {
                 // If plugin does not set a response we use the first one found, (this replicates pre-plugin behavior)
                 if (!isset($oResponse) && (!isset($oResponses[0]->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y') && $thissurvey['tokenanswerspersistence'] == 'Y') {
                     $oResponse = $oResponses[0];
                 }
                 if (isset($oResponse)) {
                     $_SESSION['survey_' . $surveyid]['srid'] = $oResponse->id;
                     if (!empty($oResponse->lastpage)) {
                         $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                         // If the response was completed and user is allowed to edit after completion start at the beginning and not at the last page - just makes more sense
                         if (!($oResponse->submitdate && $thissurvey['alloweditaftercompletion'] == 'Y')) {
                             $_SESSION['survey_' . $surveyid]['step'] = $oResponse->lastpage;
                         }
                     }
                     buildsurveysession($surveyid);
                     if (!empty($oResponse->submitdate)) {
                         $_SESSION['survey_' . $surveyid]['maxstep'] = $_SESSION['survey_' . $surveyid]['totalsteps'];
                     }
                     loadanswers();
                 }
             }
         }
     }
     // Preview action : Preview right already tested before
     if ($previewmode) {
         // Unset all SESSION: be sure to have the last version
         unset($_SESSION['fieldmap-' . $surveyid . App()->language]);
         // Needed by createFieldMap: else fieldmap can be outdated
         unset($_SESSION['survey_' . $surveyid]);
         if ($param['action'] == 'previewgroup') {
             $thissurvey['format'] = 'G';
         } elseif ($param['action'] == 'previewquestion') {
             $thissurvey['format'] = 'S';
         }
         buildsurveysession($surveyid, true);
     }
     sendCacheHeaders();
     //Send local variables to the appropriate survey type
     unset($redata);
     $redata = compact(array_keys(get_defined_vars()));
     Yii::import('application.helpers.SurveyRuntimeHelper');
     $tmp = new SurveyRuntimeHelper();
     $tmp->run($surveyid, $redata);
     if (isset($_POST['saveall']) || isset($flashmessage)) {
         echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . gT("Your responses were successfully saved.", "js") . "');}) </script>";
     }
 }
Example #5
0
 /**
  * Supply an array with the responseIds and all files will be added to the zip
  * and it will be be spit out on success
  *
  * @param array $responseIds
  * @param string $zipfilename
  * @param string $language
  * @return ZipArchive
  */
 private function _zipFiles($iSurveyID, $responseIds, $zipfilename)
 {
     /**
      * @todo Move this to model.
      */
     Yii::app()->loadLibrary('admin/pclzip');
     $tmpdir = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . "surveys" . DIRECTORY_SEPARATOR . $iSurveyID . DIRECTORY_SEPARATOR . "files" . DIRECTORY_SEPARATOR;
     $filelist = array();
     $responses = Response::model($iSurveyID)->findAllByPk($responseIds);
     $filecount = 0;
     foreach ($responses as $response) {
         foreach ($response->getFiles() as $file) {
             $filecount++;
             /*
              * Now add the file to the archive, prefix files with responseid_index to keep them
              * unique. This way we can have 234_1_image1.gif, 234_2_image1.gif as it could be
              * files from a different source with the same name.
              */
             if (file_exists($tmpdir . basename($file['filename']))) {
                 $filelist[] = array(PCLZIP_ATT_FILE_NAME => $tmpdir . basename($file['filename']), PCLZIP_ATT_FILE_NEW_FULL_NAME => sprintf("%05s_%02s_%s", $response->id, $filecount, rawurldecode($file['name'])));
             }
         }
     }
     if (count($filelist) > 0) {
         $zip = new PclZip($tmpdir . $zipfilename);
         if ($zip->create($filelist) === 0) {
             //Oops something has gone wrong!
         }
         if (file_exists($tmpdir . '/' . $zipfilename)) {
             @ob_clean();
             header('Content-Description: File Transfer');
             header('Content-Type: application/octet-stream');
             header('Content-Disposition: attachment; filename=' . basename($zipfilename));
             header('Content-Transfer-Encoding: binary');
             header('Expires: 0');
             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
             header('Pragma: public');
             header('Content-Length: ' . filesize($tmpdir . "/" . $zipfilename));
             readfile($tmpdir . '/' . $zipfilename);
             unlink($tmpdir . '/' . $zipfilename);
             exit;
         }
     }
     // No files : redirect to browse with a alert
     Yii::app()->setFlashMessage(gT("Sorry, there are no files for this response."), 'error');
     $this->getController()->redirect(array("admin/responses", "sa" => "browse", "surveyid" => $iSurveyID));
 }
Example #6
0
 public function getButtons()
 {
     $sViewUrl = App()->createUrl("/admin/responses/sa/view/surveyid/" . self::$sid . "/id/" . $this->id);
     $sEditUrl = App()->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/" . self::$sid . "/id/" . $this->id);
     $sDownloadUrl = App()->createUrl("admin/responses", array("sa" => "actionDownloadfiles", "surveyid" => self::$sid, "sResponseId" => $this->id));
     $sDeleteUrl = App()->createUrl("admin/responses", array("sa" => "actionDelete", "surveyid" => self::$sid));
     //$sDeleteUrl   = "#";
     $button = "";
     // View detail icon
     $button .= '<a class="btn btn-default btn-xs" href="' . $sViewUrl . '" target="_blank" role="button" data-toggle="tooltip" title="' . gT("View response details") . '"><span class="glyphicon glyphicon-list-alt" ></span></a>';
     // Edit icon
     if (Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'update')) {
         $button .= '<a class="btn btn-default btn-xs" href="' . $sEditUrl . '" target="_blank" role="button" data-toggle="tooltip" title="' . gT("Edit this response") . '"><span class="glyphicon glyphicon-pencil text-success" ></span></a>';
     }
     // Download icon
     if (hasFileUploadQuestion(self::$sid)) {
         if (Response::model(self::$sid)->findByPk($this->id)->getFiles()) {
             $button .= '<a class="btn btn-default btn-xs" href="' . $sDownloadUrl . '" target="_blank" role="button" data-toggle="tooltip" title="' . gT("Download all files in this response as a zip file") . '"><span class="glyphicon glyphicon-download-alt downloadfile text-success" ></span></a>';
         }
     }
     // Delete icon
     if (Permission::model()->hasSurveyPermission(self::$sid, 'responses', 'delete')) {
         $aPostDatas = json_encode(array('sResponseId' => $this->id));
         //$button .= '<a class="deleteresponse btn btn-default btn-xs" href="'.$sDeleteUrl.'" role="button" data-toggle="modal" data-ajax="true" data-post="'.$aPostDatas.'" data-target="#confirmation-modal" data-tooltip="true" title="'. sprintf(gT('Delete response %s'),$this->id).'"><span class="glyphicon glyphicon-trash text-danger" ></span></a>';
         $button .= "<a class='deleteresponse btn btn-default btn-xs' data-ajax-url='" . $sDeleteUrl . "' data-gridid='responses-grid' role='button' data-toggle='modal' data-post='" . $aPostDatas . "' data-target='#confirmation-modal' data-tooltip='true' title='" . sprintf(gT('Delete response %s'), $this->id) . "'><span class='glyphicon glyphicon-trash text-danger' ></span></a>";
     }
     return $button;
 }
Example #7
0
<?php
/**
 * Created by PhpStorm.
 * User: Ivanna
 * Date: 24.04.2015
 * Time: 23:47
 */
$teacherRat=Response::model()->find('who=:whoID and about=:aboutID', array(':whoID'=>$data['who'],':aboutID'=>$teacher->user_id));
$user=StudentReg::model()->findByPk($data['who']);
if($teacherRat){
    $rat= $teacherRat->rate;
} else{
    $rat= Null;
}
?>
<div class="TeacherProfiletitles">
    <?php echo $user->firstName." ".$user->secondName; ?>
</div>
<div class="sm">
    <?php
    $num = $data['who_ip'];
    echo $data['date']." IP:".Teacher::getHideIp($data['who_ip']);
?>
</div>

<div class="txtMsg"><?php echo $data['text'];?></div>
<div class="border">
    <div class="TeacherProfiletitles">
        <?php
        if ($rat!==Null){
        echo Yii::t('teacher', '0186');
 public function actionReviewAdd($response_id)
 {
     if (Yii::app()->user->isGuest) {
         throw new CHttpException(403);
     }
     $Response = Response::model()->findByPK($response_id);
     if (is_null($Response)) {
         throw new CHttpException(403);
     }
     $profile = Yii::app()->user->getProfile();
     $Company = $profile->company;
     if ($Company->isBlocked()) {
         $this->render('reviewaddblock', ['Response' => $Response, 'CompanyPartner' => null]);
         return;
     }
     $CompanyPartnerId = null;
     if ($Company->id == $Response->from_company_id) {
         $CompanyPartnerId = $Response->to_company_id;
     } else {
         if ($Company->id == $Response->to_company_id) {
             $CompanyPartnerId = $Response->from_company_id;
         } else {
             // компания не принадлежит к этой сделке
             throw new CHttpException(403);
         }
     }
     $CompanyPartner = Company::model()->findByPk($CompanyPartnerId);
     if ($CompanyPartner->isBlocked()) {
         $this->render('reviewaddblock', ['Response' => $Response, 'CompanyPartner' => $CompanyPartner]);
         return;
     }
     if (!$Response->isCompaniesReadyForReviews()) {
         Yii::log("actionReviewAdd companies NOT ready for review", "info");
         throw new CHttpException(403);
     }
     $Review = Review::model()->findByAttributes(['response_id' => $response_id, 'from_company_id' => $Company->id]);
     if (is_null($Review)) {
         $Review = new Review();
     }
     //$Response = Response::model()->findByPk($response_id);
     if (isset($_POST['Review'])) {
         $Review->setAttributes($_POST['Review'], false);
         $Review->from_company_id = $Company->id;
         if ($Response->to_company->id == $Company->id) {
             $CompanyTo = $Response->from_company;
         } else {
             $CompanyTo = $Response->to_company;
         }
         $Review->to_company_id = $CompanyTo->id;
         $Review->response_id = $Response->response_id;
         if ($Review->validate()) {
             $Review->save();
             if (isset($_POST['photos'])) {
                 $Review->setPhoto($_POST['photos']);
             }
             $Review->setscenario('valid_photo');
             if ($Review->validate()) {
                 //$this->redirect('/cabinet/deal/'.$Response->response_id);
                 $this->redirect('/response/' . $Response->response_id);
             }
         }
     }
     $mainAssets = Yii::app()->getTheme()->getAssetsUrl();
     Yii::app()->getClientScript()->registerCssFile($mainAssets . '/css/review.css');
     $this->render('reviewadd', ['Review' => $Review, 'Response' => $Response]);
 }
 public function notifyInterestedPersonsViaLongPool($type, $model, $model_id, $user_id, $message_id, $arrMore = null)
 {
     if ('Response' == $model) {
         if (isset(Yii::app()->params['comet_messages_url_publisher']) && strlen(Yii::app()->params['comet_messages_url_publisher']) > 0) {
             if ('file' == $type) {
                 if (is_array($arrMore) && isset($arrMore['photo_id']) && $arrMore['photo_id']) {
                     // nothing to do here
                 } else {
                     return;
                 }
             }
             // response to/from company , this thread all user_id
             // user_id message.model .model_id
             // response .from_company_id .to_company_id .user_id
             // site_user_user .company_id
             $Response = Response::model()->findByPk($model_id);
             // вспомогательный массив для добавления пользователей на оповещение
             $arrPersons = ['from' => ['id' => $Response->from_company_id, 'count' => 0], 'to' => ['id' => $Response->to_company_id, 'count' => 0]];
             $arrUsers = [];
             $arrUsers[$Response->user_id] = Yii::app()->userManager->tokenStorage->getCometMessagesToken($Response->user_id);
             $messages = Message::model()->findAllByAttributes(['model' => 'Response', 'model_id' => $model_id]);
             foreach ($messages as $msg) {
                 if (!isset($arrUsers[$msg->user_id])) {
                     $arrUsers[$msg->user_id] = Yii::app()->userManager->tokenStorage->getCometMessagesToken($msg->user_id);
                     $user_company_id = $msg->user->company_id;
                     if ($user_company_id == $arrPersons['from']['id']) {
                         $arrPersons['from']['count']++;
                     } else {
                         $arrPersons['to']['count']++;
                     }
                 }
             }
             // проверить что есть пользователи от обоих компаний, если нет, то надо добавить
             foreach ($arrPersons as $kp => $kv) {
                 if (0 == $kv['count']) {
                     $Users = User::model()->findAllByAttributes(['company_id' => $kv['id']]);
                     foreach ($Users as $userCheck) {
                         if (!isset($arrUsers[$userCheck->id])) {
                             $arrUsers[$userCheck->id] = Yii::app()->userManager->tokenStorage->getCometMessagesToken($userCheck->id);
                         }
                     }
                 }
             }
             if ('message' == $type || 'file' == $type) {
                 // убрать того, кто отправил
                 if (isset($arrUsers[$user_id])) {
                     unset($arrUsers[$user_id]);
                 }
             }
             Yii::log("notifyInterestedPersonsViaLongPool arrUsers=[" . print_r($arrUsers, true) . "]", "info");
             $arrData = [];
             if ('message' == $type) {
                 // DB request to get create field data, now is 'NOW()'
                 $curMessage = Message::model()->findByPk($message_id);
                 $User = $curMessage->user;
                 $arrData['last_name'] = $User->last_name;
                 $arrData['first_name'] = $User->first_name;
                 $arrData['create'] = $curMessage->create;
                 $arrData['message'] = $curMessage->message;
             }
             $arrData['type'] = $type;
             $arrData['message_id'] = $message_id;
             $arrData['model'] = $model;
             $arrData['model_id'] = $model_id;
             $arrData['user_id'] = $user_id;
             if ('file' == $type) {
                 $arrData = array_merge($arrData, $arrMore);
             }
             static::sendMessageToLongPool($arrUsers, $arrData);
         }
     }
 }
Example #10
0
 public function getAverageRateMot ($id)
 {
     $countMot = Response::model()->count("motivation>0 and about=$id");
     $sum = Yii::app()->db->createCommand()
         ->select('sum(motivation)')
         ->from('response')
         ->where('about=:id', array(':id'=>$id))
         ->queryRow();
     return round($sum['sum(motivation)']/$countMot);
 }
Example #11
0
 public function actionResponsedelete($type, $id, $model = null)
 {
     if (\Yii::app()->user->isGuest) {
         throw new CHttpException(403);
     }
     switch ($type) {
         case "element":
             Yii::log("actionResponsedelete element", "info");
             $Response = \Response::model()->findByPk($id);
             if (is_null($Response)) {
                 throw new CHttpException(403);
             }
             if (!\Yii::app()->user->checkAccess('admin')) {
                 if (\Yii::app()->user->id != $Response->user_id) {
                     throw new CHttpException(403);
                 }
             }
             \Response::model()->deleteByPk($id);
             break;
         case "all":
             Yii::log("actionResponsedelete all", "info");
             if (is_null($model)) {
                 throw new CHttpException(403);
             }
             $user_id = \Yii::app()->user->id;
             $arrResponse = \Response::model()->findAllByAttributes(['external_id' => $id, 'model' => $model]);
             $isAdmin = \Yii::app()->user->checkAccess('admin');
             foreach ($arrResponse as $Response) {
                 if (!$isAdmin) {
                     if ($user_id != $Response->user_id) {
                         throw new CHttpException(403);
                     }
                 }
                 \Response::model()->deleteByPk($Response->response_id);
             }
             break;
         default:
             throw new CHttpException(403);
     }
     $this->redirect('/response');
 }
Example #12
0
<?php
/**
 * Created by PhpStorm.
 * User: Ivanna
 * Date: 12.05.2015
 * Time: 16:56
 */
?>

<?php $teacherRat=Response::model()->find('who=:whoID and about=:aboutID', array(':whoID'=>Yii::app()->user->getId(),':aboutID'=>$model->user_id));?>
<div class="TeacherProfileblock2">
    <?php $this->renderPartial('_teacherRate', array('model' => $model)); ?>

    <?php
    $this->widget('zii.widgets.CListView', array(
        'dataProvider'=>$dataProvider,
        'viewData' => array('teacher'=>$model),
        'itemView'=>'_responseBlock',
        'template'=>'{items}{pager}',
        'emptyText'=>Yii::t('profile', '0195'),
        'pager' => array(
            'firstPageLabel'=>'<<',
            'lastPageLabel'=>'>>',
            'prevPageLabel'=>'<',
            'nextPageLabel'=>'>',
            'header'=>'',
        ),
    ));
    ?>

Example #13
0
 public static function isResponseAlreadyExists($model, $external_id, $myCompanyId, $modelCompanyId)
 {
     $ret = false;
     $criteria = new CDbCriteria();
     $criteria->addColumnCondition(['model' => $model, 'external_id' => $external_id, 'from_company_id' => $myCompanyId, 'to_company_id' => $modelCompanyId]);
     $countAlready = Response::model()->count($criteria);
     if ($countAlready) {
         $ret = true;
     }
     return $ret;
 }
Example #14
0
echo Yii::t('default', 'Прикрепить файл');
?>
</a>
    </section>
    <section class="col-sm-9">
    </section>
</div>
<div class="row">
<?php 
if ('Response' == $model) {
    ?>
    
    <section class="col-sm-4">
        <br />
<?php 
    $this->widget('application.components.btnCreateReview.BtnCreateReviewWidget', ['Response' => Response::model()->findByPk($model_id)]);
    ?>
    </section>
    <section class="col-sm-3">
        <br />
<?php 
    $this->widget('application.components.gpsView.GPSViewWidget', ['response_id' => $model_id]);
    ?>
    </section>
    <section class="col-sm-2">
    </section>
<?php 
} else {
    ?>
        
    <section class="col-sm-9">
Example #15
0
    public function actionResponse($id)
    {
        $response = new Response();
        $teacher = Teacher::model()->findByPk($id);
        $teacherRat=Response::model()->find('who=:whoID and about=:aboutID', array(':whoID'=>Yii::app()->user->getId(),':aboutID'=>$teacher->user_id));

        if ($_POST['sendResponse']) {
            if (!empty($_POST['response'])) {
                $response->who = Yii::app()->user->id;
                $response->about = $teacher->user_id;
                $response->date = date("Y-m-d H:i:s");
                $response->text = $response->bbcode_to_html($_POST['response']);
                if($teacherRat && $teacherRat->knowledge==$_POST['material'] && $teacherRat->behavior==$_POST['behavior'] && $response->motivation==$_POST['motiv']){
                    $response->knowledge = Null;
                    $response->behavior = Null;
                    $response->motivation = Null;
                    $response->rate = Null;
                } if($teacherRat && ($teacherRat->knowledge!==$_POST['material'] || $teacherRat->behavior!==$_POST['behavior'] || $response->motivation!==$_POST['motiv'])){
                    $teacherRat->knowledge = $_POST['material'];
                    $teacherRat->behavior = $_POST['behavior'];
                    $teacherRat->motivation = $_POST['motiv'];
                    $teacherRat->rate = round(($_POST['material'] + $_POST['behavior'] + $_POST['motiv']) / 3);
                    $teacherRat->save();
                }else{
                    $response->knowledge = $_POST['material'];
                    $response->behavior = $_POST['behavior'];
                    $response->motivation = $_POST['motiv'];
                    $response->rate = round(($_POST['material'] + $_POST['behavior'] + $_POST['motiv']) / 3);
                }
                $response->who_ip = $_SERVER["REMOTE_ADDR"];
                if($_POST['material']!=='' && $_POST['behavior']!=='' && $_POST['motiv']!==''){
                    $response->save();
                    $teacher->updateByPk($id, array('rate_knowledge' => $teacher->getAverageRateKnwl($teacher->user_id)));
                    $teacher->updateByPk($id, array('rate_efficiency' => $teacher->getAverageRateBeh($teacher->user_id)));
                    $teacher->updateByPk($id, array('rate_relations' => $teacher->getAverageRateMot($teacher->user_id)));
                    $teacher->updateByPk($id, array('rating' => $teacher->getAverageRate($teacher->user_id)));
                    Yii::app()->user->setFlash('messageResponse', Yii::t('response', '0386'));
                } else {
                    Yii::app()->user->setFlash('responseError', Yii::t('response', '0385'));
                }
            }
            header('Location: ' . $_SERVER['HTTP_REFERER']);
        }
    }
<?php

$Response = \Response::model()->findByPk($data['response_id']);
$numUnreaded = \Yii::app()->db->createCommand()->select("SUM(IF( msr.flag IS NULL ,1,0)) as count_unreaded")->from('{{message}} t')->leftjoin('{{message_readed}} msr', 'msr.message_id = t.message_id')->where("t.user_id != :user_id AND t.model = 'Response' AND t.model_id = :model_id", ['model_id' => $data['response_id'], 'user_id' => Yii::app()->user->id])->group('t.model_id')->queryScalar();
if (false === $numUnreaded) {
    $numUnreaded = 0;
}
$arrTrClass = ['element_message'];
if ($numUnreaded) {
    $arrTrClass[] = 'unread_messages';
}
$arrUnreadBlock = ['num_unread_block'];
if (!$numUnreaded) {
    $arrUnreadBlock[] = 'unread_block_hide';
}
?>
<tr class="<?php 
echo implode(' ', $arrTrClass);
?>
" onClick="window.location = '/response/<?php 
echo $data['response_id'];
?>
'" data-response-id="<?php 
echo $data['response_id'];
?>
">
    <td><?php 
echo $data['response_id'];
?>
&nbsp;<?php 
echo \Response::getHumanNameByResponseItem($Response->model, $Response->external_id);
 public function getResponses($surveyId, $attributes = array(), $condition = '', $params = array())
 {
     return Response::model($surveyId)->findAllByAttributes($attributes, $condition, $params);
 }
Example #18
0
                        if( "success" == data.status ) {
                            document.location.href = data.data;
                        } else {
                            alert("error create response [" + data.data + "]");
                        }
                    }', 'error' => 'js:function (data) {
                        console.log("ajaxButton error",data);
                        }', 'data' => [Yii::app()->request->csrfTokenName => Yii::app()->request->csrfToken, 'model' => $model, 'external_id' => $external_id]], 'label' => Yii::t('default', 'Заказать'), 'encodeLabel' => false, 'size' => 'large', 'context' => 'default', 'htmlOptions' => ['class' => 'pull-right offer']]);
    }
    ?>

<?php 
} else {
    ?>
    <?php 
    $response = Response::model()->find('model = :model AND external_id = :external_id AND from_company_id = :from_company_id AND to_company_id = :to_company_id', [':model' => $model, ':external_id' => $external_id, ':from_company_id' => $myCompanyId, ':to_company_id' => $modelCompanyId]);
    ?>
    <?php 
    if ($response) {
        ?>
        <a href="/response/<?php 
        echo $response->response_id;
        ?>
" class="pull-right offer btn btn-default btn-lg"><?php 
        echo Yii::t('default', 'Заказать');
        ?>
</a>
    <?php 
    }
}
?>
Example #19
0
 public function getResponceCount()
 {
     $criteria = new CDbCriteria();
     $criteria->addCondition('confirmation_date IS NULL');
     //$criteria->addCondition("( from_company_id = :company_id OR to_company_id = :company_id )");
     $criteria->addCondition("( to_company_id = :company_id )");
     $criteria->params["company_id"] = Yii::app()->user->getProfile()->company_id;
     return Response::model()->count($criteria);
     // Код странный, response_visit нигде в проекте не обрабатывается.
     //        if(empty($this->response_visit)) {
     //            return 0;
     //        } else {
     //            $criteria = new CDbCriteria;
     //            $criteria->addCondition(':response_visit < t.create');
     //            $criteria->params = [':response_visit' => $this->response_visit];
     //            return  Response::model()->count($criteria);
     //        }
 }
Example #20
0
$arrMsg = $data->message(['order' => 'message.create DESC', 'limit' => 1]);
if (count($arrMsg)) {
    echo $arrMsg[0]->MessageHuman;
} else {
    echo Yii::t('default', 'Сообщений нет');
}
?>
    </td>
    <td>
        <?php 
if ($data->to_company_id == $company_id) {
    $criteria = new CDbCriteria();
    $criteria->addCondition('model = :model');
    $criteria->addCondition('external_id = :external_id');
    $criteria->params = ['model' => $data->model, 'external_id' => $data->external_id];
    echo Response::model()->count($criteria);
}
?>
    </td>
    <td>
        <?php 
if ($data->from_company_id == $company_id) {
    ?>
        <a href="/responsedelete/element/<?php 
    echo $data->response_id;
    ?>
" class="btn btn-default"><?php 
    echo Yii::t('default', 'Удалить');
    ?>
</a>
        <?php