sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function applyToMenuSource(\Gems_Menu_ParameterSource $source) { $source->setTokenId($this->_tokenId); if ($this->exists) { if (! isset($this->_gemsData['gr2o_patient_nr'])) { $this->_ensureRespondentData(); } $source->setTokenId($this->_tokenId); $this->getRespondentTrack()->applyToMenuSource($source); $source->offsetSet('gsu_id_survey', $this->_gemsData['gto_id_survey']); $source->offsetSet('is_completed', $this->_gemsData['gto_completion_time'] ? 1 : 0); $source->offsetSet('show_answers', $this->_gemsData['gto_completion_time'] ? 1 : 0); $source->offsetSet('gto_in_source', $this->_gemsData['gto_in_source']); $source->offsetSet('gto_reception_code', $this->_gemsData['gto_reception_code']); $receptionCode = $this->getReceptionCode(); $source->offsetSet('grc_success', $receptionCode->isSuccess() ? 1 : 0); if ($receptionCode->isSuccess() && (! $this->_gemsData['gto_completion_time']) && ($validFrom = $this->getValidFrom())) { $validUntil = $this->getValidUntil(); $today = new \MUtil_Date(); $canBeTaken = $validFrom->isEarlier($today) && ($validUntil ? $validUntil->isLater($today) : true); } else { $canBeTaken = false; } $source->offsetSet('can_be_taken', $canBeTaken); } return $this; }
Set menu parameters from this token @param \Gems_Menu_ParameterSource $source @return \Gems_Tracker_Token (continuation pattern)
entailment
public function assignTo($respondentRelationId, $relationFieldId) { if ($this->getRelationFieldId() == $relationFieldId && $this->getRelationId() == $respondentRelationId) return 0; return $this->_updateToken(array( 'gto_id_relation'=>$respondentRelationId, 'gto_id_relationfield'=>$relationFieldId ), $this->loader->getCurrentUser()->getUserId()); }
Assign this token to a specific relation @param int $respondentRelationId @param int $relationFieldId @return int 1 if data changed, 0 otherwise
entailment
public function cacheGet($key, $defaultValue = null) { if ($this->cacheHas($key)) { return $this->_cache[$key]; } else { return $defaultValue; } }
Retrieve a certain $key from the local cache For speeding up things the token can hold a local cache, living as long as the token object exists in memory. Sources can use this to store reusable information. To reset the cache on an update, the source can use the cacheReset method or the setCache method to update the changed value. @param string $key The key used in the cache @param mixed $defaultValue The optional default value to use when it is not present @return mixed
entailment
public function cacheReset($key = null) { if (is_null($key)) { $this->_cache = array(); } else { unset($this->_cache[$key]); } }
Reset the local cache for this token You can pass in an optional $key parameter to reset just that key, otherwise all the cache will be reset @param string|null $key The key to reset
entailment
protected function calculateReturnUrl() { $currentUri = $this->util->getCurrentURI(); /* // Referrer would be powerful when someone is usng multiple windows, but // the loop does not always provide a correct referrer. $referrer = $_SERVER["HTTP_REFERER"]; // If a referrer was specified and that referral is from the current site, then use it // as it is more dependable when the user has multiple windows open on the application. if ($referrer && (0 == strncasecmp($referrer, $currentUri, strlen($currentUri)))) { return $referrer; // \MUtil_Echo::track($referrer); } // */ // Use the survey return if available. $surveyReturn = $this->currentUser->getSurveyReturn(); if ($surveyReturn) { // Do not show the base url as it is in $currentUri $surveyReturn['NoBase'] = true; // Add route reset to prevet the current parameters to be // added to the url. $surveyReturn['RouteReset'] = true; // \MUtil_Echo::track($currentUri, \MUtil_Html::urlString($surveyReturn)); return $currentUri . \MUtil_Html::urlString($surveyReturn); } // Ultimate backup solution for return return $currentUri . '/ask/forward/' . \MUtil_Model::REQUEST_ID . '/' . urlencode($this->getTokenId()); }
Returns the full url Gems should forward to after survey completion. This fix allows multiple sites with multiple url's to share a single installation. @return string
entailment
public function checkRegistryRequestsAnswers() { if ($this->_gemsData) { if ($this->currentUser instanceof \Gems_User_User) { $this->_gemsData = $this->currentUser->applyGroupMask($this->_gemsData); } } else { if ($this->db instanceof \Zend_Db_Adapter_Abstract) { $this->refresh(); } else { return false; } } return $this->exists; }
Should be called after answering the request to allow the Target to check if all required registry values have been set correctly. @return boolean False if required are missing.
entailment
public function checkTokenCompletion($userId) { $result = self::COMPLETION_NOCHANGE; // Some defaults $values['gto_completion_time'] = null; $values['gto_duration_in_sec'] = null; $values['gto_result'] = null; if ($this->inSource()) { $survey = $this->getSurvey(); $values['gto_in_source'] = 1; $startTime = $survey->getStartTime($this); if ($startTime instanceof \MUtil_Date) { // Value from source overrules any set date time $values['gto_start_time'] = $startTime->toString(\Gems_Tracker::DB_DATETIME_FORMAT); } else { // Otherwise use the time kept by Gems. $startTime = $this->getDateTime('gto_start_time'); //What if we have older tokens... where no gto_start_time was set?? if (is_null($startTime)) { $startTime = new \MUtil_Date(); } // No need to set $values['gto_start_time'], it does not change } // If there is a start date there can be a completion date if ($startTime instanceof \MUtil_Date) { if ($survey->isCompleted($this)) { $complTime = $survey->getCompletionTime($this); $setCompletionTime = true; if (! $complTime instanceof \MUtil_Date) { // Token is completed but the source cannot tell the time // // Try to see it was stored already $complTime = $this->getDateTime('gto_completion_time'); if ($complTime instanceof \MUtil_Date) { // Again no need to change a time that did not change unset($values['gto_completion_time']); $setCompletionTime = false; } else { // Well anyhow it was completed now or earlier. Get the current moment. $complTime = new \MUtil_Date(); } } //Set completion time for completion event if ($setCompletionTime) { $values['gto_completion_time'] = $complTime->toString(\Gems_Tracker::DB_DATETIME_FORMAT); //Save the old value $originalCompletionTime = $this->_gemsData['gto_completion_time']; $this->_gemsData['gto_completion_time'] = $values['gto_completion_time']; } // Process any Gems side survey dependent changes if ($changed = $this->handleAfterCompletion()) { // Communicate change $result += self::COMPLETION_EVENTCHANGE; if (\Gems_Tracker::$verbose) { \MUtil_Echo::r($changed, 'Source values for ' . $this->_tokenId . ' changed by event.'); } } if ($setCompletionTime) { //Reset to old value, so changes will be picked up $this->_gemsData['gto_completion_time'] = $originalCompletionTime; } $values['gto_duration_in_sec'] = max($complTime->diffSeconds($startTime), 0); //If the survey has a resultfield, store it if ($resultField = $survey->getResultField()) { $rawAnswers = $this->getRawAnswers(); if (isset($rawAnswers[$resultField])) { // Cast to string, because that is the way the result is stored in the db // not casting to strings means e.g. float results always result in // an update, even when they did not change. $values['gto_result'] = (string) $rawAnswers[$resultField]; // Chunk of text that is too long if ($len = $this->_getResultFieldLength()) { $values['gto_result'] = substr($values['gto_result'], 0, $len); } } } if ($this->project->hasResponseDatabase()) { $this->toResponseDatabase($userId); } } } } else { $values['gto_in_source'] = 0; $values['gto_start_time'] = null; } if ($this->_updateToken($values, $userId)) { // Communicate change $result += self::COMPLETION_DATACHANGE; } return $result; }
Checks whether the survey for this token was completed and processes the result @param int $userId The id of the gems user @return int self::COMPLETION_NOCHANGE || (self::COMPLETION_DATACHANGE | self::COMPLETION_EVENTCHANGE)
entailment
public function createReplacement($newComment, $userId, array $otherValues = array()) { $values['gto_id_respondent_track'] = $this->_gemsData['gto_id_respondent_track']; $values['gto_id_round'] = $this->_gemsData['gto_id_round']; $values['gto_id_respondent'] = $this->_gemsData['gto_id_respondent']; $values['gto_id_organization'] = $this->_gemsData['gto_id_organization']; $values['gto_id_track'] = $this->_gemsData['gto_id_track']; $values['gto_id_survey'] = $this->_gemsData['gto_id_survey']; $values['gto_round_order'] = $this->_gemsData['gto_round_order']; $values['gto_round_description'] = $this->_gemsData['gto_round_description']; $values['gto_valid_from'] = $this->_gemsData['gto_valid_from']; $values['gto_valid_from_manual'] = $this->_gemsData['gto_valid_from_manual']; $values['gto_valid_until'] = $this->_gemsData['gto_valid_until']; $values['gto_valid_until_manual'] = $this->_gemsData['gto_valid_until_manual']; $values['gto_mail_sent_date'] = $this->_gemsData['gto_mail_sent_date']; $values['gto_comment'] = $newComment; $newValues = $otherValues + $values; // Now make sure there are no more date objects foreach($newValues as &$value) { if ($value instanceof \Zend_Date) { $value = $value->getIso(); } } $tokenId = $this->tracker->createToken($newValues, $userId); $replacementLog['gtrp_id_token_new'] = $tokenId; $replacementLog['gtrp_id_token_old'] = $this->_tokenId; $replacementLog['gtrp_created'] = new \MUtil_Db_Expr_CurrentTimestamp(); $replacementLog['gtrp_created_by'] = $userId; $this->db->insert('gems__token_replacements', $replacementLog); return $tokenId; }
Creates an almost exact copy of this token at the same place in the track, only without answers and other source data Returns the new token id @param string $newComment Description of why the token was replaced @param int $userId The current user @param array $otherValues Other values to set in the token @return string The new token
entailment
public function getAllUnansweredTokens($where = '') { $select = $this->tracker->getTokenSelect(); $select->andReceptionCodes() ->andRespondentTracks() ->andRounds(array()) ->andSurveys(array()) ->andTracks() ->forGroupId($this->getSurvey()->getGroupId()) ->forRespondent($this->getRespondentId(), $this->getOrganizationId()) ->onlySucces() ->forWhere('gsu_active = 1') ->forWhere('gro_active = 1 OR gro_active IS NULL') ->order('gtr_track_name') ->order('gr2t_track_info') ->order('gto_valid_until') ->order('gto_valid_from'); $this->_addRelation($select); if (!empty($where)) { $select->forWhere($where); } return $select->fetchAll(); }
Get all unanswered tokens for the person answering this token Similar to @see $this->getNextUnansweredToken() Similar to @see $this->getTokenCountUnanswered() @return array of tokendata
entailment
public function getAnswerSnippetNames() { if ($this->exists) { if (! $this->_loopCheck) { // Events should not call $this->getAnswerSnippetNames() but // $this->getTrackEngine()->getAnswerSnippetNames(). Just in // case the code writer made a mistake we have a guard here. $this->_loopCheck = true; $snippets = $this->getTrackEngine()->getRoundAnswerSnippets($this); if (! $snippets) { $snippets = $this->getSurvey()->getAnswerSnippetNames($this); } if ($snippets) { $this->_loopCheck = false; return $snippets; } } return $this->getTrackEngine()->getAnswerSnippetNames(); } else { return 'Token\\TokenNotFoundSnippet'; } }
Returns a snippet name that can be used to display the answers to this token. @return string
entailment
public function getCopiedFrom() { if (null === $this->_copiedFromTokenId) { $this->_copiedFromTokenId = $this->db->fetchOne( "SELECT gtrp_id_token_old FROM gems__token_replacements WHERE gtrp_id_token_new = ?", $this->_tokenId ); } return $this->_copiedFromTokenId; }
Get the token id of the token this one was copied from, null when not loaded, false when does not exist @return string
entailment
public function getCopiedTo() { if (null === $this->_copiedToTokenIds) { $this->_copiedToTokenIds = $this->db->fetchPairs( "SELECT gtrp_id_token_new, gtrp_id_token_new FROM gems__token_replacements WHERE gtrp_id_token_old = ?", $this->_tokenId ); if (! $this->_copiedToTokenIds) { $this->_copiedToTokenIds = []; } } return $this->_copiedToTokenIds; }
The token id's of the tokens this one was copied to, null when not loaded, [] when none exist @return array tokenId => tokenId
entailment
public function getEmail() { // If staff, return null, we don't know who to email if ($this->getSurvey()->isTakenByStaff()) { return null; } // If we have a relation, return that address if ($this->hasRelation()) { if ($relation = $this->getRelation()) { return $relation->getEmail(); } return null; } // It can only be the respondent return $this->getRespondent()->getEmailAddress(); }
Get the email address of the person who needs to fill out this survey. This method will return null when no address available @return string|null Email address of the person who needs to fill out the survey or null
entailment
public function getNextToken() { if (null === $this->_nextToken) { $tokenSelect = $this->tracker->getTokenSelect(); $tokenSelect ->andReceptionCodes() ->forPreviousTokenId($this->_tokenId); if ($tokenData = $tokenSelect->fetchRow()) { $this->_nextToken = $this->tracker->getToken($tokenData); $this->_nextToken->_previousToken = $this; } else { $this->_nextToken = false; } } return $this->_nextToken; }
Returns the next token in this track @return \Gems_Tracker_Token
entailment
public function getNextUnansweredToken() { $tokenSelect = $this->tracker->getTokenSelect(); $tokenSelect ->andReceptionCodes() // ->andRespondents() // ->andRespondentOrganizations() // ->andConsents ->andRounds(array()) ->andSurveys(array()) ->forRespondent($this->getRespondentId()) ->forGroupId($this->getSurvey()->getGroupId()) ->onlySucces() ->onlyValid() ->forWhere('gsu_active = 1') ->forWhere('gro_active = 1 OR gro_active IS NULL') ->order(array('gto_valid_from', 'gto_round_order')); $this->_addRelation($tokenSelect); if ($tokenData = $tokenSelect->fetchRow()) { return $this->tracker->getToken($tokenData); } }
Returns the next unanswered token for the person answering this token @return \Gems_Tracker_Token
entailment
public function getPreviousSuccessToken() { $prev = $this->getPreviousToken(); while ($prev && (! $prev->hasSuccesCode())) { $prev = $prev->getPreviousToken(); } return $prev; }
Returns the previous token that has succes in this track @return \Gems_Tracker_Token
entailment
public function getPreviousToken() { if (null === $this->_previousToken) { $tokenSelect = $this->tracker->getTokenSelect(); $tokenSelect ->andReceptionCodes() ->forNextTokenId($this->_tokenId); if ($tokenData = $tokenSelect->fetchRow()) { $this->_previousToken = $this->tracker->getToken($tokenData); $this->_previousToken->_nextToken = $this; } else { $this->_previousToken = false; } } return $this->_previousToken; }
Returns the previous token in this track @return \Gems_Tracker_Token
entailment
public function getRawAnswers() { if (! is_array($this->_sourceDataRaw)) { $this->_sourceDataRaw = $this->getSurvey()->getRawTokenAnswerRow($this->_tokenId); } return $this->_sourceDataRaw; }
Returns the answers in simple raw array format, without value processing etc. Function may return more fields than just the answers. @return array Field => Value array
entailment
public function getRelation() { if (is_null($this->_relation) || $this->_relation->getRelationId() !== $this->getRelationId()) { $model = $this->loader->getModels()->getRespondentRelationModel(); $relationObject = $model->getRelation($this->getRespondentId(), $this->getRelationId()); $this->_relation = $relationObject; } return $this->_relation; }
Get the relation object if any @return Gems_Model_RespondentRelationInstance
entailment
public function getRelationFieldName() { if ($relationFieldId = $this->getRelationFieldId()) { $names = $this->getRespondentTrack()->getTrackEngine()->getFieldNames(); $fieldPrefix = \Gems\Tracker\Model\FieldMaintenanceModel::FIELDS_NAME . \Gems\Tracker\Engine\FieldsDefinition::FIELD_KEY_SEPARATOR; $key = $fieldPrefix . $relationFieldId; return array_key_exists($key, $names) ? lcfirst($names[$key]) : null; } return null; }
Get the name of the relationfield for this token @return string
entailment
public function getRespondent() { $patientNumber = $this->getPatientNumber(); $organizationId = $this->getOrganizationId(); if (! ($this->_respondentObject instanceof \Gems_Tracker_Respondent) || $this->_respondentObject->getPatientNumber() !== $patientNumber || $this->_respondentObject->getOrganizationId() !== $organizationId) { $this->_respondentObject = $this->loader->getRespondent($patientNumber, $organizationId); } return $this->_respondentObject; }
Get the respondent linked to this token @return \Gems_Tracker_Respondent
entailment
public function getRespondentGenderHello() { $greetings = $this->util->getTranslated()->getGenderGreeting(); $gender = $this->getRespondentGender(); if (isset($greetings[$gender])) { return $greetings[$gender]; } }
Returns the gender for use as part of a sentence, e.g. Dear Mr/Mrs @return string
entailment
public function getRespondentLanguage() { if (! isset($this->_gemsData['grs_iso_lang'])) { $this->_ensureRespondentData(); if (! isset($this->_gemsData['grs_iso_lang'])) { // Still not set in a project? The it is single language $this->_gemsData['grs_iso_lang'] = $this->locale->getLanguage(); } } return $this->_gemsData['grs_iso_lang']; }
Return the default language for the respondent @return string Two letter language code
entailment
public function getRespondentName() { if ($this->hasRelation()) { if ($relation = $this->getRelation()) { return $relation->getName(); } else { return null; } } return $this->getRespondent()->getName(); }
Get the name of the person answering this token Could be the patient or the relation when assigned to one @return string
entailment
public function getRoundCode() { $roundCode = null; $roundId = $this->getRoundId(); if ($roundId > 0) { $roundCode = $this->getRespondentTrack()->getRoundCode($roundId); } return $roundCode; }
Get the round code for this token @return string|null Null when no round id is present or round no longer exists
entailment
public function getTokenCountUnanswered() { $tokenSelect = $this->tracker->getTokenSelect(new \Zend_Db_Expr('COUNT(*)')); $tokenSelect ->andReceptionCodes(array()) ->andSurveys(array()) ->andRounds(array()) ->forRespondent($this->getRespondentId()) ->forGroupId($this->getSurvey()->getGroupId()) ->onlySucces() ->onlyValid() ->forWhere('gsu_active = 1') ->forWhere('gro_active = 1 OR gro_active IS NULL') ->withoutToken($this->_tokenId); $this->_addRelation($tokenSelect); return $tokenSelect->fetchOne(); }
Returns the number of unanswered tokens for the person answering this token, minus this token itself @return int
entailment
public function handleAfterCompletion() { $survey = $this->getSurvey(); $event = $survey->getSurveyCompletedEvent(); if ($event) { try { $changed = $event->processTokenData($this); if ($changed && is_array($changed)) { $this->setRawAnswers($changed); return $changed; } } catch (\Exception $e) { $this->logger->log(sprintf( "After completion event error for token %s on survey '%s' using event '%s': %s", $this->_tokenId, $this->getSurveyName(), $event->getEventName(), $e->getMessage() ), \Zend_Log::ERR); } } }
Survey dependent calculations / answer changes that must occur after a survey is completed @param type $tokenId The tokend the answers are for @param array $tokenAnswers Array with answers. May be changed in process @return array The changed values
entailment
public function handleBeforeAnswering() { $survey = $this->getSurvey(); $event = $survey->getSurveyBeforeAnsweringEvent(); if ($event) { try { $changed = $event->processTokenInsertion($this); if ($changed && is_array($changed)) { $this->setRawAnswers($changed); if (\Gems_Tracker::$verbose) { \MUtil_Echo::r($changed, 'Source values for ' . $this->_tokenId . ' changed by event.'); } return $changed; } } catch (\Exception $e) { $this->logger->log(sprintf( "Before answering event error for token %s on survey '%s' using event '%s': %s", $this->_tokenId, $this->getSurveyName(), $event->getEventName(), $e->getMessage() ), \Zend_Log::ERR); } } }
Survey dependent calculations / answer changes that must occur after a survey is completed @param type $tokenId The tokend the answers are for @param array $tokenAnswers Array with answers. May be changed in process @return array The changed values
entailment
public function inSource() { if ($this->exists) { $survey = $this->getSurvey(); return $survey->inSource($this); } else { return false; } }
True is this token was exported to the source. @return boolean
entailment
public function isExpired() { $date = $this->getValidUntil(); if ($date instanceof \MUtil_Date) { return $date->isEarlierOrEqual(time()); } return false; }
True when the valid until is set and is in the past @return boolean
entailment
public function isNotYetValid() { $date = $this->getValidFrom(); if ($date instanceof \MUtil_Date) { return $date->isLaterOrEqual(time()); } return true; }
True when the valid from is in the future or not yet set @return boolean
entailment
public function setNextToken(\Gems_Tracker_Token $token) { $this->_nextToken = $token; $token->_previousToken = $this; return $this; }
Sets the next token in this track @param \Gems_Tracker_Token $token @return \Gems_Tracker_Token (continuation pattern)
entailment
public function setRawAnswers($answers) { $survey = $this->getSurvey(); $source = $survey->getSource(); $source->setRawTokenAnswers($this, $answers, $survey->getSurveyId(), $survey->getSourceSurveyId()); // They are not always loaded if ($this->hasAnswersLoaded()) { //Now update internal answer cache $this->_sourceDataRaw = $answers + $this->_sourceDataRaw; } }
Sets answers for this token to the values defined in the $answers array. Also handles updating the internal answercache if present @param array $answers
entailment
public function setReceptionCode($code, $comment, $userId) { // Make sure it is a \Gems_Util_ReceptionCode object if (! $code instanceof \Gems_Util_ReceptionCode) { $code = $this->util->getReceptionCode($code); } $values['gto_reception_code'] = $code->getCode(); if ($comment) { $values['gto_comment'] = $comment; } // \MUtil_Echo::track($values); $changed = $this->_updateToken($values, $userId); if ($changed) { if ($code->isOverwriter() || (! $code->isSuccess())) { $survey = $this->getSurvey(); // Update the consent code in the source if ($survey->inSource($this)) { $survey->updateConsent($this); } } } return $changed; }
Set the reception code for this token and make sure the necessary cascade to the source takes place. @param string $code The new (non-success) reception code or a \Gems_Util_ReceptionCode object @param string $comment Comment False values leave value unchanged @param int $userId The current user @return int 1 if the token has changed, 0 otherwise
entailment
public function setRoundDescription($description, $userId) { $values = $this->_gemsData; $values['gto_round_description'] = $description; return $this->_updateToken($values, $userId); }
Set a round description for the token @param string The new round description @param int $userId The current user @return int 1 if data changed, 0 otherwise
entailment
protected function toResponseDatabase($userId) { $responseDb = $this->project->getResponseDatabase(); // WHY EXPLANATION!! // // For some reason mysql prepared parameters do nothing with a \Zend_Db_Expr // object and that causes an error when using CURRENT_TIMESTAMP $current = \MUtil_Date::now()->toString(\Gems_Tracker::DB_DATETIME_FORMAT); $rValues = array( 'gdr_id_token' => $this->_tokenId, 'gdr_changed' => $current, 'gdr_changed_by' => $userId, 'gdr_created' => $current, 'gdr_created_by' => $userId, ); $responses = $this->getRawAnswers(); unset($responses['token'], $responses['id'], $responses['lastpage'], $responses['startlanguage'], $responses['submitdate'], $responses['startdate'], $responses['datestamp']); // first read current responses to differentiate between insert and update $responseSelect = $responseDb->select()->from('gemsdata__responses', array('gdr_answer_id', 'gdr_response')) ->where('gdr_id_token = ?', $this->_tokenId); $currentResponses = $responseDb->fetchPairs($responseSelect); if (! $currentResponses) { $currentResponses = array(); } // \MUtil_Echo::track($currentResponses, $responses); // Prepare sql $sql = "UPDATE gemsdata__responses SET `gdr_response` = ?, `gdr_changed` = ?, `gdr_changed_by` = ? WHERE gdr_id_token = ? AND gdr_answer_id = ? AND gdr_answer_row = 1"; $statement = $responseDb->prepare($sql); $inserts = array(); foreach ($responses as $fieldName => $response) { $rValues['gdr_answer_id'] = $fieldName; if (is_array($response)) { $response = join('|', $response); } $rValues['gdr_response'] = $response; if (array_key_exists($fieldName, $currentResponses)) { // Already exists, do update // But only if value changed if ($currentResponses[$fieldName] != $response) { try { // \MUtil_Echo::track($sql, $rValues['gdr_id_token'], $fieldName, $response); $statement->execute(array( $response, $rValues['gdr_changed'], $rValues['gdr_changed_by'], $rValues['gdr_id_token'], $fieldName )); } catch (\Zend_Db_Statement_Exception $e) { error_log($e->getMessage()); \Gems_Log::getLogger()->logError($e); } } } else { // We add the inserts together in the next prepared statement to improve speed $inserts[$fieldName] = $rValues; } } if (count($inserts)>0) { // \MUtil_Echo::track($inserts); try { $fields = array_keys(reset($inserts)); $fields = array_map(array($responseDb, 'quoteIdentifier'), $fields); $sql = 'INSERT INTO gemsdata__responses (' . implode(', ', $fields) . ') VALUES (' . implode(', ', array_fill(1, count($fields), '?')) . ')'; // \MUtil_Echo::track($sql); $statement = $responseDb->prepare($sql); foreach($inserts as $insert) { // \MUtil_Echo::track($insert); $statement->execute($insert); } } catch (\Zend_Db_Statement_Exception $e) { error_log($e->getMessage()); \Gems_Log::getLogger()->logError($e); } } }
Handle sending responses to the response database (if used) Triggered by checkTokenCompletion @param int $userId The id of the gems user
entailment
public function getTab() { $username = 'Not Authed'; $role = 'Unknown Role'; if (!$this->_auth->hasIdentity()) { return 'Not authorized'; } $identity = $this->_auth->getIdentity(); if (is_object($identity)) { $username = $this->_auth->getIdentity()->{$this->_user}; $role = $this->_auth->getIdentity()->{$this->_role}; } else { $username = $this->_auth->getIdentity(); $role = ''; } return $username . ' (' . $role . ')'; }
Gets menu tab for the Debugbar @return string
entailment
public function execute($trackId = null, $fieldKey = null) { $batch = $this->getBatch(); $engine = $this->loader->getTracker()->getTrackEngine($trackId); $fields = $engine->getFieldsDefinition(); $model = $fields->getMaintenanceModel(); $filter = FieldsDefinition::splitKey($fieldKey); $filter['gtf_id_track'] = $trackId; $data = $model->loadFirst($filter); // \MUtil_Echo::track($fieldKey, $data); if ($data) { unset($data['sub'], $data['gtf_id_field'], $data['gtf_id_track'], $data['gtf_filter_id'], // TODO: Export track filters $data['gtf_changed'], $data['gtf_changed_by'], $data['gtf_created'], $data['gtf_created_by'], $data['calculation'], $data['htmlUse'], $data['htmlCalc']); if (isset($data['gtf_calculate_using']) && $data['gtf_calculate_using']) { $calcs = explode(FieldAbstract::FIELD_SEP, $data['gtf_calculate_using']); foreach ($calcs as &$key) { $key = $this->translateFieldCode($fields, $key); } $data['gtf_calculate_using'] = implode(FieldAbstract::FIELD_SEP, $calcs); } $count = $batch->addToCounter('fields_exported'); if ($count == 1) { $this->exportTypeHeader('fields'); } // The number and order of fields can change per field and installation $this->exportFieldHeaders($data); $this->exportFieldData($data); $this->exportFlush(); $batch->setMessage('fields_export', sprintf( $this->plural('%d field exported', '%d fields exported', $count), $count )); } }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
protected function _addPeriodSelectors(array &$elements, $dates, $defaultDate = null, $switchToSelect = 4) { if (is_array($dates) && (1 === count($dates))) { $fromLabel = reset($dates); $dates = key($dates); } else { $fromLabel = $this->_('From'); } if (is_string($dates)) { $element = new \Zend_Form_Element_Hidden(self::PERIOD_DATE_USED); $element->setValue($dates); } else { if (count($dates) >= $switchToSelect) { $element = $this->_createSelectElement(self::PERIOD_DATE_USED, $dates); $element->setLabel($this->_('For date')); $fromLabel = ''; } else { $element = $this->_createRadioElement(self::PERIOD_DATE_USED, $dates); $element->setSeparator(' '); $fromLabel = html_entity_decode(' » ', ENT_QUOTES, 'UTF-8'); } $fromLabel .= $this->_('from'); if ((null === $defaultDate) || (! isset($dates[$defaultDate]))) { // Set value to first key reset($dates); $defaultDate = key($dates); } $element->setValue($defaultDate); } $elements[self::PERIOD_DATE_USED] = $element; $type = 'date'; if ($this->dateFormat) { $options['dateFormat'] = $this->dateFormat; list($dateFormat, $separator, $timeFormat) = \MUtil_Date_Format::splitDateTimeFormat($options['dateFormat']); if ($timeFormat) { if ($dateFormat) { $type = 'datetime'; } else { $type = 'time'; } } } $options['label'] = $fromLabel; \MUtil_Model_Bridge_FormBridge::applyFixedOptions($type, $options); $elements['datefrom'] = new \Gems_JQuery_Form_Element_DatePicker('datefrom', $options); $options['label'] = ' ' . $this->_('until'); $elements['dateuntil'] = new \Gems_JQuery_Form_Element_DatePicker('dateuntil', $options); }
Generate two date selectors and - depending on the number of $dates passed - either a hidden element containing the field name or an radio button or dropdown selector for the type of date to use. @param array $elements Search element array to which the element are added. @param mixed $dates A string fieldName to use or an array of fieldName => Label @param string $defaultDate Optional element, otherwise first is used. @param int $switchToSelect The number of dates where this function should switch to select display
entailment
protected function _createCheckboxElement($name, $label, $description = null) { if ($name && $label) { $element = $this->form->createElement('checkbox', $name); $element->setLabel($label); $element->getDecorator('Label')->setOption('placement', \Zend_Form_Decorator_Abstract::APPEND); if ($description) { $element->setDescription($description); $element->setAttrib('title', $description); } return $element; } }
Creates a \Zend_Form_Element_Select If $options is a string it is assumed to contain an SQL statement. @param string $name Name of the element @param string $label Label for element @param string $description Optional description @return \Zend_Form_Element_Checkbox
entailment
protected function _createMultiCheckBoxElements($name, $options, $separator = null, $toggleLabel = null, $breakBeforeToggle = false) { $elements[$name] = $this->_createMultiElement('multiCheckbox', $name, $options, null); if (! $elements[$name]) { return []; } if (null === $separator) { $separator = ' '; } $elements[$name]->setSeparator($separator); if (false === $toggleLabel) { return $elements; } if ($breakBeforeToggle) { $elements['break_' . $name] = \MUtil_Html::create('br'); } $tName = 'toggle_' . $name; $options = [ 'label' => $toggleLabel ? $toggleLabel : $this->_('Toggle'), 'selector' => "input[name^=$name]", ]; $elements[$tName] = $this->form->createElement('ToggleCheckboxes', $tName, $options); return $elements; }
Creates a \Zend_Form_Element_MultiCheckbox If $options is a string it is assumed to contain an SQL statement. @param string $name Name of the select element @param string|array $options Can be a SQL select string or key/value array of options @param mixed $separator Optional separator string @param string $toggleLabel Optional text for toggle all button, when false no button is added @param boolean $breakBeforeToggle Enter a newline before the toggle button @return array Of [\Zend_Form_Element_MultiCheckbox, [\MUtil_Bootstrap_Form_Element_ToggleCheckboxes]]
entailment
protected function _createRadioElement($name, $options, $empty = null) { return $this->_createMultiElement('radio', $name, $options, $empty); }
Creates a \Zend_Form_Element_Select If $options is a string it is assumed to contain an SQL statement. @param string $name Name of the select element @param string|array $options Can be a SQL select string or key/value array of options @param string $empty Text to display for the empty selector @return \Zend_Form_Element_Radio
entailment
protected function _createSelectElement($name, $options, $empty = null) { return $this->_createMultiElement('select', $name, $options, $empty); }
Creates a \Zend_Form_Element_Select If $options is a string it is assumed to contain an SQL statement. @param string $name Name of the select element @param string|array $options Can be a SQL select string or key/value array of options @param string $empty Text to display for the empty selector @return \Zend_Form_Element_Select
entailment
public function afterRegistry() { parent::afterRegistry(); if ($this->util && (false !== $this->searchData) && (! $this->requestCache)) { $this->requestCache = $this->util->getRequestCache(); } if ($this->requestCache) { // Do not store searchButtonId $this->requestCache->removeParams($this->searchButtonId); } }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
protected function getAutoSearchElements(array $data) { // Search text $element = $this->form->createElement('text', $this->model->getTextFilter(), array('label' => $this->_('Free search text'), 'size' => 20, 'maxlength' => 30)); return array($element); }
Returns a text element for autosearch. Can be overruled. The form / html elements to search on. Elements can be grouped by inserting null's between them. That creates a distinct group of elements @param array $data The $form field values (can be usefull, but no need to set them) @return array Of (possible nested) \Zend_Form_Element's or static text to add to the html or null for group breaks.
entailment
protected function getAutoSearchForm() { $data = $this->getSearchData(); // \MUtil_Echo::track($data); $this->form = $form = $this->createForm(array('name' => 'autosubmit', 'class' => 'form-inline', 'role' => 'form')); $elements = $this->getAutoSearchElements($data); if ($elements) { // Assign a name so autosubmit will only work on this form (when there are others) $form->setHtml('div'); $div = $form->getHtml(); $div->class = 'search'; $span = $div->div(array('class' => 'panel panel-default'))->div(array('class' => 'inputgroup panel-body')); $elements[] = $this->getAutoSearchSubmit(); if ($reset = $this->getAutoSearchReset()) { $elements[] = $reset; } $prev = null; foreach (\MUtil_Ra::flatten($elements) as $element) { if ($element instanceof \Zend_Form_Element) { $appendLabel = false; if ($element->getLabel()) { $labelDecor = $element->getDecorator('Label'); if ($labelDecor) { $appendLabel = \Zend_Form_Decorator_Abstract::APPEND === $labelDecor->getPlacement(); if (! $appendLabel) { $span->label($element); } } } $span->input($element); if ($appendLabel) { $span->label($element); } // TODO: Elementen automatisch toevoegen in \MUtil_Form $form->addElement($element); } elseif (null === $element && $prev !== null) { $span = $div->div(array('class' => 'panel panel-default'))->div(array('class' => 'inputgroup panel-body')); } else { $span[] = $element; } $prev = $element; } // \MUtil_Echo::track($data); if ($this->request->isPost()) { if (! $form->isValid($data)) { $this->addMessage($form->getErrorMessages()); $this->addMessage($form->getMessages()); } } else { $form->populate($data); } if ($this->containingId) { $href = $this->getAutoSearchHref(); if ($href) { $form->setAutoSubmit($href, $this->containingId); } } return $form; } }
Creates an autosearch form for indexAction. @return \Gems_Form|null
entailment
protected function getAutoSearchReset() { if ($menuItem = $this->menu->getCurrent()) { $link = $menuItem->toActionLink($this->request, array('reset' => 1), $this->_('Reset search')); $element = new \MUtil_Form_Element_Html('reset'); $element->setValue($link); return $element; } }
Creates a reset button for the search form @return \Zend_Form_Element_Html or null
entailment
public static function getPeriodFilter(array &$filter, \Zend_Db_Adapter_Abstract $db, $inFormat = null, $outFormat = null) { $from = array_key_exists('datefrom', $filter) ? $filter['datefrom'] : null; $until = array_key_exists('dateuntil', $filter) ? $filter['dateuntil'] : null; $period = array_key_exists(self::PERIOD_DATE_USED, $filter) ? $filter[self::PERIOD_DATE_USED] : null; unset($filter[self::PERIOD_DATE_USED], $filter['datefrom'], $filter['dateuntil']); if (! $period) { return; } if (null === $outFormat) { $outFormat = 'yyyy-MM-dd'; } if (null === $inFormat) { $inFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat'); } if ($from && \Zend_Date::isDate($from, $inFormat)) { $datefrom = $db->quote(\MUtil_Date::format($from, $outFormat, $inFormat)); } else { $datefrom = null; } if ($until && \Zend_Date::isDate($until, $inFormat)) { $dateuntil = $db->quote(\MUtil_Date::format($until, $outFormat, $inFormat)); } else { $dateuntil = null; } if (! ($datefrom || $dateuntil)) { return; } switch ($period[0]) { case '_': // overlaps $periods = explode(' ', substr($period, 1)); if ($datefrom && $dateuntil) { return sprintf( '(%1$s <= %4$s OR (%1$s IS NULL AND %2$s IS NOT NULL)) AND (%2$s >= %3$s OR %2$s IS NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom, $dateuntil ); } if ($datefrom) { return sprintf( '%2$s >= %3$s OR (%2$s IS NULL AND %1$s IS NOT NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom ); } if ($dateuntil) { return sprintf( '%1$s <= %3$s OR (%1$s IS NULL AND %2$s IS NOT NULL)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $dateuntil ); } return; case '-': // within $periods = explode(' ', substr($period, 1)); if ($datefrom && $dateuntil) { return sprintf( '%1$s >= %3$s AND %2$s <= %4$s', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom, $dateuntil ); } if ($datefrom) { return sprintf( '%1$s >= %3$s AND (%2$s IS NULL OR %2$s >= %3$s)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $datefrom ); } if ($dateuntil) { return sprintf( '%2$s <= %3$s AND (%1$s IS NULL OR %1$s <= %3$s)', $db->quoteIdentifier($periods[0]), $db->quoteIdentifier($periods[1]), $dateuntil ); } return; default: if ($datefrom && $dateuntil) { return sprintf( '%s BETWEEN %s AND %s', $db->quoteIdentifier($period), $datefrom, $dateuntil ); } if ($datefrom) { return sprintf( '%s >= %s', $db->quoteIdentifier($period), $datefrom ); } if ($dateuntil) { return sprintf( '%s <= %s', $db->quoteIdentifier($period), $dateuntil ); } return; } }
Helper function to generate a period query string @param array $filter A filter array or $request->getParams() @param \Zend_Db_Adapter_Abstract $db @param $inFormat Optional format to use for date when reading @param $outFormat Optional format to use for date in query @return string
entailment
protected function createForm($options = null) { $optionVars = array('askCheck', 'askOld', 'checkFields', 'forceRules', 'labelWidthFactor', 'reportRules'); foreach ($optionVars as $name) { if ($this->$name !== null) { $options[$name] = $this->$name; } } $options['useTableLayout'] = false; // Layout set by this snippet return $this->user->getChangePasswordForm($options); }
Creates an empty form. Allows overruling in sub-classes. @param mixed $options @return \Zend_Form
entailment
protected function getMenuList() { if ($this->user->isPasswordResetRequired()) { $this->menu->setVisible(false); return null; } return parent::getMenuList(); }
overrule to add your own buttons. @return \Gems_Menu_MenuList
entailment
public function hasHtmlOutput() { if (! ($this->user->inAllowedGroup() && $this->user->canSetPassword())) { $this->addMessage($this->getNotAllowedMessage()); return false; } return parent::hasHtmlOutput(); }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
protected function saveData() { // If form is valid, but contains messages, do show them. Most likely these are the not enforced password rules if ($this->_form->getMessages()) { $this->addMessage($this->_form->getMessages()); } $this->addMessage($this->_('New password is active.')); // If the password is valid (for the form) then it is saved by the form itself. return 1; }
Hook containing the actual save code. @return int The number of "row level" items changed
entailment
protected function findTokenFor(array $row) { if (isset($row[$this->patientNrField], $row[$this->orgIdField], $row[$this->completionField]) && $row[$this->patientNrField] && $row[$this->orgIdField] && $row[$this->completionField]) { if ($row[$this->completionField] instanceof \Zend_Date) { $compl = $row[$this->completionField]->toString(\Gems_Tracker::DB_DATETIME_FORMAT); } else { $compl = $row[$this->completionField]; } $select = $this->db->select(); $select->from('gems__tokens', array('gto_id_token')) ->joinInner( 'gems__respondent2org', 'gto_id_respondent = gr2o_id_user AND gto_id_organization = gr2o_id_organization', array() ) ->where('gr2o_patient_nr = ?', $row[$this->patientNrField]) ->where('gr2o_id_organization = ?', $row[$this->orgIdField]) ->where('gto_id_survey = ?', $this->getSurveyId()) ->where('gto_valid_from <= ?', $compl) ->where('(gto_valid_until >= ? OR gto_valid_until IS NULL)', $compl); $trackId = $this->getTrackId(); if ($trackId) { $select->where('gto_id_track = ?', $trackId); } $select->order(new \Zend_Db_Expr("CASE WHEN gto_completion_time IS NULL AND gto_valid_from IS NOT NULL THEN 1 WHEN gto_completion_time IS NULL AND gto_valid_from IS NULL THEN 2 ELSE 3 END ASC")) ->order('gto_completion_time DESC') ->order('gto_valid_from ASC') ->order('gto_round_order'); $token = $this->db->fetchOne($select); if ($token) { return $token; } } return null; }
Find the token id using the passed row data and the other translator parameters. @param array $row @return string|null
entailment
public function getNoTokenError(array $row, $key) { if (! (isset($row[$this->completionField]) && $row[$this->completionField])) { return $this->_('Missing date in completion_date field.'); } if (isset($row[$this->patientNrField], $row[$this->orgIdField]) && $row[$this->patientNrField] && $row[$this->orgIdField]) { $select = $this->db->select(); $select->from('gems__tokens', array('gto_id_token')) ->joinInner( 'gems__respondent2org', 'gto_id_respondent = gr2o_id_user AND gto_id_organization = gr2o_id_organization', array() ) ->where('gr2o_patient_nr = ?', $row[$this->patientNrField]) ->where('gr2o_id_organization = ?', $row[$this->orgIdField]) ->where('gto_id_survey = ?', $this->getSurveyId()); if ($this->db->fetchOne($select)) { $survey = $this->loader->getTracker()->getSurvey($this->getSurveyId()); return sprintf( $this->_('Respondent %s has no valid token for the %s survey.'), $row[$this->patientNrField], $survey->getName() ); } } return parent::getNoTokenError($row, $key); }
Get the error message for when no token exists @return string
entailment
public function getRespondentAnswerTranslations() { $this->_targetModel->set($this->completionField, 'label', $this->_('Patient ID'), 'order', 8, 'required', true, 'type', \MUtil_Model::TYPE_DATETIME ); return parent::getRespondentAnswerTranslations(); }
Get information on the field translations @return array of fields sourceName => targetName @throws \MUtil_Model_ModelException
entailment
protected function getAutoSearchElements(array $data) { $elements = parent::getAutoSearchElements($data); $groups = $this->util->getDbLookup()->getGroups(); $elements[] = $this->_createSelectElement('gsu_id_primary_group', $groups, $this->_('(all groups)')); // If more than one source, allow to filter on it $sources = $this->util->getDbLookup()->getSources(); if (count($sources) > 1) { $elements[] = $this->_createSelectElement('gsu_id_source', $sources, $this->_('(all sources)')); } $states = array( 'act' => $this->_('Active'), 'sok' => $this->_('OK in source, not active'), 'nok' => $this->_('Blocked in source'), ); $elements[] = $this->_createSelectElement('status', $states, $this->_('(every state)')); $elements[] = \MUtil_Html::create('br'); $yesNo = $this->util->getTranslated()->getYesNo(); $elements[] = $this->_createSelectElement('gsu_insertable', $yesNo, $this->_('(any insertable)')); return $elements; }
Returns a text element for autosearch. Can be overruled. The form / html elements to search on. Elements can be grouped by inserting null's between them. That creates a distinct group of elements @param array $data The $form field values (can be usefull, but no need to set them) @return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks.
entailment
protected function bin($program = '') { // Get list of allowed search paths if ($location = $this->config()->get('binary_location')) { $locations = [$location]; } else { $locations = $this->config()->get('search_binary_locations'); } // Find program in each path foreach ($locations as $location) { $path = "{$location}/{$program}"; if (file_exists($path)) { return $path; } if (file_exists($path . '.exe')) { return $path . '.exe'; } } // Not found return null; }
Accessor to get the location of the binary @param string $program Name of binary @return string
entailment
protected function getRawOutput($file) { if (!$this->isAvailable()) { throw new Exception("getRawOutput called on unavailable extractor"); } $path = $file instanceof File ? $this->getPathFromFile($file) : $file; exec(sprintf('%s %s - 2>&1', $this->bin('pdftotext'), escapeshellarg($path)), $content, $err); if ($err) { if (!is_array($err) && $err == 1) { // For Windows compatibility $err = $content; } throw new Exception(sprintf( 'PDFTextExtractor->getContent() failed for %s: %s', $path, implode(PHP_EOL, $err) )); } return implode(PHP_EOL, $content); }
Invoke pdftotext with the given File object @param File|string $file @return string Output @throws Exception
entailment
protected function cleanupLigatures($input) { $mapping = [ 'ff' => 'ff', 'fi' => 'fi', 'fl' => 'fl', 'ffi' => 'ffi', 'ffl' => 'ffl', 'ſt' => 'ft', 'st' => 'st' ]; return str_replace(array_keys($mapping), array_values($mapping), $input); }
Removes utf-8 ligatures. @link http://en.wikipedia.org/wiki/Typographic_ligature#Computer_typesetting @param string $input @return string
entailment
protected function getReadableData() { $job = $this->monitorJob; $data = $job->getArrayCopy(); // Skip when job is not started if ($data['setTime'] == 0) return; $data['firstCheck'] = date(MonitorJob::$monitorDateFormat, $data['firstCheck']); $data['checkTime'] = date(MonitorJob::$monitorDateFormat, $data['checkTime']); $data['setTime'] = date(MonitorJob::$monitorDateFormat, $data['setTime']); $period = $data['period']; $mins = $period % 3600; $secs = $mins % 60; $hours = ($period - $mins) / 3600; $mins = ($mins - $secs) / 60; $data['period'] = sprintf('%2d:%02d:%02d',$hours,$mins,$secs); return $data; }
Create readable output @return array
entailment
protected function getWhere() { $id = intval($this->request->getParam(\MUtil_Model::REQUEST_ID)); $add = " = " . $id; return implode($add . ' OR ', (array) $this->filterOn) . $add; }
Get the appointment where for this snippet @return string
entailment
public function hasHtmlOutput() { if ($this->request->getParam($this->confirmParameter)) { $this->performAction(); $redirectRoute = $this->getRedirectRoute(); return empty($redirectRoute); } else { return parent::hasHtmlOutput(); } }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
protected function performAction() { $count = $this->db->delete("gems__appointments", $this->getWhere()); $this->addMessage(sprintf($this->plural( '%d appointment deleted.', '%d appointments deleted.', $count ), $count)); $this->setAfterCleanupRoute(); }
Overrule this function if you want to perform a different action than deleting when the user choose 'yes'.
entailment
protected function setAfterCleanupRoute() { // Default is just go to the index if ($this->cleanupAction && ($this->request->getActionName() !== $this->cleanupAction)) { $this->afterSaveRouteUrl = array( $this->request->getControllerKey() => $this->request->getControllerName(), $this->request->getActionKey() => $this->cleanupAction, ); } }
Set what to do when the form is 'finished'.
entailment
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $fparams = array('class' => 'centerAlign'); $row = $bridge->getRow(); if (isset($row[$this->filterWhen]) && $row[$this->filterWhen]) { $count = $this->db->fetchOne("SELECT COUNT(*) FROM gems__appointments WHERE " . $this->getWhere()); if ($count) { $footer = $bridge->tfrow($fparams); $footer[] = sprintf($this->plural( 'This will delete %d appointment. Are you sure?', 'This will delete %d appointments. Are you sure?', $count ), $count); $footer[] = ' '; $footer->actionLink( array($this->confirmParameter => 1), $this->_('Yes') ); $footer[] = ' '; $footer->actionLink( array($this->request->getActionKey() => $this->abortAction), $this->_('No') ); } else { $this->addMessage($this->_('Clean up not needed!')); $bridge->tfrow($this->_('No clean up needed, no appointments exist.'), $fparams); } } else { $this->addMessage($this->_('Clean up filter disabled!')); $bridge->tfrow($this->_('No clean up possible.'), array('class' => 'centerAlign')); } if ($this->displayMenu) { if (! $this->menuList) { $this->menuList = $this->menu->getCurrentMenuList($this->request, $this->_('Cancel')); $this->menuList->addCurrentSiblings(); } if ($this->menuList instanceof \Gems_Menu_MenuList) { $this->menuList->addParameterSources($bridge); } $bridge->tfrow($this->menuList, $fparams); } }
Set the footer of the browse table. Overrule this function to set the header differently, without having to recode the core table building code. @param \MUtil_Model_Bridge_VerticalTableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
protected function _getData() { $versions = $this->loader->getVersions(); $data[$this->_('Project name')] = $this->project->getName(); $data[$this->_('Project version')] = $versions->getProjectVersion(); $data[$this->_('Gems version')] = $versions->getGemsVersion(); $data[$this->_('Gems build')] = $versions->getBuild(); $data[$this->_('Gems project')] = GEMS_PROJECT_NAME; $data[$this->_('Gems web directory')] = $this->getDirInfo(GEMS_WEB_DIR); $data[$this->_('Gems root directory')] = $this->getDirInfo(GEMS_ROOT_DIR); $data[$this->_('Gems code directory')] = $this->getDirInfo(GEMS_LIBRARY_DIR); $data[$this->_('Gems variable directory')] = $this->getDirInfo(GEMS_ROOT_DIR . '/var'); $data[$this->_('MUtil version')] = \MUtil_Version::get(); $data[$this->_('Zend version')] = \Zend_Version::VERSION; $data[$this->_('Application environment')] = APPLICATION_ENV; $data[$this->_('Application baseuri')] = $this->loader->getUtil()->getCurrentURI(); $data[$this->_('Application directory')] = $this->getDirInfo(APPLICATION_PATH); $data[$this->_('Application encoding')] = APPLICATION_ENCODING; $data[$this->_('PHP version')] = phpversion(); $data[$this->_('Server Hostname')] = php_uname('n'); $data[$this->_('Server OS')] = php_uname('s'); $data[$this->_('Time on server')] = date('r'); $driveVars = array( $this->_('Session directory') => \Zend_Session::getOptions('save_path'), $this->_('Temporary files directory') => realpath(getenv('TMP')), ); if ($system = getenv('SystemDrive')) { $driveVars[$this->_('System Drive')] = realpath($system); } foreach ($driveVars as $name => $drive) { $data[$name] = $this->getDirInfo($drive); } return $data; }
Returns the data to show in the index action Allows to easily add or modifiy the information at project level @return array
entailment
protected function _showText($caption, $logFile, $emptyLabel = null, $context = null) { $this->html->h2($caption); if ($emptyLabel && (1 == $this->_getParam(\MUtil_Model::REQUEST_ID)) && file_exists($logFile)) { unlink($logFile); } if (file_exists($logFile)) { if (is_readable($logFile)) { $content = trim(file_get_contents($logFile)); if ($content) { $error = false; } else { $error = $this->_('empty file'); } } else { $error = $this->_('file content not readable'); } } else { $content = null; $error = $this->_('file not found'); } if ($emptyLabel) { $buttons = $this->html->buttonDiv(); if ($error) { $buttons->actionDisabled($emptyLabel); } else { $buttons->actionLink(array(\MUtil_Model::REQUEST_ID => 1), $emptyLabel); } } if ($error) { $this->html->pre($error, array('class' => 'disabled logFile')); } elseif (substr($logFile, -3) == '.md') { $parseDown = new \Gems\Parsedown($context); $this->html->div(array('class'=>'logFile'))->raw($parseDown->parse($content)); } else { $this->html->pre($content, array('class' => 'logFile')); } if ($emptyLabel) { // Buttons at both bottom and top. $this->html[] = $buttons; } }
Helper function to show content of a text file @param string $caption @param string $logFile @param string $emptyLabel
entailment
public function changelogAction() { $this->_showText(sprintf($this->_('Changelog %s'), $this->escort->project->name), APPLICATION_PATH . '/changelog.txt'); }
Show the project specific change log
entailment
protected function getDirInfo($directory) { if (! is_dir($directory)) { return sprintf($this->_('%s - does not exist'), $directory); } $free = disk_free_space($directory); $total = disk_total_space($directory); if ((false === $free) || (false === $total)) { return sprintf($this->_('%s - no disk information available'), $directory); } $percent = intval($free / $total * 100); return sprintf( $this->_('%s - %s free of %s = %d%% available'), $directory, \MUtil_File::getByteSized($free), \MUtil_File::getByteSized($total), $percent ); }
Tell all about it @param string $directory @return string
entailment
public function maintenanceAction() { // Switch lock if ($this->util->getMonitor()->reverseMaintenanceMonitor()) { $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set ON')); } else { $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set OFF')); // Dump the existing maintenance mode messages. $this->escort->getMessenger()->clearCurrentMessages(); $this->escort->getMessenger()->clearMessages(); \MUtil_Echo::out(); } // Redirect $request = $this->getRequest(); $this->_reroute(array($request->getActionKey() => 'index')); }
Action that switches the maintenance lock on or off.
entailment
public function apply(\MUtil_Model_ModelAbstract $model, $valueField) { $model->setSaveWhenNotNull($valueField); $model->setOnLoad($valueField, array($this, 'loadValue')); $model->setOnSave($valueField, array($this, 'saveValue')); if ($model instanceof \MUtil_Model_DatabaseModelAbstract) { $model->setOnTextFilter($valueField, false); } return $this; }
Use this function for a default application of this type to the model @param \MUtil_Model_ModelAbstract $model @param string $valueField The field containing the value to be encrypted @return \Gems_Model_Type_EncryptedField (continuation pattern)
entailment
public function loadValue($value, $isNew = false, $name = null, array $context = array(), $isPost = false) { if ($value && (! $isPost)) { if ($this->valueMask) { return str_repeat('*', 8); } else { return $this->project->decrypt($value); } } return $value; }
A ModelAbstract->setOnLoad() function that takes care of transforming a dateformat read from the database to a \Zend_Date format If empty or \Zend_Db_Expression (after save) it will return just the value currently there are no checks for a valid date format. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @param boolean $isPost True when passing on post data @return \MUtil_Date|\Zend_Db_Expr|string
entailment
public function saveValue($value, $isNew = false, $name = null, array $context = array()) { if ($value) { // \MUtil_Echo::track($value); return $this->project->encrypt($value); } }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return \Zend_Date
entailment
public function afterRegistry() { parent::afterRegistry(); if (! $this->model instanceof \Gems_Model_RespondentModel) { $this->model = $this->loader->getModels()->getRespondentModel(true); } }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
public function checkConsent($consent) { static $warned; if ($warned) { return $consent; } $unknown = $this->util->getConsentUnknown(); // Value is translated by now if in bridge if (($consent == $unknown) || ($consent == $this->_($unknown))) { $warned = true; $msg = $this->_('Please settle the informed consent form for this respondent.'); if ($this->view instanceof \Zend_View) { $url[$this->request->getControllerKey()] = 'respondent'; $url[$this->request->getActionKey()] = 'edit'; $url[\MUtil_Model::REQUEST_ID1] = $this->request->getParam(\MUtil_Model::REQUEST_ID1); $url[\MUtil_Model::REQUEST_ID2] = $this->request->getParam(\MUtil_Model::REQUEST_ID2); $urlString = $this->view->url($url) . '#tabContainer-frag-4'; $this->addMessage(\MUtil_Html::create()->a($urlString, $msg)); } else { $this->addMessage($msg); } } return $consent; }
Check if we have the 'Unknown' consent, and present a warning. The project default consent is normally 'Unknown' but this can be overruled in project.ini so checking for default is not right @static boolean $warned We need only one warning in case of multiple consents @param string $consent
entailment
protected function getCaption($onlyNotCurrent = false) { $orgId = $this->request->getParam(\MUtil_Model::REQUEST_ID2); if ($orgId == $this->loader->getCurrentUser()->getCurrentOrganizationId()) { if ($onlyNotCurrent) { return; } else { return $this->_('Respondent information'); } } else { return sprintf($this->_('%s respondent information'), $this->loader->getOrganization($orgId)->getName()); } }
Returns the caption for this table @param boolean $onlyNotCurrent Only return a string when the organization is different @return string
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $bridge = $this->model->getBridgeFor('itemTable', array('class' => 'displayer table table-condensed')); $bridge->setRepeater($this->repeater); $bridge->setColumnCount(2); // May be overruled $this->addTableCells($bridge); if ($this->model->has('row_class')) { // Make sure deactivated rounds are show as deleted foreach ($bridge->getTable()->tbody() as $tr) { foreach ($tr as $td) { if ('td' === $td->tagName) { $td->appendAttrib('class', $bridge->row_class); } } } } $this->addButtons($bridge); $this->addOnClick($bridge); $container = \MUtil_Html::create()->div(array('class' => 'table-container')); $container[] = $bridge->getTable(); return $container; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
public function hasHtmlOutput() { if ($this->model) { $this->model->setIfExists('gr2o_email', 'itemDisplay', array('MUtil_Html_AElement', 'ifmail')); $this->model->setIfExists('gr2o_comments', 'rowspan', 2); if ($this->showConsentWarning && $this->model->has('gr2o_consent')) { $this->model->set('gr2o_consent', 'formatFunction', array($this, 'checkConsent')); } if (! $this->repeater) { if (! $this->respondent) { $this->repeater = $this->model->loadRepeatable(); } else { $data = array($this->respondent->getArrayCopy()); $this->repeater = \MUtil_Lazy::repeat($data); } } return true; } return false; }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $html = $this->getHtmlSequence(); $html->h3($this->_('Choose an organization')); $user = $this->loader->getCurrentUser(); $url[$this->request->getControllerKey()] = 'organization'; $url[$this->request->getActionKey()] = 'change-ui'; if ($orgs = $user->getRespondentOrganizations()) { $html->pInfo($this->_('This organization cannot have any respondents, please choose one that does:')); foreach ($orgs as $orgId => $name) { $url['org'] = $orgId; $html->pInfo()->actionLink($url, $name)->appendAttrib('class', 'larger'); } } else { $html->pInfo($this->_('This organization cannot have any respondents.')); } return $html; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
private function _getHardAnswers($qid, $scaleId) { if (! is_array($this->_hardAnswers)) { $qaTable = $this->_getAnswersTableName(); $qTable = $this->_getQuestionsTableName(); $sql = 'SELECT a.*, q.other FROM ' . $qaTable . ' AS a LEFT JOIN ' . $qTable . ' AS q ON q.qid = a.qid AND q.language = a.language WHERE q.sid = ? AND q.language = ? ORDER BY a.qid, a.scale_id, sortorder'; $this->_hardAnswers = array(); if ($rows = $this->lsDb->fetchAll($sql, array($this->sourceSurveyId, $this->language))) { foreach ($rows as $row) { $this->_hardAnswers[$row['qid']][$row['scale_id']][$row['code']] = $row['answer']; if ($row['other']=='Y') { $this->_hardAnswers[$row['qid']][$row['scale_id']]['-oth-'] = $this->_getQuestionAttribute($row['qid'], 'other_replace_text', $this->translate->_('Other')); } } } } if (array_key_exists($qid, $this->_hardAnswers) && array_key_exists($scaleId, $this->_hardAnswers[$qid])) { return $this->_hardAnswers[$qid][$scaleId]; } return false; }
Returns the answers for a matrix or list type question from the answers table Uses 1 query to retrieve all answers and serves them as needed @param integer $qid Question ID @param integer $scaleId Scale ID
entailment
protected function _getMultiOptions($field) { $scaleId = isset($field['scale_id']) ? $field['scale_id'] : 0; $qid = $field['qid']; switch ($field['type']) { case 'F': case 'H': case 'L': case 'O': case 'R': case '1': case '!': $answers = $this->_getHardAnswers($qid, $scaleId); break; case ':': //Get the labels that could apply! $answers = false; if ($this->_getQuestionAttribute($qid, 'multiflexible_checkbox')) { $answers = $this->_getFixedAnswers($field['type']); } break; case "C": case "E": case 'G': case 'M': case 'P': case 'Y': $answers = $this->_getFixedAnswers($field['type']); break; default: $answers = false; } return $answers; }
Return an array with all possible answers for a given sid/field combination @param $field Field from getFieldMap function
entailment
private function _getPossibleAnswers($field) { $scaleId = isset($field['scale_id']) ? $field['scale_id'] : 0; $code = $field['code']; if (isset($this->_answers[$code][$scaleId])) { return $this->_answers[$code][$scaleId]; } $qid = $field['qid']; // Get the real multioption $answers = $this->_getMultiOptions($field); if (!$answers) { // If not present, try to find ranges or a description switch ($field['type']) { case ':': //Get the labels that could apply! if ($this->_getQuestionAttribute($qid, 'multiflexible_checkbox')) { $answers = $this->_getFixedAnswers($field['type']); break; } $maxvalue = $this->_getQuestionAttribute($qid, 'multiflexible_max', 10); $minvalue = $this->_getQuestionAttribute($qid, 'multiflexible_min', 1); $stepvalue = $this->_getQuestionAttribute($qid, 'multiflexible_step', 1); $answers = range($minvalue, $maxvalue, $stepvalue); $answers = array_combine($answers, $answers); break; case '5': case 'A': $answers = range(1, 5); $answers = array_combine($answers, $answers); break; case 'B': $answers = range(1, 10); $answers = array_combine($answers, $answers); break; case 'K': $maxvalue = $this->_getQuestionAttribute($qid, 'slider_max', 100); $minvalue = $this->_getQuestionAttribute($qid, 'slider_min', 0); $stepvalue = $this->_getQuestionAttribute($qid, 'slider_accuracy', 1); $answers = range($minvalue, $maxvalue, $stepvalue); $answers = array_combine($answers, $answers); break; case 'D': $answers = $this->translate->_('Date'); break; case 'N': $answers = $this->translate->_('Free number'); break; case 'X': $answers = ''; // Boilerplate, this has no answer break; case 'T': $answers = $this->translate->_('Free text (long)'); break; case 'U': $answers = $this->translate->_('Free text (very long)'); break; default: $answers = $this->translate->_('Free text'); } } $this->_answers[$code][$scaleId] = $answers; return $this->_answers[$code][$scaleId]; }
Return an array with all possible answers for a given sid/field combination @param $field Field from getFieldMap function
entailment
protected function _getQuestionAttribute($qid, $attribute, $default = null) { if (! is_array($this->_attributes)) { $this->_attributes = []; $attributesTable = $this->_getQuestionAttributesTableName(); $questionsTable = $this->_getQuestionsTableName(); $surveyTable = $this->_getSurveysTableName(); $sql = 'SELECT a.qid, a.attribute, a.value FROM ' . $attributesTable . ' AS a LEFT JOIN ' . $questionsTable . ' AS q ON q.qid = a.qid LEFT JOIN ' . $surveyTable . ' AS s ON s.sid = q.sid AND q.language = s.language WHERE s.sid = ?'; $attributes = $this->lsDb->fetchAll($sql, $this->sourceSurveyId); if (false === $attributes) { // If DB lookup failed, return the default return $default; } foreach ($attributes as $attrib) { $this->_attributes[$attrib['qid']][$attrib['attribute']] = $attrib['value']; } } if (isset($this->_attributes[$qid][$attribute]) && strlen(trim($this->_attributes[$qid][$attribute]))) { return $this->_attributes[$qid][$attribute]; } else { return $default; } }
Return a certain question attribute or the default value if it does not exist. @param string $qid @param string $attribute @param mxied $default @return mixed
entailment
private function _getTitlesMap() { if (! is_array($this->_titlesMap)) { $map = $this->_getMap(); $result = array(); foreach ($map as $key => $row) { // Title does not have to be unique. So if a title is used // twice we only use it for the first result. if (isset($row['code']) && $row['code'] && (! isset($result[$row['code']]))) { $result[$row['code']] = $key; } } $this->_titlesMap = $result; } return $this->_titlesMap; }
Returns a map of databasecode => questioncode @return array
entailment
protected function _getType($field) { switch ($field['type']) { case ':': //Get the labels that could apply! if ($this->_getQuestionAttribute($field['qid'], 'multiflexible_checkbox')) { return \MUtil_Model::TYPE_STRING; } case '5': case 'A': case 'B': case 'K': case 'N': return \MUtil_Model::TYPE_NUMERIC; case 'D': //date_format if ($format = $this->_getQuestionAttribute($field['qid'], 'date_format')) { $date = false; $time = false; if (strpos($format, ':')) { $time = true; } // Find any of -\/ to mark as a date $regExp = '/.*[-\/\\\\]+.*/m'; $matches = []; preg_match($regExp, $format, $matches); if (count($matches) > 0) { $date = true; } if ($date && !$time) { return \MUtil_Model::TYPE_DATE; } elseif (!$date && $time) { return \MUtil_Model::TYPE_TIME; } else { return \MUtil_Model::TYPE_DATETIME; } } return \MUtil_Model::TYPE_DATE; case 'X': return \MUtil_Model::TYPE_NOVALUE; case self::INTERNAL: // Not a limesurvey type, used internally for meta data return \MUtil_Model::TYPE_DATETIME; default: return \MUtil_Model::TYPE_STRING; } }
Returns @param $field Field from _getMap function @return int \MUtil_Model::TYPE_ constant
entailment
public function applyToModel(\MUtil_Model_ModelAbstract $model) { $map = $this->_getMap(); $oldfld = null; $parent = null; foreach ($map as $name => $field) { $tmpres = array(); $tmpres['thClass'] = \Gems_Tracker_SurveyModel::CLASS_MAIN_QUESTION; $tmpres['group'] = $field['gid']; $tmpres['type'] = $this->_getType($field); $tmpres['survey_question'] = true; if ($tmpres['type'] === \MUtil_Model::TYPE_DATETIME || $tmpres['type'] === \MUtil_Model::TYPE_DATE || $tmpres['type'] === \MUtil_Model::TYPE_TIME) { if ($dateFormats = $this->getDateFormats($name, $tmpres['type'])) { $tmpres = $tmpres + $dateFormats; } } if ($options = $this->_getMultiOptions($field)) { $tmpres['multiOptions'] = $options; // Limesurvey defines numeric options as string, maybe we can convert it back if ($tmpres['type'] === \MUtil_Model::TYPE_STRING) { $changeType = true; foreach(array_keys($options) as $key) { // But if we find a numeric = false, we leave as is if(!is_numeric($key)) { $changeType = false; break; } } if ($changeType == true) { $tmpres['type'] = \MUtil_Model::TYPE_NUMERIC; } } } if ($tmpres['type'] === \MUtil_Model::TYPE_NUMERIC && !isset($tmpres['multiOptions'])) { $tmpres['formatFunction'] = array($this, 'handleFloat'); } if (isset($field['question'])) { $tmpres['label'] = \MUtil_Html::raw($this->removeMarkup($field['question'])); } if (isset($field['help']) && $field['help']) { $tmpres['description'] = \MUtil_Html::raw($this->removeMarkup($field['help'])); } $oldQid = isset($oldfld['qid']) ? $oldfld['qid'] : 0; // Juggle the labels for sub-questions etc.. if (isset($field['sq_question'])) { if ($oldQid !== $field['qid']) { // Add non answered question for grouping and make it the current parent //$parent = '_' . $name . '_'; $parent = $field['title']; $model->set($parent, $tmpres); $model->set($parent, 'type', \MUtil_Model::TYPE_NOVALUE); } if (isset($field['sq_question1'])) { $tmpres['label'] = \MUtil_Html::raw(sprintf( $this->translate->_('%s: %s'), $this->removeMarkup($field['sq_question']), $this->removeMarkup($field['sq_question1']) )); } else { $tmpres['label'] = \MUtil_Html::raw($this->removeMarkup($field['sq_question'])); } $tmpres['thClass'] = \Gems_Tracker_SurveyModel::CLASS_SUB_QUESTION; } // Code does not have to be unique. So if a title is used // twice we only use it for the first result. if (isset($field['code']) && (! $model->has($field['code']))) { $name = $field['code']; } // Parent storage if (\Gems_Tracker_SurveyModel::CLASS_MAIN_QUESTION === $tmpres['thClass']) { $parent = $name; } elseif ($parent) { // Add the name of the parent item $tmpres['parent_question'] = $parent; } $model->set($name, $tmpres); $oldfld = $field; } }
Applies the fieldmap data to the model @param \MUtil_Model_ModelAbstract $model
entailment
public function getQuestionInformation() { $map = $this->_getMap(); $oldfld = null; $result = array(); foreach ($map as $name => $field) { if ($field['type'] == self::INTERNAL) { continue; } $tmpres = array(); $tmpres['class'] = \Gems_Tracker_SurveyModel::CLASS_MAIN_QUESTION; $tmpres['group'] = $field['gid']; $tmpres['type'] = $field['type']; $tmpres['title'] = $field['title']; $oldQid = isset($oldfld['qid']) ? $oldfld['qid'] : 0; if ($oldQid !== $field['qid']) { $tmpres['question'] = $this->removeMarkup($field['question']); } // Juggle the labels for sub-questions etc.. if (isset($field['sq_question'])) { if (isset($field['sq_question1'])) { $field['sq_question'] = sprintf($this->translate->_('%s: %s'), $field['sq_question'], $field['sq_question1']); } if (! isset($tmpres['question'])) { $tmpres['question'] = $this->removeMarkup($field['sq_question']); } else { $tmpres['answers'] = array(''); // Empty array prevents "n/a" display // Add non answered question for grouping $result[$field['title']] = $tmpres; // "Next" question $tmpres['question'] = $this->removeMarkup($field['sq_question']); } $tmpres['class'] = \Gems_Tracker_SurveyModel::CLASS_SUB_QUESTION; } $tmpres['answers'] = $this->_getPossibleAnswers($field); // Title does not have to be unique. So if a title is used // twice we only use it for the first result. if (isset($field['code']) && (! isset($result[$field['code']]))) { $name = $field['code']; } $result[$name] = $tmpres; if (isset($field['sgq'])) { $result[$name]['id'] = $field['sgq']; } $oldfld = $field; } // \MUtil_Echo::track($result); return $result; }
Returns an array of array with the structure: question => string, class => question|question_sub group => is for grouping type => (optional) source specific type answers => string for single types, array for selection of, nothing for no answer @return array Nested array
entailment
public function getQuestionList($forType = false) { $map = $this->_getMap(); $results = array(); $question = null; foreach ($map as $name => $field) { // Always need the last field if (isset($field['question'])) { $question = $this->removeMarkup($field['question']); } // Optional type check if ((! $forType) || ($field['type'] == $forType)) { // Juggle the labels for sub-questions etc.. if (isset($field['sq_question1'])) { $squestion = sprintf($this->translate->_('%s: %s'), $this->removeMarkup($field['sq_question']), $this->removeMarkup($field['sq_question1'])); } elseif (isset($field['sq_question'])) { $squestion = $this->removeMarkup($field['sq_question']); } else { $squestion = null; } // Title does not have to be unique. So if a title is used // twice we only use it for the first result. if (isset($field['code']) && (! isset($results[$field['code']]))) { $name = $field['code']; } if ($question && $squestion) { $results[$name] = sprintf($this->translate->_('%s - %s'), $question, $squestion);; } elseif ($question) { $results[$name] = $question; } elseif ($squestion) { $results[$name] = sprintf($this->translate->_('- %s'), $squestion); } elseif (isset($field['question']) && $field['title']) { // When question is empty, but we have a title $results[$name] = $field['title']; } } } return $results; }
Returns an array containing fieldname => label for dropdown list etc.. @param string $forType Optional type filter @return array fieldname => label
entailment
public function mapKeysToTitles(array $values) { $map = array_flip($this->_getTitlesMap()); $result = array(); foreach ($values as $key => $value) { if (isset($map[$key])) { $result[$map[$key]] = $value; } else { $result[$key] = $value; } } // \MUtil_Echo::track($result); return $result; }
Changes the keys of the values array to the more readable titles also available in LimeSurvey @param array $values
entailment
public function mapTitlesToKeys(array $values) { $titlesMap = $this->_getTitlesMap(); $result = array(); foreach ($values as $key => $value) { if (isset($titlesMap[$key])) { $result[$titlesMap[$key]] = $value; } else { $result[$key] = $value; } } // \MUtil_Echo::track($result); return $result; }
Changes the keys of the values array to the more readable titles also available in LimeSurvey @param array $values
entailment
protected function _changeIds($array, $oldId, $newId, $keys) { if (!is_array($array)) { return $array; } $matches = array_intersect_key($array, $keys); foreach($matches as $key => &$curId) { if ($curId == $oldId) { $array[$key] = $newId; } } return $array; }
Helper function for setcurrentOrganization Change value to $newId in an array if the key is in the $keys array (as key) and value is $oldId @param array $array @param int $oldId @param int $newId @param array $keys @return array
entailment
protected function _getRole($roleField) { $role = $this->_getVar($roleField); if (intval($role)) { $role = \Gems_Roles::getInstance()->translateToRoleName($role); $this->_setVar($roleField, $role); } return $role; }
Get a role with a check on the value in case of integers @param string $roleField @return mixed
entailment
protected function _getVar($name) { $store = $this->_getVariableStore(); if ($store instanceof \Zend_Session_Namespace) { if ($store->__isset($name)) { return $store->__get($name); } } else { if ($store->offsetExists($name)) { return $store->offsetGet($name); } } return null; }
Get a value in whatever store is used by this object. @param string $name @return mixed
entailment
protected function _hasVar($name) { $store = $this->_getVariableStore(); if ($store instanceof \Zend_Session_Namespace) { return $store->__isset($name); } else { return $store->offsetExists($name); } }
Checks for existence of a value in whatever store is used by this object. @param string $name @return boolean
entailment
protected function _setVar($name, $value) { $store = $this->_getVariableStore(); if ($store instanceof \Zend_Session_Namespace) { $store->__set($name, $value); } else { $store->offsetSet($name, $value); } }
Sets a value in whatever store is used by this object. @param string $name @param mixed $value @return void
entailment
protected function _unsetVar($name) { $store = $this->_getVariableStore(); if ($store instanceof \Zend_Session_Namespace) { $store->__unset($name); } else { if ($store->offsetExists($name)) { $store->offsetUnset($name); } } }
Sets a value in whatever store is used by this object. @param string $name @return void
entailment
protected function afterAuthorization(Result $result, $lastAuthorizer = null) { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', array('gula_failed_logins', 'gula_last_failed', 'gula_block_until', new \Zend_Db_Expr('UNIX_TIMESTAMP() - UNIX_TIMESTAMP(gula_last_failed) AS since_last'))) ->where('gula_login = ?', $this->getLoginName()) ->where('gula_id_organization = ?', $this->getCurrentOrganizationId()) ->limit(1); $values = $this->db->fetchRow($select); // The first login attempt if (! $values) { $values['gula_login'] = $this->getLoginName(); $values['gula_id_organization'] = $this->getCurrentOrganizationId(); $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $values['since_last'] = $this->failureIgnoreTime + 1; } if ($result->isValid()) { // Reset login failures $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; } else { // Reset the counters when the last login was longer ago than the delay factor if ($values['since_last'] > $this->failureIgnoreTime) { $values['gula_failed_logins'] = 1; } elseif ($lastAuthorizer === 'pwd') { // Only increment failed login when password failed $values['gula_failed_logins'] += 1; } // If block is already set if ($values['gula_block_until']) { // Do not change it anymore unset($values['gula_block_until']); } else { // Only set the block when needed if ($this->failureBlockCount <= $values['gula_failed_logins']) { $values['gula_block_until'] = new \Zend_Db_Expr('DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ' . $this->failureIgnoreTime . ' SECOND)'); } } // Always record the last fail $values['gula_last_failed'] = new \MUtil_Db_Expr_CurrentTimestamp(); $values['gula_failed_logins'] = max(1, $values['gula_failed_logins']); // Response gets slowly slower $sleepTime = min($values['gula_failed_logins'] - 1, 10) * 2; sleep($sleepTime); // \MUtil_Echo::track($sleepTime, $values, $result->getMessages()); } // Value not saveable unset($values['since_last']); if (isset($values['gula_login'])) { $this->db->insert('gems__user_login_attempts', $values); } else { $where = $this->db->quoteInto('gula_login = ? AND ', $this->getLoginName()); $where .= $this->db->quoteInto('gula_id_organization = ?', $this->getCurrentOrganizationId()); $this->db->update('gems__user_login_attempts', $values, $where); } } catch (\Zend_Db_Exception $e) { // Fall through as this does not work if the database upgrade did not yet run // \MUtil_Echo::r($e); } }
Process everything after authentication. @param Zend\Authentication\Result $result
entailment
public function applyToMenuSource(\Gems_Menu_ParameterSource $source) { $source->offsetSet('gsf_id_organization', $this->getBaseOrganizationId()); $source->offsetSet('gsf_active', $this->isActive() ? 1 : 0); $source->offsetSet('accessible_role', $this->inAllowedGroup() ? 1 : 0); $source->offsetSet('can_mail', $this->hasEmailAddress() ? 1 : 0); $source->offsetSet('has_2factor', $this->isTwoFactorEnabled() ? 2 : 0); }
Set menu parameters from this user @param \Gems_Menu_ParameterSource $source @return \Gems_User_User
entailment
public function authenticate($password, $testPassword = true) { $auths = $this->loadAuthorizers($password, $testPassword); $lastAuthorizer = null; foreach ($auths as $lastAuthorizer => $result) { if (is_callable($result)) { $result = call_user_func($result); } if ($result instanceof AdapterInterface) { $result = $result->authenticate(); } if ($result instanceof Result) { if (! $result->isValid()) { break; } } else { if (true === $result) { $result = new Result(Result::SUCCESS, $this->getLoginName()); } else { // Always a fail when not true if ($result === false) { $code = Result::FAILURE_CREDENTIAL_INVALID; $result = array(); } else { $code = Result::FAILURE_UNCATEGORIZED; if (is_string($result)) { $result = array($result); } } $result = new Result($code, $this->getLoginName(), $result); break; } } } if ($result->isValid() && $this->definition instanceof \Gems_User_DbUserDefinitionAbstract) { $this->definition->checkRehash($this, $password); } $this->afterAuthorization($result, $lastAuthorizer); // \MUtil_Echo::track($result); $this->_authResult = $result; return $result; }
Authenticate a users credentials using the submitted form @param string $password The password to test @param boolean $testPassword Set to false to test the non-password checks only @return Zend\Authentication\Result
entailment
protected function authorizeBlock() { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', new \Zend_Db_Expr('UNIX_TIMESTAMP(gula_block_until) - UNIX_TIMESTAMP() AS wait')) ->where('gula_block_until is not null') ->where('gula_login = ?', $this->getLoginName()) ->where('gula_id_organization = ?', $this->getCurrentOrganizationId()) ->limit(1); // Not the first login if ($block = $this->db->fetchOne($select)) { if ($block > 0) { $minutes = intval($block / 60) + 1; // Report all is not well return sprintf($this->plural('Your account is temporarily blocked, please wait a minute.', 'Your account is temporarily blocked, please wait %d minutes.', $minutes), $minutes); } else { // Clean the block once it's past $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $where = $this->db->quoteInto('gula_login = ? AND ', $this->getLoginName()); $where .= $this->db->quoteInto('gula_id_organization = ?', $this->getCurrentOrganizationId()); $this->db->update('gems__user_login_attempts', $values, $where); } } } catch (\Zend_Db_Exception $e) { // Fall through as this does not work if the database upgrade did not run // \MUtil_Echo::r($e); } return true; }
Checks if the user is allowed to login or is blocked An adapter authorizes and if the end resultis boolean, string or array it is converted into a Zend\Authenticate\Result. @return mixed Zend\Authentication\Adapter\AdapterInterface|Zend\Authenticate\Result|boolean|string|array
entailment