getController()->lang; $thissurvey = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'read') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'export') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update') ) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } Yii::app()->loadHelper("surveytranslator"); $aData['surveyprivate'] = $thissurvey['anonymized']; // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } else { //Check that the tokens table has the required fields /** * @todo is this still needed? What versions of token tables require this?? */ TokenDynamic::model($iSurveyId)->checkColumns(); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['queries'] = Token::model($iSurveyId)->summary(); $this->_renderWrappedTemplate('token', array('tokenbar', 'tokensummary'), $aData); } } /** * tokens::bounceprocessing() * * @return void */ function bounceprocessing($iSurveyId) { $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { $clang->eT("No token table."); return; } $thissurvey = getSurveyInfo($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { $clang->eT("We are sorry but you don't have permissions to do this."); return; } if ($thissurvey['bounceprocessing'] != 'N' || ($thissurvey['bounceprocessing'] == 'G' && getGlobalSetting('bounceaccounttype') != 'off')) { if (!function_exists('imap_open')) { $clang->eT("The imap PHP library is not installed. Please contact your system administrator."); return; } $bouncetotal = 0; $checktotal = 0; if ($thissurvey['bounceprocessing'] == 'G') { $accounttype=strtoupper(getGlobalSetting('bounceaccounttype')); $hostname = getGlobalSetting('bounceaccounthost'); $username = getGlobalSetting('bounceaccountuser'); $pass = getGlobalSetting('bounceaccountpass'); $hostencryption=strtoupper(getGlobalSetting('bounceencryption')); } else { $accounttype=strtoupper($thissurvey['bounceaccounttype']); $hostname = $thissurvey['bounceaccounthost']; $username = $thissurvey['bounceaccountuser']; $pass = $thissurvey['bounceaccountpass']; $hostencryption=strtoupper($thissurvey['bounceaccountencryption']); } @list($hostname, $port) = split(':', $hostname); if (empty($port)) { if ($accounttype == "IMAP") { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":143"; break; case "SSL": $hostname = $hostname . ":993"; break; case "TLS": $hostname = $hostname . ":993"; break; } } else { switch ($hostencryption) { case "OFF": $hostname = $hostname . ":110"; break; case "SSL": $hostname = $hostname . ":995"; break; case "TLS": $hostname = $hostname . ":995"; break; } } } else { $hostname = $hostname.":".$port; } $flags = ""; switch ($accounttype) { case "IMAP": $flags.="/imap"; break; case "POP": $flags.="/pop3"; break; } switch ($hostencryption) // novalidate-cert to have personal CA , maybe option. { case "OFF": $flags.="/notls"; // Really Off break; case "SSL": $flags.="/ssl/novalidate-cert"; break; case "TLS": $flags.="/tls/novalidate-cert"; break; } if ($mbox = @imap_open('{' . $hostname . $flags . '}INBOX', $username, $pass)) { imap_errors(); $count = imap_num_msg($mbox); if ($count>0) { $lasthinfo = imap_headerinfo($mbox, $count); $datelcu = strtotime($lasthinfo->date); $datelastbounce = $datelcu; $lastbounce = $thissurvey['bouncetime']; while ($datelcu > $lastbounce) { @$header = explode("\r\n", imap_body($mbox, $count, FT_PEEK)); // Don't mark messages as read foreach ($header as $item) { if (preg_match('/^X-surveyid/', $item)) { $iSurveyIdBounce = explode(": ", $item); } if (preg_match('/^X-tokenid/', $item)) { $tokenBounce = explode(": ", $item); if ($iSurveyId == $iSurveyIdBounce[1]) { $aData = array( 'emailstatus' => 'bounced' ); $condn = array('token' => $tokenBounce[1]); $record = Token::model($iSurveyId)->findByAttributes($condn); if ($record->emailstatus != 'bounced') { $record->emailstatus = 'bounced'; $record->save(); $bouncetotal++; } $readbounce = imap_body($mbox, $count); // Put read if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) // TODO Y or just true, and a imap_delete { $deletebounce = imap_delete($mbox, $count); // Put delete } } } } $count--; @$lasthinfo = imap_headerinfo($mbox, $count); @$datelc = $lasthinfo->date; $datelcu = strtotime($datelc); $checktotal++; } } @imap_close($mbox); $condn = array('sid' => $iSurveyId); $survey = Survey::model()->findByAttributes($condn); $survey->bouncetime = $datelastbounce; $survey->save(); if ($bouncetotal > 0) { printf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal, $bouncetotal); } else { printf($clang->gT("%s messages were scanned, none were marked as bounce by the system."), $checktotal); } } else { $clang->eT("Please check your settings"); } } else { $clang->eT("Bounce processing is deactivated either application-wide or for this survey in particular."); return; } exit; // if bounceprocessing : javascript : no more todo } /** * Browse Tokens */ function browse($iSurveyId, $limit = 50, $start = 0, $order = false, $searchstring = false) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); /* Check permissions */ if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'read')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/tokens/sa/index/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } /* build JS variable to hide buttons forbidden for the current user */ $aData['showDelButton'] = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'delete')?'true':'false'; $aData['showInviteButton'] = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')?'true':'false'; $aData['showBounceButton'] = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')?'true':'false'; $aData['showRemindButton'] = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')?'true':'false'; // Javascript App()->getClientScript()->registerPackage('jqgrid'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "tokens.js"); // CSS App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "displayParticipants.css"); App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "jquery-ui/jquery-timepicker.css"); Yii::app()->loadHelper('surveytranslator'); Yii::import('application.libraries.Date_Time_Converter', true); $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); $limit = (int) $limit; $start = (int) $start; $tkcount = Token::model($iSurveyId)->count(); $next = $start + $limit; $last = $start - $limit; $end = $tkcount - $limit; if ($end < 0) { $end = 0; } if ($last < 0) { $last = 0; } if ($next >= $tkcount) { $next = $tkcount - $limit; } if ($end < 0) { $end = 0; } $order = Yii::app()->request->getPost('order','tid'); $order = preg_replace('/[^_ a-z0-9-]/i', '', $order); $aData['next'] = $next; $aData['last'] = $last; $aData['end'] = $end; $searchstring = Yii::app()->request->getPost('searchstring'); $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['searchstring'] = $searchstring; $aData['surveyid'] = $iSurveyId; $aData['bgc'] = ""; $aData['limit'] = $limit; $aData['start'] = $start; $aData['order'] = $order; $aData['surveyprivate'] = $aData['thissurvey']['anonymized']; $aData['dateformatdetails'] = $dateformatdetails; $this->_renderWrappedTemplate('token', array('tokenbar', 'browse'), $aData); } /** * This function sends the shared participant info to the share panel using JSON encoding * This function is called after the share panel grid is loaded * This function returns the json depending on the user logged in by checking it from the session * @param it takes the session user data loginID * @return JSON encoded string containg sharing information */ function getTokens_json($iSurveyId, $search = null) { // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { $clang->eT("No token table.");// return json ? error not treated in js. return; } $clang = $this->getController()->lang; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'read')) { $clang->eT("We are sorry but you don't have permissions to do this.");// return json ? error not treated in js. return; } $page = Yii::app()->request->getPost('page', 1); $sidx = Yii::app()->request->getPost('sidx', 'lastname'); $sord = Yii::app()->request->getPost('sord', 'asc'); $limit = Yii::app()->request->getPost('rows', 25); $aData = new stdClass; $aData->page = $page; if (!empty($search)) { $condition = TokenDynamic::model($iSurveyId)->getSearchMultipleCondition($search); } else { $condition = new CDbCriteria(); } $condition->order = $sidx. " ". $sord; $condition->offset = ($page - 1) * $limit; $condition->limit = $limit; $tokens = Token::model($iSurveyId)->findAll($condition); $condition->offset=0; $condition->limit=0; $aData->records = Token::model($iSurveyId)->count($condition); if ($limit>$aData->records) { $limit=$aData->records; } if ($limit!=0) { $aData->total = ceil($aData->records / $limit); } else { $aData->total = 0; } Yii::app()->loadHelper("surveytranslator"); $format = getDateFormatData(Yii::app()->session['dateformat']); $aSurveyInfo = Survey::model()->findByPk($iSurveyId)->getAttributes(); //Get survey settings $attributes = getAttributeFieldNames($iSurveyId); // Now find all responses for the visible tokens $visibleTokens = array(); $answeredTokens = array(); if ($aSurveyInfo['anonymized'] == "N" && $aSurveyInfo['active'] == "Y") { foreach ($tokens as $token) { if(isset($token['token']) && $token['token']) $visibleTokens[] = $token['token']; } $answers = SurveyDynamic::model($iSurveyId)->findAllByAttributes(array('token'=>$visibleTokens)); foreach($answers as $answer) { $answeredTokens[$answer['token']] = $answer['token']; } } $bReadPermission = Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'read'); $bCreatePermission = Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'create'); $bTokenUpdatePermission = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update'); $bTokenDeletePermission = Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'delete'); $bGlobalPanelReadPermission = Permission::model()->hasGlobalPermission('participantpanel','read'); foreach ($tokens as $token) { $aRowToAdd = array(); if ((int) $token['validfrom']) { $token['validfrom'] = date($format['phpdate'] . ' H:i', strtotime(trim($token['validfrom']))); } else { $token['validfrom'] = ''; } if ((int) $token['validuntil']) { $token['validuntil'] = date($format['phpdate'] . ' H:i', strtotime(trim($token['validuntil']))); } else { $token['validuntil'] = ''; } $aRowToAdd['id'] = $token['tid']; $action=""; $action .= "
'; $aRowToAdd['cell'] = array($token['tid'], $action, $token['firstname'], $token['lastname'], $token['email'], $token['emailstatus'], $token['token'], $token['language'], $token['sent'], $token['remindersent'], $token['remindercount'], $token['completed'], $token['usesleft'], $token['validfrom'], $token['validuntil']); foreach ($attributes as $attribute) { $aRowToAdd['cell'][] = $token[$attribute]; } $aData->rows[] = $aRowToAdd; } viewHelper::disableHtmlLogging(); header("Content-type: application/json"); echo ls_json_encode($aData); } function getSearch_json($iSurveyId) { $searchcondition = Yii::app()->request->getQuery('search'); $searchcondition = urldecode($searchcondition); $finalcondition = array(); $condition = explode("||", $searchcondition); return $this->getTokens_json($iSurveyId, $condition); } /** * Called by jqGrid if a token is saved after editing * * @param mixed $iSurveyId The Survey ID */ function editToken($iSurveyId) { $clang = $this->getController()->lang; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { $clang->eT("We are sorry but you don't have permissions to do this.");// return json ? error not treated in js. return; } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } $sOperation = Yii::app()->request->getPost('oper'); if (trim(Yii::app()->request->getPost('validfrom')) == '') $from = null; else $from = date('Y-m-d H:i:s', strtotime(trim($_POST['validfrom']))); if (trim(Yii::app()->request->getPost('validuntil')) == '') $until = null; else $until = date('Y-m-d H:i:s', strtotime(trim($_POST['validuntil']))); // if edit it will update the row if ($sOperation == 'edit' && Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { // if (Yii::app()->request->getPost('language') == '') // { // $sLang = Yii::app()->session['adminlang']; // } // else // { // $sLang = Yii::app()->request->getPost('language'); // } echo $from . ',' . $until; $aData = array( 'firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => Yii::app()->request->getPost('emailstatus'), 'token' => Yii::app()->request->getPost('token'), 'language' => Yii::app()->request->getPost('language'), 'sent' => Yii::app()->request->getPost('sent'), 'remindersent' => Yii::app()->request->getPost('remindersent'), 'remindercount' => Yii::app()->request->getPost('remindercount'), 'completed' => Yii::app()->request->getPost('completed'), 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => $from, 'validuntil' => $until); $attrfieldnames = GetParticipantAttributes($iSurveyId); foreach ($attrfieldnames as $attr_name => $desc) { $value = Yii::app()->request->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') $this->getController()->error(sprintf($this->controller->lang->gT('%s cannot be left empty'), $desc['description'])); $aData[$attr_name] = Yii::app()->request->getPost($attr_name); } $token = Token::model($iSurveyId)->find('tid=' . Yii::app()->getRequest()->getPost('id')); foreach ($aData as $k => $v) $token->$k = $v; echo $token->update(); } // if add it will insert a new row elseif ($sOperation == 'add' && Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { if (Yii::app()->request->getPost('language') == '') $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => Yii::app()->request->getPost('emailstatus'), 'token' => Yii::app()->request->getPost('token'), 'language' => Yii::app()->request->getPost('language'), 'sent' => Yii::app()->request->getPost('sent'), 'remindersent' => Yii::app()->request->getPost('remindersent'), 'remindercount' => Yii::app()->request->getPost('remindercount'), 'completed' => Yii::app()->request->getPost('completed'), 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => $from, 'validuntil' => $until); $attrfieldnames = Survey::model()->findByPk($iSurveyId)->tokenAttributes; foreach ($attrfieldnames as $attr_name => $desc) { $value = Yii::app()->request->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description'])); $aData[$attr_name] = Yii::app()->request->getPost($attr_name); } $token = Token::create($surveyId); $token->setAttributes($aData, false); echo $token->save(); } elseif ($sOperation == 'del' && Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { $_POST['tid'] = Yii::app()->request->getPost('id'); $this->delete($iSurveyId); } else { $clang->eT("We are sorry but you don't have permissions to do this.");// return json ? error not treated in js. return; } } /** * Add new token form */ function addnew($iSurveyId) { // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } Yii::app()->loadHelper("surveytranslator"); $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); if (Yii::app()->request->getPost('subaction') == 'inserttoken') { Yii::import('application.libraries.Date_Time_Converter'); //Fix up dates and match to database format if (trim(Yii::app()->request->getPost('validfrom')) == '') { $validfrom = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i'); $validfrom = $datetimeobj->convert('Y-m-d H:i:s'); } if (trim(Yii::app()->request->getPost('validuntil')) == '') { $validuntil = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i'); $validuntil = $datetimeobj->convert('Y-m-d H:i:s'); } $sanitizedtoken = sanitize_token(Yii::app()->request->getPost('token')); /* Mdekker: commented out this block as it doesn't respect tokenlength * or existing tokens and was always handled by the tokenify action as * the ui still suggests if (empty($sanitizedtoken)) { $isvalidtoken = false; while ($isvalidtoken == false) { $newtoken = randomChars(15); if (!isset($existingtokens[$newtoken])) { $isvalidtoken = true; $existingtokens[$newtoken] = null; } } $sanitizedtoken = $newtoken; } */ $aData = array( 'firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => Yii::app()->request->getPost('emailstatus'), 'token' => $sanitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => Yii::app()->request->getPost('sent'), 'remindersent' => Yii::app()->request->getPost('remindersent'), 'completed' => Yii::app()->request->getPost('completed'), 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => $validfrom, 'validuntil' => $validuntil, ); // add attributes $attrfieldnames = Survey::model()->findByPk($iSurveyId)->tokenAttributes; $aTokenFieldNames=Yii::app()->db->getSchema()->getTable("{{tokens_$iSurveyId}}",true); $aTokenFieldNames=array_keys($aTokenFieldNames->columns); foreach ($attrfieldnames as $attr_name => $desc) { if(!in_array($attr_name,$aTokenFieldNames)) continue; $value = Yii::app()->getRequest()->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description'])); $aData[$attr_name] = Yii::app()->getRequest()->getPost($attr_name); } $udresult = Token::model($iSurveyId)->findAll("token <> '' and token = '$sanitizedtoken'"); if (count($udresult) == 0) { // AutoExecute $token = Token::create($iSurveyId); $token->setAttributes($aData, false); $inresult = $token->save(); $aData['success'] = true; } else { $aData['success'] = false; } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'addtokenpost'), $aData); } else { self::_handletokenform($iSurveyId, "addnew"); } } /** * Edit Tokens */ function edit($iSurveyId, $iTokenId) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); $iTokenId = sanitize_int($iTokenId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } Yii::app()->loadHelper("surveytranslator"); $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); if (Yii::app()->request->getPost('subaction')) { Yii::import('application.libraries.Date_Time_Converter', true); if (trim(Yii::app()->request->getPost('validfrom')) == '') { $_POST['validfrom'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s'); } if (trim(Yii::app()->request->getPost('validuntil')) == '') { $_POST['validuntil'] = null; } else { $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i'); $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s'); } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aTokenData['firstname'] = Yii::app()->request->getPost('firstname'); $aTokenData['lastname'] = Yii::app()->request->getPost('lastname'); $aTokenData['email'] = Yii::app()->request->getPost('email'); $aTokenData['emailstatus'] = Yii::app()->request->getPost('emailstatus'); $santitizedtoken = sanitize_token(Yii::app()->request->getPost('token')); $aTokenData['token'] = $santitizedtoken; $aTokenData['language'] = sanitize_languagecode(Yii::app()->request->getPost('language')); $aTokenData['sent'] = Yii::app()->request->getPost('sent'); $aTokenData['completed'] = Yii::app()->request->getPost('completed'); $aTokenData['usesleft'] = Yii::app()->request->getPost('usesleft'); $aTokenData['validfrom'] = Yii::app()->request->getPost('validfrom'); $aTokenData['validuntil'] = Yii::app()->request->getPost('validuntil'); $aTokenData['remindersent'] = Yii::app()->request->getPost('remindersent'); $aTokenData['remindercount'] = intval(Yii::app()->request->getPost('remindercount')); $udresult = Token::model($iSurveyId)->findAll("tid <> '$iTokenId' and token <> '' and token = '$santitizedtoken'"); if (count($udresult) == 0) { //$aTokenData = array(); $attrfieldnames = $udresult[0]->survey->tokenAttributes; foreach ($attrfieldnames as $attr_name => $desc) { $value = Yii::app()->request->getPost($attr_name); if ($desc['mandatory'] == 'Y' && trim($value) == '') $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description'])); $aTokenData[$attr_name] = Yii::app()->request->getPost($attr_name); } $token = Token::model($iSurveyId)->findByPk($iTokenId); foreach ($aTokenData as $k => $v) $token->$k = $v; $token->save(); $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array( 'title' => $clang->gT("Success"), 'message' => $clang->gT("The token entry was successfully updated.") . "".sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."),$newDummyToken,$invalidtokencount) .$clang->gT("Try with a bigger token length.")."
" ."\ngetController()->createUrl("admin/tokens/sa/browse/surveyid/$iSurveyId") . "', '_top')\" />\n" ); } $this->_renderWrappedTemplate('token', array('tokenbar','message' => $message),$aData); } else { $tokenlength = !empty(Token::model($iSurveyId)->survey->tokenlength) ? Token::model($iSurveyId)->survey->tokenlength : 15; $thissurvey = getSurveyInfo($iSurveyId); $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $iSurveyId; $aData['tokenlength'] = $tokenlength; $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'],$clang->langcode); $aData['aAttributeFields']=GetParticipantAttributes($iSurveyId); $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData); } } /** * Handle managetokenattributes action */ function managetokenattributes($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } Yii::app()->loadHelper("surveytranslator"); $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aData['tokenfields'] = getAttributeFieldNames($iSurveyId); $aData['tokenfielddata'] = $aData['thissurvey']['attributedescriptions']; // Prepare token fiel list for dropDownList $tokenfieldlist=array(); foreach($aData['tokenfields'] as $tokenfield){ if (isset($aData['tokenfielddata'][$tokenfield])) $descrition = $aData['tokenfielddata'][$tokenfield]['description']; else $descrition = ""; $descrition=sprintf($clang->gT("Attribute %s (%s)"),str_replace("attribute_","",$tokenfield),$descrition); $tokenfieldlist[]=array("id"=>$tokenfield,"descrition"=>$descrition); } $aData['tokenfieldlist'] = $tokenfieldlist; $languages = array_merge((array) Survey::model()->findByPk($iSurveyId)->language, Survey::model()->findByPk($iSurveyId)->additionalLanguages); $captions = array(); foreach ($languages as $language) $captions[$language] = SurveyLanguageSetting::model()->findByAttributes(array('surveyls_survey_id' => $iSurveyId, 'surveyls_language' => $language))->attributeCaptions; $aData['languages'] = $languages; $aData['tokencaptions'] = $captions; $aData['nrofattributes'] = 0; $aData['examplerow'] = TokenDynamic::model($iSurveyId)->find(); $aData['aCPDBAttributes']['']=$clang->gT('(none)'); foreach (ParticipantAttributeName::model()->getCPDBAttributes() as $aCPDBAttribute) { $aData['aCPDBAttributes'][$aCPDBAttribute['attribute_id']]=$aCPDBAttribute['attribute_name']; } $this->_renderWrappedTemplate('token', array('tokenbar', 'managetokenattributes'), $aData); } /** * Update token attributes */ function updatetokenattributes($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } $number2add = sanitize_int(Yii::app()->request->getPost('addnumber'), 1, 100); $tokenattributefieldnames = getAttributeFieldNames($iSurveyId); $i = 1; for ($b = 0; $b < $number2add; $b++) { while (in_array('attribute_' . $i, $tokenattributefieldnames) !== false) { $i++; } $tokenattributefieldnames[] = 'attribute_' . $i; Yii::app()->db->createCommand(Yii::app()->db->getSchema()->addColumn("{{tokens_".intval($iSurveyId)."}}", 'attribute_' . $i, 'VARCHAR(255)'))->execute(); $fields['attribute_' . $i] = array('type' => 'VARCHAR', 'constraint' => '255'); } Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyId . '}}', true); // Refresh schema cache just in case the table existed in the past LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed Yii::app()->session['flashmessage'] = sprintf($clang->gT("%s field(s) were successfully added."), $number2add); Yii::app()->getController()->redirect(array("/admin/tokens/sa/managetokenattributes/surveyid/$iSurveyId")); } /** * Delete token attributes */ function deletetokenattributes($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { Yii::app()->session['flashmessage'] = $clang->gT("No token table."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $confirm=Yii::app()->request->getPost('confirm',''); $cancel=Yii::app()->request->getPost('cancel',''); $tokenfields = getAttributeFieldNames($iSurveyId); $sAttributeToDelete=Yii::app()->request->getPost('deleteattribute',''); tracevar($sAttributeToDelete); if(!in_array($sAttributeToDelete,$tokenfields)) $sAttributeToDelete=false; tracevar($sAttributeToDelete); if ($cancel=='cancel') { Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/$iSurveyId")); } elseif ($confirm!='confirm' && $sAttributeToDelete) { $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array( 'title' => sprintf($clang->gT("Delete token attribute %s"),$sAttributeToDelete), 'message' => "".$clang->gT("If you remove this attribute, you will lose all information.") . "
\n" . CHtml::form(array("admin/tokens/sa/deletetokenattributes/surveyid/{$iSurveyId}"), 'post',array('id'=>'attributenumber')) . CHtml::hiddenField('deleteattribute',$sAttributeToDelete) . CHtml::hiddenField('sid',$iSurveyId) . CHtml::htmlButton($clang->gT('Delete attribute'),array('type'=>'submit','value'=>'confirm','name'=>'confirm')) . CHtml::htmlButton($clang->gT('Cancel'),array('type'=>'submit','value'=>'cancel','name'=>'cancel')) . CHtml::endForm() )), $aData); } elseif($sAttributeToDelete) { $sTableName="{{tokens_".intval($iSurveyId)."}}"; Yii::app()->db->createCommand(Yii::app()->db->getSchema()->dropColumn($sTableName, $sAttributeToDelete))->execute(); Yii::app()->db->schema->getTable($sTableName, true); // Refresh schema cache just in case the table existed in the past LimeExpressionManager::SetDirtyFlag(); Yii::app()->session['flashmessage'] = sprintf($clang->gT("Attribute %s was deleted."), $sAttributeToDelete); Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/$iSurveyId")); } else { Yii::app()->session['flashmessage'] = $clang->gT("The selected attribute was invalid."); Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/$iSurveyId")); } } /** * updatetokenattributedescriptions action */ function updatetokenattributedescriptions($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } // find out the existing token attribute fieldnames $tokenattributefieldnames = getAttributeFieldNames($iSurveyId); $languages = array_merge((array) Survey::model()->findByPk($iSurveyId)->language, Survey::model()->findByPk($iSurveyId)->additionalLanguages); $fieldcontents = array(); $captions = array(); foreach ($tokenattributefieldnames as $fieldname) { $fieldcontents[$fieldname] = array( 'description' => strip_tags(Yii::app()->request->getPost('description_' . $fieldname)), 'mandatory' => Yii::app()->request->getPost('mandatory_' . $fieldname) == 'Y' ? 'Y' : 'N', 'show_register' => Yii::app()->request->getPost('show_register_' . $fieldname) == 'Y' ? 'Y' : 'N', 'cpdbmap' => Yii::app()->request->getPost('cpdbmap_' . $fieldname) ); foreach ($languages as $language) $captions[$language][$fieldname] = $_POST["caption_{$fieldname}_$language"]; } Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents))); foreach ($languages as $language) { $ls = SurveyLanguageSetting::model()->findByAttributes(array('surveyls_survey_id' => $iSurveyId, 'surveyls_language' => $language)); $ls->surveyls_attributecaptions = json_encode($captions[$language]); $ls->save(); } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array( 'title' => $clang->gT('Token attribute descriptions were successfully updated.'), 'message' => "$iq\n"); } } // End for each entry } // End foreach responseGroup } // End of if resnum >= 1 $aData['duplicatelist'] = $duplicatelist; $aData['invalidemaillist'] = $invalidemaillist; $aData['invalidemailcount'] = $invalidemailcount; $aData['resultnum'] = $resultnum; $aData['xv'] = $xv; $aData['xy'] = $xy; $aData['xz'] = $xz; $this->_renderWrappedTemplate('token', array('tokenbar', 'ldappost'), $aData); } else { $aData['sError'] = $clang->gT("Can't bind to the LDAP directory"); $this->_renderWrappedTemplate('token', array('tokenbar', 'ldapform'), $aData); } @ldap_close($ds); } else { $aData['sError'] = $clang->gT("Can't connect to the LDAP directory"); $this->_renderWrappedTemplate('token', array('tokenbar', 'ldapform'), $aData); } } } /** * import from csv */ function import($iSurveyId) { $clang = $this->getController()->lang; $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js'); $aEncodings =aEncodingsArray(); if (Yii::app()->request->getPost('submit')) { if (Yii::app()->request->getPost('csvcharset') && Yii::app()->request->getPost('csvcharset')) //sanitize charset - if encoding is not found sanitize to 'auto' { $uploadcharset = Yii::app()->request->getPost('csvcharset'); if (!array_key_exists($uploadcharset, $aEncodings)) { $uploadcharset = 'auto'; } $filterduplicatetoken = (Yii::app()->request->getPost('filterduplicatetoken') && Yii::app()->request->getPost('filterduplicatetoken') == 'on'); $filterblankemail = (Yii::app()->request->getPost('filterblankemail') && Yii::app()->request->getPost('filterblankemail') == 'on'); } $attrfieldnames = getAttributeFieldNames($iSurveyId); $duplicatelist = array(); $invalidemaillist = array(); $invalidformatlist = array(); $firstline = array(); $sPath = Yii::app()->getConfig('tempdir'); $sFileTmpName = $_FILES['the_file']['tmp_name']; $sFilePath = $sPath . '/' . randomChars(20); if (!@move_uploaded_file($sFileTmpName, $sFilePath)) { $aData['sError'] = $clang->gT("Upload file not found. Check your permissions and path ({$sFilePath}) for the upload directory"); $aData['aEncodings'] = $aEncodings; $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); } else { $xz = 0; $recordcount = 0; $xv = 0; // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings $tokenlistarray = file($sFilePath); $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language; if (!Yii::app()->request->getPost('filterduplicatefields') || (Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0)) { $filterduplicatefields = array('firstname', 'lastname', 'email'); } else { $filterduplicatefields = Yii::app()->request->getPost('filterduplicatefields'); } $separator = returnGlobal('separator'); foreach ($tokenlistarray as $buffer) { $buffer = @mb_convert_encoding($buffer, "UTF-8", $uploadcharset); if ($recordcount == 0) { // Parse first line (header) from CSV $buffer = removeBOM($buffer); // We alow all field except tid because this one is really not needed. $allowedfieldnames = array('participant_id','firstname','lastname','email','emailstatus','token','language','blacklisted','sent','remindersent','remindercount','validfrom','validuntil','completed','usesleft'); $allowedfieldnames = array_merge($attrfieldnames, $allowedfieldnames); // Some header don't have same column name $aReplacedFields=array( 'invited'=>'sent' ); switch ($separator) { case 'comma': $separator = ','; break; case 'semicolon': $separator = ';'; break; default: $comma = substr_count($buffer, ','); $semicolon = substr_count($buffer, ';'); if ($semicolon > $comma) $separator = ';'; else $separator = ','; } $firstline = convertCSVRowToArray($buffer, $separator, '"'); $firstline = array_map('trim', $firstline); $ignoredcolumns = array(); // Now check the first line for invalid fields foreach ($firstline as $index => $fieldname) { $firstline[$index] = preg_replace("/(.*) <[^,]*>$/", "$1", $fieldname); $fieldname = $firstline[$index]; if (!in_array($fieldname, $allowedfieldnames)) { $ignoredcolumns[] = $fieldname; } if (array_key_exists($fieldname, $aReplacedFields)) { $firstline[$index] = $aReplacedFields[$fieldname]; } } if (!in_array('firstname', $firstline) || !in_array('lastname', $firstline) || !in_array('email', $firstline)) { $recordcount = count($tokenlistarray); break; } } else { $line = convertCSVRowToArray($buffer, $separator, '"'); if (count($firstline) != count($line)) { $invalidformatlist[] = $recordcount; $recordcount++; continue; } $writearray = array_combine($firstline, $line); //kick out ignored columns foreach ($ignoredcolumns as $column) { unset($writearray[$column]); } $dupfound = false; $invalidemail = false; if ($filterduplicatetoken != false) { $dupquery = "SELECT count(tid) from {{tokens_".intval($iSurveyId)."}} where 1=1"; foreach ($filterduplicatefields as $field) { if (isset($writearray[$field])) { $dupquery.= " and ".Yii::app()->db->quoteColumnName($field)." = " . Yii::app()->db->quoteValue($writearray[$field]); } } $dupresult = Yii::app()->db->createCommand($dupquery)->queryScalar(); if ($dupresult > 0) { $dupfound = true; $duplicatelist[] = Yii::app()->db->quoteValue($writearray['firstname']) . " " . Yii::app()->db->quoteValue($writearray['lastname']) . " (" . Yii::app()->db->quoteValue($writearray['email']) . ")"; } } $writearray['email'] = trim($writearray['email']); //treat blank emails if ($filterblankemail && $writearray['email'] == '') { $invalidemail = true; $invalidemaillist[] = $line[0] . " " . $line[1] . " ( )"; } if ($writearray['email'] != '') { $aEmailAddresses = explode(';', $writearray['email']); foreach ($aEmailAddresses as $sEmailaddress) { if (!validateEmailAddress($sEmailaddress)) { $invalidemail = true; $invalidemaillist[] = $line[0] . " " . $line[1] . " (" . $line[2] . ")"; } } } if (isset($writearray['token'])) { $writearray['token'] = sanitize_token($writearray['token']); } if (!$dupfound && !$invalidemail) { // unset all empty value foreach ($writearray as $key=>$value) { if($writearray[$key]=="") unset($writearray[$key]); if (substr($value, 0, 1)=='"' && substr($value, -1)=='"')// Fix CSV quote $value = substr($value, 1, -1); } // Some default value : to be moved to Token model rules in future release ? // But think we have to accept invalid email etc ... then use specific scenario $writearray['emailstatus']=isset($writearray['emailstatus'])?$writearray['emailstatus']:"OK"; $writearray['language']=isset($writearray['language'])?$writearray['language']:$sBaseLanguage; $oToken = Token::create($iSurveyId); foreach ($writearray as $key => $value) { //if(in_array($key,$oToken->attributes)) Not needed because we filter attributes before $oToken->$key=$value; } $ir=$oToken->save(); if (!$ir) { $duplicatelist[] = $writearray['firstname'] . " " . $writearray['lastname'] . " (" . $writearray['email'] . ")"; } else { $xz++; } } $xv++; } $recordcount++; } $recordcount = $recordcount - 1; unlink($sFilePath); $aData['tokenlistarray'] = $tokenlistarray; $aData['xz'] = $xz; $aData['xv'] = $xv; $aData['recordcount'] = $recordcount; $aData['firstline'] = $firstline; $aData['duplicatelist'] = $duplicatelist; $aData['invalidformatlist'] = $invalidformatlist; $aData['invalidemaillist'] = $invalidemaillist; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData); } } else { $aData['aEncodings'] = $aEncodings; $aData['iSurveyId'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aTokenTableFields = getTokenFieldsAndNames($iSurveyId); unset($aTokenTableFields['sent']); unset($aTokenTableFields['remindersent']); unset($aTokenTableFields['remindercount']); unset($aTokenTableFields['usesleft']); foreach ($aTokenTableFields as $sKey=>$sValue) { if ($sValue['description']!=$sKey) { $sValue['description'] .= ' - '.$sKey; } $aNewTokenTableFields[$sKey]= $sValue['description']; } $aData['aTokenTableFields'] = $aNewTokenTableFields; $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData); } } /** * Generate tokens */ function tokenify($iSurveyId) { $iSurveyId = sanitize_int($iSurveyId); $clang = $this->getController()->lang; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) { Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) //If no tokens table exists { self::_newtokentable($iSurveyId); } $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; if (!Yii::app()->request->getParam('ok')) { $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array( 'title' => $clang->gT("Create tokens"), 'message' => $clang->gT("Clicking 'Yes' will generate tokens for all those in this token list that have not been issued one. Continue?") . "