sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function forFilterId($filterId) { $filter = $this->agenda->getFilter($filterId); if ($filter) { return $this->forFilter($filter); } return $this; }
For a certain appointment filter @param int $filterId @return \Gems\Agenda\AppointmentSelect
entailment
public function forRespondent($respondentId, $organizationId) { $this->_select->where('gap_id_user = ?', $respondentId) ->where('gap_id_organization = ?', $organizationId); return $this; }
For a certain respondent / organization @param int $respondentId @param int $organizationId @return \Gems\Agenda\AppointmentSelect
entailment
public function uniqueForTrackId($trackId, $respTrackId, $previousAppIds) { if ($previousAppIds) { // When unique for all tracks of this type the current track // appointment id's should also be excluded. $this->uniqueInTrackInstance($previousAppIds); } $sql = "gap_id_appointment NOT IN (SELECT gr2t2a_id_appointment FROM gems__respondent2track2appointment INNER JOIN gems__respondent2track ON gr2t2a_id_respondent_track = gr2t_id_respondent_track WHERE gr2t2a_id_appointment IS NOT NULL AND gr2t_id_track = $trackId"; if ($respTrackId) { // Exclude all fields of the current respondent track as it is being recalculated // and therefore they may have changed. // // Instead we filter here on $previousAppIds $sql .= " AND NOT (gr2t2a_id_respondent_track = $respTrackId)"; } $sql .= ")"; $this->_select->where($sql); }
Add a filter for the appointment id's currently used in tracks with this track id @param int $trackId The current trrack id @param int $respTrackId The current respondent track id or null for new tracks @param array $previousAppIds array of gap_id_appointment
entailment
public function changeUiAction() { $request = $this->getRequest(); $orgId = urldecode($request->getParam('org')); $oldOrg = $this->currentUser->getCurrentOrganizationId(); $origUrl = base64_decode($request->getParam('current_uri')); $allowedOrganizations = $this->currentUser->getAllowedOrganizations(); if (isset($allowedOrganizations[$orgId])) { $this->currentUser->setCurrentOrganization($orgId); if ($origUrl) { // Check for organization id in url, but not when a patient id is stated if (strpos($origUrl, '/' . \MUtil_Model::REQUEST_ID1 . '/') === false) { foreach ($this->currentUser->possibleOrgIds as $key) { $finds[] = '/' . $key. '/' . $oldOrg; $replaces[] = '/' . $key. '/' . $orgId; } $correctUrl = str_replace($finds, $replaces, $origUrl); } else { $correctUrl = $origUrl; } // \MUtil_Echo::track($origUrl, $correctUrl); $this->getResponse()->setRedirect($correctUrl); } else { $this->currentUser->gotoStartPage($this->menu, $request); } return; } throw new \Gems_Exception( $this->_('Inaccessible or unknown organization'), 403, null, sprintf( $this->_('Access to this page is not allowed for current role: %s.'), $this->currentUser->getRole() ) ); }
Switch the active organization
entailment
public function checkAllAction() { $batch = $this->loader->getTaskRunnerBatch('orgCheckAll'); if (! $batch->isLoaded()) { $sql = "SELECT gr2o_id_user, gr2o_id_organization FROM gems__respondent2org INNER JOIN gems__reception_codes ON gr2o_reception_code = grc_id_reception_code WHERE grc_success = 1 ORDER BY gr2o_id_organization, gr2o_created"; // \MUtil_Echo::track($sql); $rows = $this->db->fetchAll($sql); foreach ($rows as $row) { $batch->addTask('Respondent\\UpdateRespondentTask', $row['gr2o_id_user'], $row['gr2o_id_organization']); } } $title = $this->_("Checking all respondents."); $this->_helper->BatchRunner($batch, $title, $this->accesslog); $this->addSnippet('Organization\\CheckOrganizationInformation'); }
Check a single organization
entailment
public function checkOrgAction() { $go = true; $orgId = $this->_getIdParam(); $org = $this->loader->getOrganization($orgId); if (! $org->getRespondentChangeEventClass()) { $go = false; $this->addMessage(sprintf( $this->_('Nothing to do: respondent change event for %s not set.'), $org->getName() )); } if (! $org->canHaveRespondents()) { $go = false; $this->addMessage(sprintf( $this->_('Nothing to do: %s has no respondents.'), $org->getName() )); } if ($go) { $batch = $this->loader->getTaskRunnerBatch('orgCheck' . $orgId); if (! $batch->isLoaded()) { $sql = "SELECT gr2o_id_user FROM gems__respondent2org INNER JOIN gems__reception_codes ON gr2o_reception_code = grc_id_reception_code WHERE gr2o_id_organization = ? AND grc_success = 1 ORDER BY gr2o_created"; // \MUtil_Echo::track($sql); $respIds = $this->db->fetchCol($sql, $orgId); foreach ($respIds as $respId) { $batch->addTask('Respondent\\UpdateRespondentTask', $respId, $orgId); } } $title = sprintf($this->_("Checking respondents for '%s'."), $org->getName()); $this->_helper->BatchRunner($batch, $title, $this->accesslog); } $this->addSnippet('Organization\\CheckOrganizationInformation'); }
Check a single organization
entailment
public function createModel($detailed, $action) { if ($this->escort instanceof \Gems_Project_Layout_MultiLayoutInterface) { $styles = \MUtil_Lazy::call(array($this->escort, 'getStyles')); } else { $styles = array(); } $model = $this->loader->getModels()->getOrganizationModel($styles); if ($detailed) { if (('create' == $action) || ('edit' == $action)) { $model->applyEditSettings(); } else { $model->applyDetailSettings(); } } else { $model->applyBrowseSettings(); } return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
public function getSearchFilter($useRequest = true) { $filter = parent::getSearchFilter(); if (isset($filter['respondentstatus'])) { switch ($filter['respondentstatus']) { case 'maybePatient': $filter[] = '(gor_add_respondents = 1 OR gor_has_respondents = 1)'; break; case 'createPatient': $filter['gor_add_respondents'] = 1; break; case 'noNewPatient': $filter['gor_add_respondents'] = 0; // Intentional fall through case 'hasPatient': $filter['gor_has_respondents'] = 1; break; case 'noPatient': $filter['gor_add_respondents'] = 0; $filter['gor_has_respondents'] = 0; break; } unset($filter['respondentstatus']); } if (isset($filter['accessible_by'])) { $filter[] = $this->db->quoteInto('gor_accessible_by LIKE ?', '%:' . intval($filter['accessible_by']) . ':%'); unset($filter['accessible_by']); } return $filter; }
Get the filter to use with the model for searching including model sorts, etc.. @param boolean $useRequest Use the request as source (when false, the session is used) @return array or false
entailment
public function afterRegistry() { $this->_filters = $this->util->getTranslated()->getEmptyDropdownArray() + $this->agenda->getFilterList(); parent::afterRegistry(); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
public function getTextSettings() { $messages = array( 'gaf_id' => $this->_('Sub filter may not be the same as this filter.'), $this->_('Filters may be chosen only once.') ); return array( 'gaf_filter_text1' => array( 'label' => $this->_('Filter 1'), 'elementClass' => 'Select', 'multiOptions' => $this->_filters, 'required' => true, 'validator' => new \MUtil_Validate_NotEqualTo('gaf_id', $messages), ), 'gaf_filter_text2' => array( 'label' => $this->_('Filter 2'), 'elementClass' => 'Select', 'multiOptions' => $this->_filters, 'required' => true, 'validator' => new \MUtil_Validate_NotEqualTo(array('gaf_id', 'gaf_filter_text1'), $messages), ), 'gaf_filter_text3' => array( 'label' => $this->_('Filter 3'), 'elementClass' => 'Select', 'multiOptions' => $this->_filters, 'validator' => new \MUtil_Validate_NotEqualTo( array('gaf_id', 'gaf_filter_text1', 'gaf_filter_text2'), $messages ), ), 'gaf_filter_text4' => array( 'label' => $this->_('Filter 4'), 'elementClass' => 'Select', 'multiOptions' => $this->_filters, 'validator' => new \MUtil_Validate_NotEqualTo( array('gaf_id', 'gaf_filter_text1', 'gaf_filter_text2', 'gaf_filter_text3'), $messages ), ), ); }
Get the settings for the gaf_filter_textN fields Fields not in this array are not shown in any way @return array gaf_filter_textN => array(modelFieldName => fieldValue)
entailment
protected function _checkReturnURI($sourceSurveyId, \Gems_Tracker_Survey $survey, array &$messages) { $lsSurvLang = $this->_getSurveyLanguagesTableName(); $sql = 'SELECT surveyls_language FROM ' . $lsSurvLang . ' WHERE surveyls_survey_id = ?'; $lsDb = $this->getSourceDatabase(); $languages = $lsDb->fetchAll($sql, array($sourceSurveyId)); $langChanges = 0; foreach ($languages as $language) { $langChanges = $langChanges + $lsDb->update( $lsSurvLang, array( 'surveyls_urldescription' => $this->_getReturnURIDescription($language['surveyls_language']) ), array( 'surveyls_survey_id = ?' => $sourceSurveyId, 'surveyls_language = ?' => $language ) ); } if ($langChanges > 0) { $messages[] = sprintf($this->_('The description of the exit url description was changed for %s languages in survey \'%s\'.'), $langChanges, $survey->getName()); } }
Checks the return URI in LimeSurvey and sets it to the correct one when needed @see checkSurvey() @param string $sourceSurveyId @param \Gems_Tracker_Survey $survey @param array $messages
entailment
protected function _checkTokenTable(array $tokenTable) { $missingFields = array(); $tokenLength = $this->_extractFieldLength($tokenTable['token']['Type']); $token_library = $this->tracker->getTokenLibrary(); if ($tokenLength < $token_library->getLength()) { $tokenLength = $token_library->getLength(); $missingFields['token'] = 'CHANGE COLUMN `token` `token` varchar(' . $tokenLength . ") CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL"; } foreach ($this->_attributeMap as $name => $field) { if (! isset($tokenTable[$field])) { $missingFields[$field] = 'ADD ' . $field . ' varchar(' . $this->attributeSize . ") CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'"; } else { $attrLength = $this->_extractFieldLength($tokenTable[$field]['Type']); if ($attrLength < $this->attributeSize) { $missingFields[$field] = "CHANGE COLUMN `$field` `$field` varchar(" . $this->attributeSize . ") CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL"; } } } return $missingFields; }
Check a token table for any changes needed by this version. @param array $tokenTable @return array Fieldname => change field commands
entailment
protected function _fillAttributeMap(\Gems_Tracker_Token $token) { $values[$this->_attributeMap['respondentid']] = substr($token->getRespondentId(), 0, $this->attributeSize); $values[$this->_attributeMap['organizationid']] = substr($token->getOrganizationId(), 0, $this->attributeSize); $values[$this->_attributeMap['consentcode']] = substr($token->getConsentCode(), 0, $this->attributeSize); $values[$this->_attributeMap['resptrackid']] = substr($token->getRespondentTrackId(), 0, $this->attributeSize); return $values; }
Returns a list of field names that should be set in a newly inserted token. @param \Gems_Tracker_Token $token @return array Of fieldname => value type
entailment
protected function _filterAnswersOnly($sourceSurveyId, array $answers) { $s = $sourceSurveyId . 'X'; $l = strlen($s); $results = array(); foreach ($answers as $key => $value) { if (substr($key, 0, $l) == $s) { $results[$key] = $value; } } return $results; }
Filters an answers array, return only those fields that where answered by the user. @param int $sourceSurveyId Survey ID @param array $answers @return array
entailment
protected function _getFieldMap($sourceSurveyId, $language = null) { $language = $this->_getLanguage($sourceSurveyId, $language); // \MUtil_Echo::track($language, $sourceSurveyId); if (! isset($this->_fieldMaps[$sourceSurveyId][$language])) { $className = $this->fieldMapClass; $this->_fieldMaps[$sourceSurveyId][$language] = new $className( $sourceSurveyId, $language, $this->getSourceDatabase(), $this->translate, $this->addDatabasePrefix(''), $this->cache, $this->getId() ); } return $this->_fieldMaps[$sourceSurveyId][$language]; }
Return a fieldmap object @param int $sourceSurveyId Survey ID @param string $language Optional (ISO) Language, uses default language for survey when null @return \Gems_Tracker_Source_LimeSurvey1m9FieldMap
entailment
protected function _getLanguage($sourceSurveyId, $language) { if (! is_string($language)) { $language = (string) $language; } if (! isset($this->_languageMap[$sourceSurveyId][$language])) { if ($language && $this->_isLanguage($sourceSurveyId, $language)) { $this->_languageMap[$sourceSurveyId][$language] = $language; } else { $lsDb = $this->getSourceDatabase(); $sql = 'SELECT language FROM ' . $this->_getSurveysTableName() . ' WHERE sid = ?'; $this->_languageMap[$sourceSurveyId][$language] = $lsDb->fetchOne($sql, $sourceSurveyId); } } return $this->_languageMap[$sourceSurveyId][$language]; }
Returns the langauge to use for the survey when this language is specified. Uses the requested language if it exists for the survey, the default language for the survey otherwise @param int $sourceSurveyId Survey ID @param string $language (ISO) Language @return string (ISO) Language
entailment
protected function _getReturnURIDescription($language) { return sprintf( $this->translate->_('Back to %s', $language), $this->project->getName() ); }
Get the return URI description to set in LimeSurvey @param string $language @return string
entailment
protected function _getSourceSurveysForSynchronisation() { // Surveys in LS $lsDb = $this->getSourceDatabase(); $select = $lsDb->select(); $select->from($this->_getSurveysTableName(), 'sid') ->order('sid'); return $lsDb->fetchCol($select); }
Returns all surveys for synchronization @return array of sourceId values or false
entailment
protected function _isLanguage($sourceSurveyId, $language) { if ($language && strlen($language)) { // Check for availability of language $sql = 'SELECT surveyls_language FROM ' . $this->_getSurveyLanguagesTableName() . ' WHERE surveyls_survey_id = ? AND surveyls_language = ?'; $lsDb = $this->getSourceDatabase(); return $lsDb->fetchOne($sql, array($sourceSurveyId, $language)); } return false; }
Check if the specified language is available in Lime Survey @param int $sourceSurveyId Survey ID @param string $language (ISO) Language @return boolean True when the language is an existing language
entailment
public function checkSourceActive($userId) { // The only method to check if it is active is by getting all the tables, // since the surveys table may be empty so we just check for existence. $sourceDb = $this->getSourceDatabase(); $tables = array_map('strtolower', $sourceDb->listTables()); $tableName = $this->addDatabasePrefix(self::SURVEYS_TABLE, false); // Get name without database prefix. $active = strtolower(in_array($tableName, $tables)); $values['gso_active'] = $active ? 1 : 0; $values['gso_status'] = $active ? 'Active' : 'Inactive'; $this->_updateSource($values, $userId); return $active; }
Check if the tableprefix exists in the source database, and change the status of this adapter in the gems_sources table accordingly @param int $userId Id of the user who takes the action (for logging) @return boolean True if the source is active
entailment
public function checkSurvey($sourceSurveyId, $surveyId, $userId) { $messages = array(); $survey = $this->tracker->getSurvey($surveyId); if (null === $sourceSurveyId) { // Was removed $values['gsu_active'] = 0; $values['gsu_surveyor_active'] = 0; $values['gsu_status'] = 'Survey was removed from source.'; if ($survey->saveSurvey($values, $userId)) { $messages[] = sprintf($this->_('The \'%s\' survey is no longer active. The survey was removed from LimeSurvey!'), $survey->getName()); } } else { $lsDb = $this->getSourceDatabase(); // SELECT sid, surveyls_title AS short_title, surveyls_description AS description, active, datestamp, ' . $this->_anonymizedField . ' $select = $lsDb->select(); // 'alloweditaftercompletion' ? $select->from($this->_getSurveysTableName(), array('active', 'datestamp', 'tokenanswerspersistence', $this->_anonymizedField)) ->joinInner( $this->_getSurveyLanguagesTableName(), 'sid = surveyls_survey_id AND language = surveyls_language', array('surveyls_title', 'surveyls_description')) ->where('sid = ?', $sourceSurveyId); $lsSurvey = $lsDb->fetchRow($select); $surveyor_title = substr(\MUtil_Html::removeMarkup(html_entity_decode($lsSurvey['surveyls_title'])), 0, 100); $surveyor_description = substr(\MUtil_Html::removeMarkup(html_entity_decode($lsSurvey['surveyls_description'])), 0, 100); $surveyor_status = ''; // ANONIMIZATION switch ($lsSurvey[$this->_anonymizedField]) { case 'Y': $surveyor_status .= 'Uses anonymous answers. '; break; case 'N': break; default: // This is for the case that $this->_anonymizedField is empty, we show an update statement. // The answers already in the table can only be linked to the response based on the completion time // this requires a manual action as token table only hold minuts while survey table holds seconds // and we might have responses with the same timestamp. $lsDb->query("UPDATE " . $this->_getSurveysTableName() . " SET `" . $this->_anonymizedField . "` = 'N' WHERE sid = ?;", $sourceSurveyId); $messages[] = sprintf($this->_("Corrected anonymization for survey '%s'"), $surveyor_title); $lsDb->query("ALTER TABLE " . $this->_getSurveyTableName($sourceSurveyId) . " ADD `token` varchar(36) default NULL;"); } // DATESTAMP if ($lsSurvey['datestamp'] == 'N') { $surveyor_status .= 'Not date stamped. '; } // DATESTAMP if ($lsSurvey['tokenanswerspersistence'] == 'N') { $surveyor_status .= 'Token-based persistence is disabled. '; } // IS ACTIVE if ($lsSurvey['active'] == 'Y') { try { $tokenTable = $lsDb->fetchAssoc('SHOW COLUMNS FROM ' . $this->_getTokenTableName($sourceSurveyId)); } catch (\Zend_Exception $e) { $tokenTable = false; } if ($tokenTable) { $missingFields = $this->_checkTokenTable($tokenTable); if ($missingFields) { $sql = "ALTER TABLE " . $this->_getTokenTableName($sourceSurveyId) . " " . implode(', ', $missingFields); $fields = implode($this->_(', '), array_keys($missingFields)); // \MUtil_Echo::track($missingFields, $sql); try { $lsDb->query($sql); $messages[] = sprintf($this->_("Added to token table '%s' the field(s): %s"), $surveyor_title, $fields); } catch (\Zend_Exception $e) { $surveyor_status .= 'Token attributes could not be created. '; $surveyor_status .= $e->getMessage() . ' '; $messages[] = sprintf($this->_("Attribute fields not created for token table for '%s'"), $surveyor_title); $messages[] = sprintf($this->_('Required fields: %s', $fields)); $messages[] = $e->getMessage(); // Maximum reporting for this case \MUtil_Echo::r($missingFields, 'Missing fields for ' . $surveyor_title); \MUtil_Echo::r($e); } } if ($this->fixTokenAttributeDescriptions($sourceSurveyId)) { $messages[] = sprintf($this->_("Updated token attribute descriptions for '%s'"), $surveyor_title); } } else { $surveyor_status .= 'No token table created. '; } } else { $surveyor_status .= 'Not active. '; } $surveyor_active = (0 === strlen($surveyor_status)); // Update Gems $values = array(); if ($survey->exists) { // Update if ($survey->isActiveInSource() != $surveyor_active) { $values['gsu_surveyor_active'] = $surveyor_active ? 1 : 0; $messages[] = sprintf($this->_('The status of the \'%s\' survey has changed.'), $survey->getName()); } // Reset to inactive if the surveyor survey has become inactive. if ($survey->isActive() && $surveyor_status) { $values['gsu_active'] = 0; $messages[] = sprintf($this->_('Survey \'%s\' IS NO LONGER ACTIVE!!!'), $survey->getName()); } if (substr($surveyor_status, 0, 127) != (string) $survey->getStatus()) { if ($surveyor_status) { $values['gsu_status'] = substr($surveyor_status, 0, 127); $messages[] = sprintf($this->_('The status of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $values['gsu_status']); } elseif ($survey->getStatus() != 'OK') { $values['gsu_status'] = 'OK'; $messages[] = sprintf($this->_('The status warning for the \'%s\' survey was removed.'), $survey->getName()); } } if ($survey->getName() != $surveyor_title) { $values['gsu_survey_name'] = $surveyor_title; $messages[] = sprintf($this->_('The name of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $surveyor_title); } if ($survey->getDescription() != $surveyor_description) { $values['gsu_survey_description'] = $surveyor_description; $messages[] = sprintf($this->_('The description of the \'%s\' survey has changed to \'%s\'.'), $survey->getName(), $surveyor_description); } } else { // New record $values['gsu_survey_name'] = $surveyor_title; $values['gsu_survey_description'] = $surveyor_description; $values['gsu_surveyor_active'] = $surveyor_active ? 1 : 0; $values['gsu_active'] = 0; $values['gsu_status'] = $surveyor_status ? $surveyor_status : 'OK'; $values['gsu_surveyor_id'] = $sourceSurveyId; $values['gsu_id_source'] = $this->getId(); $messages[] = sprintf($this->_('Imported the \'%s\' survey.'), $surveyor_title); } $survey->saveSurvey($values, $userId); // Check return url description $this->_checkReturnURI($sourceSurveyId, $survey, $messages); } return $messages; }
Survey source synchronization check function @param string $sourceSurveyId @param int $surveyId @param int $userId @return mixed message string or array of messages
entailment
public function copyTokenToSource(\Gems_Tracker_Token $token, $language, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $language = $this->_getLanguage($sourceSurveyId, $language); $lsDb = $this->getSourceDatabase(); $lsSurvLang = $this->_getSurveyLanguagesTableName(); $lsSurveys = $this->_getSurveysTableName(); $lsTokens = $this->_getTokenTableName($sourceSurveyId); $tokenId = $this->_getToken($token->getTokenId()); /******************************** * Check survey existence / url * ********************************/ // Lookup url information in surveyor, checks for survey being active as well. $sql = "SELECT surveyls_url FROM $lsSurveys INNER JOIN $lsSurvLang ON sid = surveyls_survey_id WHERE sid = ? AND surveyls_language = ? AND active='Y' LIMIT 1"; $currentUrl = $lsDb->fetchOne($sql, array($sourceSurveyId, $language)); // No field was returned if (false === $currentUrl) { throw new \Gems_Tracker_Source_SurveyNotFoundException(sprintf('The survey with id %d for token %s does not exist.', $surveyId, $tokenId), sprintf('The Lime Survey id is %s', $sourceSurveyId)); } /***************************** * Set the end_of_survey uri * *****************************/ if (!\MUtil_Console::isConsole()) { $newUrl = $this->_getReturnURI(); // Make sure the url is set correctly in surveyor. if ($currentUrl != $newUrl) { //$where = $lsDb->quoteInto('surveyls_survey_id = ? AND ', $sourceSurveyId) . // $lsDb->quoteInto('surveyls_language = ?', $language); $lsDb->update($lsSurvLang, array('surveyls_url' => $newUrl), array( 'surveyls_survey_id = ?' => $sourceSurveyId, 'surveyls_language = ?' => $language )); if (\Gems_Tracker::$verbose) { \MUtil_Echo::r("From $currentUrl\n to $newUrl", "Changed return url for $language version of $surveyId."); } } } /**************************************** * Insert token in table (if not there) * ****************************************/ $validDates = $this->getValidDates($token); // Get the mapped values $values = $this->_fillAttributeMap($token) + $validDates; // Apparently it is possible to have this value filled without a survey questionnaire. if ($token->isCompleted()) { $values['completed'] = $token->getCompletionTime()->toString(self::LS_DB_COMPLETION_FORMAT); } else { $values['completed'] = 'N'; } $result = 0; if ($oldValues = $lsDb->fetchRow("SELECT * FROM $lsTokens WHERE token = ? LIMIT 1", $tokenId)) { if ($this->tracker->filterChangesOnly($oldValues, $values)) { if (\Gems_Tracker::$verbose) { $echo = ''; foreach ($values as $key => $val) { $echo .= $key . ': ' . $oldValues[$key] . ' => ' . $val . "\n"; } \MUtil_Echo::r($echo, "Updated limesurvey values for $tokenId"); } $result = $lsDb->update($lsTokens, $values, array('token = ?' => $tokenId)); } } else { if (\Gems_Tracker::$verbose) { \MUtil_Echo::r($values, "Inserted $tokenId into limesurvey"); } $values['token'] = $tokenId; $result = $lsDb->insert($lsTokens, $values); } if ($result) { //If we have changed something, invalidate the cache $token->cacheReset(); } return $result; }
Inserts the token in the source (if needed) and sets those attributes the source wants to set. @param \Gems_Tracker_Token $token @param string $language @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return int 1 of the token was inserted or changed, 0 otherwise @throws \Gems_Tracker_Source_SurveyNotFoundException
entailment
protected function fixTokenAttributeDescriptions($sourceSurveyId) { $lsDb = $this->getSourceDatabase(); $fieldData = array(); foreach($this->_attributeMap as $fieldName) { // Only add the attribute fields if (substr($fieldName, 0, 10) == 'attribute_') { $fieldData[$fieldName] = array( 'description' => $fieldName, 'mandatory' => 'N', 'show_register'=> 'N', 'cpdbmap' => '' ); } } // We always have fields, so no need to check for empty. Just json_encode the data $fields = array( $this->_attributeDescriptionsField => json_encode($fieldData) ); return (boolean) $lsDb->update($this->_getSurveysTableName(), $fields, $lsDb->quoteInto('sid = ?', $sourceSurveyId)); }
Fix the tokenattribute descriptions When new token attributes are added, make sure the attributedescriptions field in the surveys table is updated to prevent problems when using these fields in LimeSurvey. For example by referencing them on screen. @param int $sourceSurveyId @return boolean
entailment
public function getAnswerDateTime($fieldName, \Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null) { $answers = $token->getRawAnswers(); if (isset($answers[$fieldName]) && $answers[$fieldName]) { return \MUtil_Date::ifDate( $answers[$fieldName], array(self::LS_DB_DATETIME_FORMAT, self::LS_DB_DATE_FORMAT) ); } }
Returns a field from the raw answers as a date object. A seperate function as only the source knows what format the date/time value has. @param string $fieldName Name of answer field @param \Gems_Tracker_Token $token Gems token object @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return \MUtil_Date date time or null
entailment
public function getCompletionTime(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null) { if ($token->cacheHas('submitdate')) { // Use cached value when it exists $submitDate = $token->cacheGet('submitdate'); } else { if ($token->hasAnswersLoaded()) { // Use loaded answers when loaded $submitDate = $this->getAnswerDateTime('submitdate', $token, $surveyId, $sourceSurveyId); } else { if ($token->cacheHas(self::CACHE_TOKEN_INFO)) { // Use token info when loaded to prevent extra query if not needed $tokenInfo = $this->getTokenInfo($token, $surveyId, $sourceSurveyId); $query = isset($tokenInfo['completed']) && ($tokenInfo['completed'] != 'N'); } else { $query = true; } if ($query) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsSurvey = $this->_getSurveyTableName($sourceSurveyId); $tokenId = $this->_getToken($token->getTokenId()); $submitDate = $lsDb->fetchOne("SELECT submitdate FROM $lsSurvey WHERE token = ? LIMIT 1", $tokenId); if ($submitDate) { $submitDate = \MUtil_Date::ifDate($submitDate, self::LS_DB_DATETIME_FORMAT); if (null === $submitDate) { $submitDate = false; // Null does not trigger cacheHas() } } } else { $submitDate = false; // Null does not trigger cacheHas() } } $token->cacheSet('submitdate', $submitDate); } return $submitDate instanceof \MUtil_Date ? $submitDate : null; }
Gets the time the survey was completed according to the source A source always return null when it does not know this time (or does not know it well enough). In the case \Gems_Tracker_Token will do it's best to keep track by itself. @param \Gems_Tracker_Token $token Gems token object @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return \MUtil_Date date time or null
entailment
public function getCompletedTokens($tokenIds, $sourceSurveyId) { $lsDb = $this->getSourceDatabase(); $lsToken = $this->_getTokenTableName($sourceSurveyId); // Make sure we use tokens in the format LimeSurvey likes $tokens = array_map(array($this, '_getToken'), $tokenIds); $sql = $lsDb->select() ->from($lsToken, array('token')) ->where('token IN (?)', $tokens) ->where('completed != ?', 'N'); $completedTokens = $lsDb->fetchCol($sql); // Now make sure we return tokens GemsTracker likes if ($completedTokens) { $translatedTokens = array(); // Can not use the map function here since we need a second parameter foreach($completedTokens as $token) { $translatedTokens[] = $this->_getToken($token, true); } return $translatedTokens; } return $completedTokens; }
Bulk check token completion Returns all tokens from the input array that are completed, by doing this in bulk we saved overhead and only do a deep check on the completed tokens. @param array $tokenIds @param int $sourceSurveyId @return array
entailment
public function getDatesList($language, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } // Not a question but it is a valid date choice // $results['submitdate'] = $this->_('Submitdate'); $results = $this->_getFieldMap($sourceSurveyId, $language)->getQuestionList('D'); // Prevent html output in date lists foreach($results as $key => &$value) { $value = \MUtil_Html::raw($value); } return $results; }
Returns an array containing fieldname => label for each date field in the survey. Used in dropdown list etc.. @param string $language (ISO) language string @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array fieldname => label
entailment
public function getFullQuestionList($language, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } return $this->_getFieldMap($sourceSurveyId, $language)->getFullQuestionList(); }
Returns an array containing fieldname => label for each answerable question in the survey. Used in dropdown list etc.. @param string $language (ISO) language string @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array fieldname => label @deprecated since version 1.8.4 remove in 1.8.5
entailment
public function getQuestionInformation($language, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } return $this->_getFieldMap($sourceSurveyId, $language)->getQuestionInformation(); }
Returns an array of arrays 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 @param string $language (ISO) language string @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array Nested array
entailment
public function getQuestionList($language, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } return $this->_getFieldMap($sourceSurveyId, $language)->getQuestionList(); }
Returns an array containing fieldname => label for each answerable question in the survey. Used in dropdown list etc.. @param string $language (ISO) language string @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array fieldname => label
entailment
public function getRawTokenAnswerRow($tokenId, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsTab = $this->_getSurveyTableName($sourceSurveyId); $token = $this->_getToken($tokenId); try { // Order by ID desc to get the same answers used as in the row retrieved by // getRawTokenAnswerRows() in case of double rows $values = $lsDb->fetchRow("SELECT * FROM $lsTab WHERE token = ? ORDER BY id DESC", $token); } catch (\Zend_Db_Statement_Exception $exception) { $this->logger->logError($exception, $this->request); $values = false; } if ($values) { return $this->_getFieldMap($sourceSurveyId)->mapKeysToTitles($values); } else { return array(); } }
Returns the answers in simple raw array format, without value processing etc. Function may return more fields than just the answers. @param string $tokenId Gems Token Id @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array Field => Value array
entailment
public function getRawTokenAnswerRows(array $filter, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $select = $this->getRawTokenAnswerRowsSelect($filter, $surveyId, $sourceSurveyId); //Now process the filters $lsSurveyTable = $this->_getSurveyTableName($sourceSurveyId); $tokenField = $lsSurveyTable . '.token'; if (is_array($filter)) { //first preprocess the tokens if (isset($filter['token'])) { foreach ((array) $filter['token'] as $key => $tokenId) { $token = $this->_getToken($tokenId); $filter[$tokenField][$key] = $token; } unset($filter['token']); } } // Prevent failure when survey no longer active try { $rows = $select->query()->fetchAll(\Zend_Db::FETCH_ASSOC); } catch (Exception $exc) { $rows = false; } $results = array(); //@@TODO: check if we really need this, or can just change the 'token' field to have the 'original' // this way other sources that don't perform changes on the token field don't have to loop // over this field. The survey(answer)model could possibly perform the translation for this source if ($rows) { $map = $this->_getFieldMap($sourceSurveyId); if (isset($filter[$tokenField])) { foreach ($rows as $values) { $token = $this->_getToken($values['token'], true); // Reverse map $results[$token] = $map->mapKeysToTitles($values); } return $results; } else { //@@TODO If we do the mapping in the select statement, maybe we can gain some performance here foreach ($rows as $values) { $results[] = $map->mapKeysToTitles($values); } return $results; } } return array(); }
Returns the answers of multiple tokens in simple raw nested array format, without value processing etc. Function may return more fields than just the answers. @param array $filter XXXXX @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return array Of nested Field => Value arrays indexed by tokenId
entailment
public function getRawTokenAnswerRowsCount(array $filter, $surveyId, $sourceSurveyId = null) { $select = $this->getRawTokenAnswerRowsSelect($filter, $surveyId, $sourceSurveyId); $p = new \Zend_Paginator_Adapter_DbSelect($select); $count = $p->getCountSelect()->query()->fetchColumn(); return $count; }
Returns the recordcount for a given filter @param array $filter filter array @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return int
entailment
public function getRawTokenAnswerRowsSelect(array $filter, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsSurveyTable = $this->_getSurveyTableName($sourceSurveyId); $lsTokenTable = $this->_getTokenTableName($sourceSurveyId); $tokenField = $lsSurveyTable . '.token'; $quotedTokenTable = $lsDb->quoteIdentifier($lsTokenTable . '.token'); $quotedSurveyTable = $lsDb->quoteIdentifier($lsSurveyTable . '.token'); $select = $lsDb->select(); $select->from($lsTokenTable, $this->_attributeMap) ->join($lsSurveyTable, $quotedTokenTable . ' = ' . $quotedSurveyTable); //Now process the filters if (is_array($filter)) { //first preprocess the tokens if (isset($filter['token'])) { foreach ((array) $filter['token'] as $key => $tokenId) { $token = $this->_getToken($tokenId); $filter[$tokenField][$key] = $token; } unset($filter['token']); } // now map the attributes to the right fields foreach ($this->_attributeMap as $name => $field) { if (isset($filter[$name])) { $filter[$field] = $filter[$name]; unset($filter[$name]); } } } // Add limit / offset to select and remove from filter $this->filterLimitOffset($filter, $select); foreach ($filter as $field => $values) { $field = $lsDb->quoteIdentifier($field); if (is_array($values)) { $select->where("$field IN (?)", array_values($values)); } else { $select->where("$field = ?", $values); } } if (\Gems_Tracker::$verbose) { \MUtil_Echo::r($select->__toString(), 'Select'); } return $select; }
Get the select object to use for RawTokenAnswerRows @param array $filter @param type $surveyId @param type $sourceSurveyId @return \Zend_Db_Select
entailment
public function getSurveyAnswerModel(\Gems_Tracker_Survey $survey, $language = null, $sourceSurveyId = null) { static $cache = array(); // working with 'real' cache produces out of memory error if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($survey->getSurveyId()); } $language = $this->_getLanguage($sourceSurveyId, $language); $cacheId = $sourceSurveyId . strtr($language, '-.', '__'); if (!array_key_exists($cacheId, $cache)) { $model = $this->tracker->getSurveyModel($survey, $this); $fieldMap = $this->_getFieldMap($sourceSurveyId, $language)->applyToModel($model); $cache[$cacheId] = $model; } return $cache[$cacheId]; }
Returns a model for the survey answers @param \Gems_Tracker_Survey $survey @param string $language Optional (ISO) language string @param string $sourceSurveyId Optional Survey Id used by source @return \MUtil_Model_ModelAbstract
entailment
public function getTokenInfo(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId, array $fields = null) { if (! $token->cacheHas(self::CACHE_TOKEN_INFO)) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsTokens = $this->_getTokenTableName($sourceSurveyId); $tokenId = $this->_getToken($token->getTokenId()); $sql = 'SELECT * FROM ' . $lsTokens . ' WHERE token = ? LIMIT 1'; try { $result = $this->getSourceDatabase()->fetchRow($sql, $tokenId); } catch (\Zend_Db_Statement_Exception $exception) { $this->logger->logError($exception, $this->request); $result = false; } $token->cacheSet(self::CACHE_TOKEN_INFO, $result); } else { $result = $token->cacheGet(self::CACHE_TOKEN_INFO); } if ($fields !== null) $result = array_intersect_key((array) $result, array_flip($fields)); return $result; }
Retrieve all fields stored in the token table, and store them in the tokencache @param \Gems_Tracker_Token $token @param type $surveyId @param type $sourceSurveyId @param array $fields @return type
entailment
public function getTokenUrl(\Gems_Tracker_Token $token, $language, $surveyId, $sourceSurveyId) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $tokenId = $this->_getToken($token->getTokenId()); if ($this->_isLanguage($sourceSurveyId, $language)) { $langUrl = '&lang=' . $language; } else { $langUrl = ''; } // mgzdev.erasmusmc.nl/incant/index.php?sid=1&token=o7l9_b8z2 $baseurl = $this->getBaseUrl(); return $baseurl . ('/' == substr($baseurl, -1) ? '' : '/') . 'index.php?sid=' . $sourceSurveyId . '&token=' . $tokenId . $langUrl; }
Returns the url that (should) start the survey for this token @param \Gems_Tracker_Token $token Gems token object @param string $language @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return string The url to start the survey
entailment
public function getValidDates(\Gems_Tracker_Token $token) { $now = new \MUtil_Date(); // For extra protection, we add valid from/to dates as needed instead of leaving them in GemsTracker only $tokenFrom = $token->getValidFrom(); $tokenUntil = $token->getValidUntil(); // Always set a date, so LimeSurvey will check the token $lsFrom = is_null($tokenFrom) ? new \MUtil_Date('1900-01-01') : $tokenFrom; if (!is_null($tokenUntil) && $tokenUntil->isEarlier($now)) { $lsUntil = $tokenUntil; } elseif (!is_null($tokenFrom)) { // To end of day. If entering via GemsTracker it will always be updated as long as the token is still valid $lsUntil = clone $now; $lsUntil->setTimeToDayEnd(); } else { // No valid from date, use same date as until $lsUntil = $lsFrom; } $values = [ 'validfrom' => $lsFrom->toString(self::LS_DB_DATETIME_FORMAT), 'validuntil' => $lsUntil->toString(self::LS_DB_DATETIME_FORMAT) ]; return $values; }
Get valid from/to dates to send to LimeSurvey depending on the dates of the token @param \Gems_Tracker_Token $token @return []
entailment
public function inSource(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null) { $tokenInfo = $this->getTokenInfo($token, $surveyId, $sourceSurveyId); return (boolean) $tokenInfo; }
Checks whether the token is in the source. @param \Gems_Tracker_Token $token Gems token object @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return boolean
entailment
public function isCompleted(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null) { $tokenInfo = $this->getTokenInfo($token, $surveyId, $sourceSurveyId); if (isset($tokenInfo['completed']) && $tokenInfo['completed'] != 'N') { return true; } else { return false; } }
Returns true if the survey was completed according to the source @param \Gems_Tracker_Token $token Gems token object @param int $surveyId Gems Survey Id @param $answers array Field => Value array, can be empty @param string $sourceSurveyId Optional Survey Id used by source @return boolean True if the token has completed
entailment
public function setRawTokenAnswers(\Gems_Tracker_Token $token, array $answers, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsTab = $this->_getSurveyTableName($sourceSurveyId); $lsTokenId = $this->_getToken($token->getTokenId()); // \MUtil_Echo::track($answers); $answers = $this->_getFieldMap($sourceSurveyId)->mapTitlesToKeys($answers); $answers = $this->_filterAnswersOnly($sourceSurveyId, $answers); // \MUtil_Echo::track($answers); if ($lsDb->fetchOne("SELECT token FROM $lsTab WHERE token = ?", $lsTokenId)) { $where = $lsDb->quoteInto("token = ?", $lsTokenId); return $lsDb->update($lsTab, $answers, $where); } else { $current = new \MUtil_Db_Expr_CurrentTimestamp(); $answers['token'] = $lsTokenId; $answers['startlanguage'] = $this->locale->getLanguage(); $answers['datestamp'] = $current; $answers['startdate'] = $current; $lsDb->insert($lsTab, $answers); return true; } }
Sets the answers passed on. @param \Gems_Tracker_Token $token Gems token object @param array $answers Field => Value array @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return true When answers changed
entailment
public function setTokenCompletionTime(\Gems_Tracker_Token $token, $completionTime, $surveyId, $sourceSurveyId = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsTabSurv = $this->_getSurveyTableName($sourceSurveyId); $lsTabTok = $this->_getTokenTableName($sourceSurveyId); $lsTokenId = $this->_getToken($token->getTokenId()); $where = $lsDb->quoteInto("token = ?", $lsTokenId); $current = new \MUtil_Db_Expr_CurrentTimestamp(); if ($completionTime instanceof \Zend_Date) { $answers['submitdate'] = $completionTime->toString(self::LS_DB_DATETIME_FORMAT); $tokenData['completed'] = $completionTime->toString(self::LS_DB_COMPLETION_FORMAT); } else { $answers['submitdate'] = null; $tokenData['completed'] = 'N'; } // Set for the survey if ($lsDb->fetchOne("SELECT token FROM $lsTabSurv WHERE token = ?", $lsTokenId)) { $lsDb->update($lsTabSurv, $answers, $where); } elseif ($completionTime instanceof \Zend_Date) { $answers['token'] = $lsTokenId; $answers['startlanguage'] = $this->locale->getLanguage(); $answers['datestamp'] = $current; $answers['startdate'] = $current; $lsDb->insert($lsTabSurv, $answers); } // Set for the token if ($lsDb->fetchOne("SELECT token FROM $lsTabTok WHERE token = ?", $lsTokenId)) { $lsDb->update($lsTabTok, $tokenData, $where); } elseif ($completionTime instanceof \Zend_Date) { $tokenData['token'] = $lsTokenId; $tokenData = $tokenData + $this->_fillAttributeMap($token); $lsDb->insert($lsTabTok, $tokenData); } $token->cacheReset(); }
Sets the completion time. @param \Gems_Tracker_Token $token Gems token object @param \Zend_Date|null $completionTime \Zend_Date or null @param int $surveyId Gems Survey Id (actually required) @param string $sourceSurveyId Optional Survey Id used by source
entailment
public function updateConsent(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null, $consentCode = null) { if (null === $sourceSurveyId) { $sourceSurveyId = $this->_getSid($surveyId); } $lsDb = $this->getSourceDatabase(); $lsTokens = $this->_getTokenTableName($sourceSurveyId); $tokenId = $this->_getToken($token->getTokenId()); if (null === $consentCode) { $consentCode = (string) $token->getConsentCode(); } $values[$this->_attributeMap['consentcode']] = $consentCode; if ($oldValues = $lsDb->fetchRow("SELECT * FROM $lsTokens WHERE token = ? LIMIT 1", $tokenId)) { if ($this->tracker->filterChangesOnly($oldValues, $values)) { if (\Gems_Tracker::$verbose) { $echo = ''; foreach ($values as $key => $val) { $echo .= $key . ': ' . $oldValues[$key] . ' => ' . $val . "\n"; } \MUtil_Echo::r($echo, "Updated limesurvey values for $tokenId"); } $result = $lsDb->update($lsTokens, $values, array('token = ?' => $tokenId)); if ($result) { //If we have changed something, invalidate the cache $token->cacheReset('tokenInfo'); } return $result; } } return 0; }
Updates the consent code of the the token in the source (if needed) @param \Gems_Tracker_Token $token @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @param string $consentCode Optional consent code, otherwise code from token is used. @return int 1 of the token was inserted or changed, 0 otherwise
entailment
protected function afterSave($changed) { if ($changed) { $this->accesslog->logChange($this->request, null, $this->formData); // Reload the current user data $user = $this->currentUser; $currentOrg = $user->getCurrentOrganizationId(); $this->loader->getUserLoader()->unsetCurrentUser(); $user = $this->loader->getUser($user->getLoginName(), $user->getBaseOrganizationId())->setAsCurrentUser(); $user->setCurrentOrganization($currentOrg); // In case locale has changed, set it in a cookie \Gems_Cookies::setLocale($this->formData['gsf_iso_lang'], $this->basepath); $this->addMessage($this->_('Saved your setup data', $this->formData['gsf_iso_lang'])); } else { $this->addMessage($this->_('No changes to save!')); } if ($this->cacheTags && ($this->cache instanceof \Zend_Cache_Core)) { $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, (array) $this->cacheTags); } }
Hook that allows actions when data was saved When not rerouted, the form will be populated afterwards @param int $changed The number of changed rows (0 or 1 usually, but can be more)
entailment
protected function createModel() { if (! $this->model instanceof \Gems_Model_StaffModel) { $this->model = $this->loader->getModels()->getStaffModel(false); $this->model->applyOwnAccountEdit(); } return $this->model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function hasHtmlOutput() { if ($this->currentUser->getUserId() == \Gems_User_UserLoader::SYSTEM_USER_ID) { $this->addMessage($this->getNotAllowedMessage()); return false; } return parent::hasHtmlOutput(); }
If the current user is the system user, present a message and don't allow to edit @return boolean
entailment
public function execute($roundId = null, $roundDescription = null) { $batch = $this->getBatch(); if ($batch->hasVariable('trackEngine')) { $trackEngine = $batch->getVariable('trackEngine'); if ($trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) { $model = $trackEngine->getRoundModel(true, 'delete'); $roundData['gro_id_round'] = $roundId; $roundData['gro_active'] = 0; $roundData = $model->save($roundData); $batch->addMessage(sprintf( $this->_('Deactivated round %s.'), ($roundDescription ? $roundDescription : $roundId) )); } } }
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
public function getTag() { if (null === $this->_tag) { $tag = $this->getOption('tag'); if (null !== $tag) { $this->removeOption('tag'); } else { $tag = 'span'; } $this->setTag($tag); return $tag; } return $this->_tag; }
Get HTML tag, if any, with which to surround tooltip @return string
entailment
public function getEscape() { if (null === $this->_escape) { if (null !== ($escape = $this->getOption('escape'))) { $this->setEscape($escape); $this->removeOption('escape'); } else { $this->setEscape(true); } } return $this->_escape; }
Get escape flag @return true
entailment
public function render($content) { $element = $this->getElement(); $view = $element->getView(); if (null === $view) { return $content; } $tooltip = $element->getAttrib('tooltip'); $tooltip = trim($tooltip); //$element->removeAttrib('tooltip'); if (empty($tooltip)) { return $content; } $view->headScript()->appendFile(\Zend_Controller_Front::getInstance()->getBaseUrl() . '/gems/js/jquery.cluetip.js'); $view->headLink()->appendStylesheet(\Zend_Controller_Front::getInstance()->getBaseUrl() . '/gems/js/jquery.cluetip.css'); $script = "$('" . $this->getTag() . ".tooltip').cluetip({ activation: 'click', sticky: 'true', closeText: '[X]', closePosition: 'title', width: 450, titleAttribute: 'tip', splitTitle: '|'}) $('#tabContainer').bind( 'tabsselect', function(event, ui) { $(document).trigger('hideCluetip'); });"; $view->jQuery()->addOnLoad($script); $separator = $this->getSeparator(); $placement = $this->getPlacement(); $class = $this->getClass(); $tag = $this->getTag(); $escape = $this->getEscape(); $options = $this->getOptions(); if ($escape) { $tooltip = $view->escape($tooltip); } $options['tag'] = $tag; $options['tip'] = str_replace('"', '\"', $tooltip); $decorator = new \Zend_Form_Decorator_HtmlTag($options); $tooltip = $decorator->render($this->getImg()) . $decorator->setOptions(array('class'=>'thetooltip', 'id'=>'tooltip-' . $this->getElement()->getAttrib('id')))->render($tooltip); switch ($placement) { case self::PREPEND: return $tooltip . $separator . $content; case self::APPEND: default: return $content . $separator . $tooltip; } /* Misschien later toch toevoegen */ $helper = $this->getHelper(); return $view->$helper($id, $content, $attribs); }
Render a tooltip @param string $content @return string
entailment
public function calcultateName($value, $isNew = false, $name = null, array $context = array()) { $output = array(); // Check all the fields for ($i = 1; $i <= $this->_fieldCount; $i++) { $field = 'gaf_filter_text' . $i; if (isset($context[$field], $this->_filters[$context[$field]]) && $context[$field] && $this->_filters[$context[$field]]) { $output[] = $this->_filters[$context[$field]]; } } if ($output) { return 'NOT (' . implode($this->_(' AND '), $output) . ')'; } else { return $this->_('empty filter'); } }
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 string
entailment
public function createModel($detailed, $action) { $defaultOrgId = null; if ($detailed) { // Make sure the user is loaded $user = $this->getSelectedUser(); if ($user) { if (! ($this->currentUser->hasPrivilege('pr.staff.see.all') || $this->currentUser->isAllowedOrganization($user->getBaseOrganizationId()))) { throw new \Gems_Exception($this->_('No access to page'), 403, null, sprintf( $this->_('You have no right to access users from the organization %s.'), $user->getBaseOrganization()->getName() )); } switch ($action) { case 'create': case 'show': case 'mail': break; default: if (! $user->inAllowedGroup()) { throw new \Gems_Exception($this->_('No access to page'), 403, null, sprintf( $this->_('In the %s group you have no right to change users in the %s group.'), $this->currentUser->getGroup()->getName(), $user->getGroup()->getName() )); } } } } // \MUtil_Model::$verbose = true; $model = $this->loader->getModels()->getStaffModel(! (('deactivate' === $action) || ('reactivate' === $action))); $model->applySettings($detailed, $action); return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
public function getDeactivateTitle() { $user = $this->getSelectedUser(); if ($user) { return sprintf($this->_('Deactivate staff member %s'), $user->getLoginName()); } return parent::getDeactivateTitle(); }
Helper function to get the title for the deactivate action. @return $string
entailment
public function getReactivateTitle() { $user = $this->getSelectedUser(); if ($user) { return sprintf($this->_('Reactivate staff member %s'), $user->getLoginName()); } return parent::getReactivateTitle(); }
Helper function to get the title for the reactivate action. @return $string
entailment
public function getSearchFilter($useRequest = true) { $filter = parent::getSearchFilter($useRequest); if (! (isset($filter['gsf_id_organization']) && $filter['gsf_id_organization'])) { $filter['gsf_id_organization'] = array_keys($this->currentUser->getAllowedOrganizations()); } return $filter; }
Get the filter to use with the model for searching including model sorts, etc.. @param boolean $useRequest Use the request as source (when false, the session is used) @return array or false
entailment
public function getShowTitle() { $user = $this->getSelectedUser(); if ($user) { return sprintf($this->_('Show staff member %s'), $user->getLoginName()); } return parent::getShowTitle(); }
Helper function to get the title for the show action. @return $string
entailment
public function mailAction() { if ($this->mailSnippets) { $params = $this->_processParameters($this->mailParameters); $this->addSnippets($this->mailSnippets, $params); } }
mail a staff member
entailment
public function resetAction() { if ($this->resetSnippets) { $params = $this->_processParameters($this->resetParameters); $this->addSnippets($this->resetSnippets, $params); } }
reset a password
entailment
public function reset2faAction() { $user = $this->getSelectedUser(); $user->clearTwoFactorKey(); $this->addMessage( sprintf($this->_('Two factor key cleared for user %s'), $user->getLoginName()), 'success'); $router = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $router->gotoRoute(['controller'=>'staff', 'action'=>'show'], null, false); }
reset two factor authentication
entailment
protected function addShowTableRows(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $this->_roundData = $bridge->getRow(); if ($this->trackEngine instanceof \Gems_Tracker_Engine_StepEngineAbstract) { $this->trackEngine->updateRoundModelToItem($model, $this->_roundData, $this->locale->getLanguage()); } $bridge->addItem('gro_id_track'); $bridge->addItem('gro_id_survey'); $bridge->addItem('gro_round_description'); $bridge->addItem('gro_id_order'); $bridge->addItem('gro_icon_file'); if ($model->has('ggp_name')) { $bridge->addItem('ggp_name'); } elseif ($model->has('gro_id_relationfield')) { $bridge->addItem('gro_id_relationfield'); } $bridge->addItem($model->get('valid_after', 'value')); $this->_addIf(array('gro_valid_after_source', 'gro_valid_after_id', 'gro_valid_after_field'), $bridge, $model); if ($model->has('gro_valid_after_length', 'label')) { $bridge->addItem(array($bridge->gro_valid_after_length, ' ', $bridge->gro_valid_after_unit), $model->get('gro_valid_after_length', 'label')); } $bridge->addItem($model->get('valid_for', 'value')); $this->_addIf(array('gro_valid_for_source', 'gro_valid_for_id', 'gro_valid_for_field'), $bridge, $model); if ($model->has('gro_valid_for_length', 'label')) { $bridge->addItem(array($bridge->gro_valid_for_length, ' ', $bridge->gro_valid_for_unit), $model->get('gro_valid_after_length', 'label')); } $bridge->addItem('condition_display'); $bridge->addItem('gro_active'); // Preven empty row when no changed events exist if ($label = $model->get('gro_changed_event', 'label')) { $bridge->addItem('gro_changed_event'); } $bridge->addItem('gro_code'); $bridge->addItem('org_specific_round'); if ($this->_roundData['org_specific_round']) { $bridge->addItem('organizations'); } $menuItem = $this->menu->find(array( $this->request->getControllerKey() => $this->request->getControllerName(), $this->request->getActionKey() => 'edit')); if ($menuItem) { $bridge->tbody()->onclick = array('location.href=\'', $menuItem->toHRefAttribute($this->request), '\';'); } }
Adds rows from the model to the bridge that creates the browse table. Overrule this function to add different columns to the browse table, without having to recode the core table building code. @param \MUtil_Model_Bridge_VerticalTableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
public function execute($sourceId = null, $sourceSurveyId = null, $surveyId = null, $userId = null) { $batch = $this->getBatch(); $source = $this->loader->getTracker()->getSource($sourceId); if (null === $userId) { $userId = $this->loader->getCurrentUser()->getUserId(); } $messages = $source->checkSurvey($sourceSurveyId, $surveyId, $userId); $batch->addToCounter('checkedSurveys'); $batch->addToCounter('changedSurveys', $messages ? 1 : 0); $batch->setMessage('changedSurveys', sprintf( $this->_('%d of %d surveys changed.'), $batch->getCounter('changedSurveys'), $batch->getCounter('checkedSurveys'))); if ($messages) { foreach ((array) $messages as $message) { $batch->addMessage($message); } } }
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
public function getActiveOrganizationId() { $request = $this->getRequest(); if ($request->isPost()) { return $request->getParam($this->organizationFieldName); } }
Get the organization id that has been currently entered @return int
entailment
public function getCurrentOrganizationId() { $userLoader = $this->loader->getUserLoader(); // Url determines organization first. if ($orgId = $userLoader->getOrganizationIdByUrl()) { $this->_organizationFromUrl = true; $userLoader->getCurrentUser()->setCurrentOrganization($orgId); return $orgId; } $request = $this->getRequest(); if ($request->isPost() && ($orgId = $request->getParam($this->organizationFieldName))) { return $orgId; } return $userLoader->getCurrentUser()->getCurrentOrganizationId(); }
Returns the organization id that should currently be used for this form. @return int Returns the current organization id, if any
entailment
public function getOrganizationElement() { $element = $this->getElement($this->organizationFieldName); $orgId = $this->getCurrentOrganizationId(); $orgs = $this->getLoginOrganizations(); $hidden = $this->_organizationFromUrl || (count($orgs) < 2); if ($hidden) { if (! $element instanceof \Zend_Form_Element_Hidden) { $element = new \Zend_Form_Element_Hidden($this->organizationFieldName); $this->addElement($element); } if (! $this->_organizationFromUrl) { $orgIds = array_keys($orgs); $orgId = reset($orgIds); } $element->setValue($orgId); } elseif (! $element instanceof \Zend_Form_Element_Select) { $element = $this->createElement('select', $this->organizationFieldName); $element->setLabel($this->translate->_('Organization')); $element->setRegisterInArrayValidator(true); $element->setRequired(true); $element->setMultiOptions($orgs); if ($this->organizationMaxLines > 1) { $element->setAttrib('size', min(count($orgs) + 1, $this->organizationMaxLines)); } $this->addElement($element); $element->setValue($orgId); } return $element; }
Returns/sets an element for determining / selecting the organization. @return \Zend_Form_Element_Xhtml
entailment
public function getUser() { if (! $this->_user) { $request = $this->getRequest(); $this->_user = $this->loader->getUser($request->getParam($this->usernameFieldName), $request->getParam($this->organizationFieldName)); } return $this->_user; }
Returns a user @return \Gems_User_User
entailment
public function getUserNameElement() { $element = $this->getElement($this->usernameFieldName); if (! $element) { // Veld inlognaam $element = $this->createElement('text', $this->usernameFieldName); $element->setLabel($this->translate->_('Username')); $element->setAttrib('size', 40); $element->setRequired(true); $this->addElement($element); } return $element; }
Returns/sets a login name element. @return \Zend_Form_Element_Text
entailment
public function isValid($data, $disableTranslateValidators = null) { $this->_user = $this->loader->getUser( (isset($data[$this->usernameFieldName]) ? $data[$this->usernameFieldName] : null), (isset($data[$this->organizationFieldName]) ? $data[$this->organizationFieldName] : '') ); return parent::isValid($data, $disableTranslateValidators); }
Validate the form As it is better for translation utilities to set the labels etc. translated, the MUtil default is to disable translation. However, this also disables the translation of validation messages, which we cannot set translated. The MUtil form is extended so it can make this switch. @param array $data @param boolean $disableTranslateValidators Extra switch @return boolean
entailment
public function wasSubmitted() { // If form was not (yet) populated, we can not use isChecked() so do this manually $request = $this->getRequest(); if ($request->isPost() && strlen(trim($request->getPost($this->_submitFieldName)))) { return true; } else { return false; } }
True when this form was submitted. @return boolean
entailment
public function addTo($newTo, $newToName = '') { if (is_array($newTo)) { $this->to = array_merge($newTo, $this->to); } else { if (empty($newToName)) { $this->to[] = $newTo; } else { $this->to[$newToName] = $newTo; } } }
Add a To field
entailment
public function getMailFields($marked=true) { if ($marked) { if (! $this->markedMailFields) { $this->markedMailFields = $this->markMailFields($this->mailFields); } return $this->markedMailFields; } else { return $this->mailFields; } }
Return the mailFields @param boolean $marked Return the mailfields with their markers @return Array List of the mailfields and their values
entailment
public function applyFields($text) { $mailKeys = array_keys($this->getMailFields()); return str_replace($mailKeys, $this->mailFields, $text); }
Replace the mailkeys with the mailfields in given text @param string $text The text to apply the replacment to @return string The text with replaced mailfields
entailment
public function getLanguage() { if ($this->project->getEmailMultiLanguage() && $this->language) { return $this->language; } else { return $this->project->getLocaleDefault(); } }
Get the prefered template language @return string language code
entailment
public function getPresetTargetData() { $targetData = array(); if ($this->to) { $fullDisplay = array(); foreach($this->to as $name=>$address) { $fullTo = ''; if (!is_numeric($name)) { $fullTo .= $name . ' '; } $fullTo .= '<' . $address . '>'; $fullDisplay[] = $fullTo; } $targetData['to'] = join(', ', $fullDisplay); } if ($this->language) { $allLanguages = $this->util->getLocalized()->getLanguages(); $targetData['prefered_language'] = $allLanguages[$this->language]; } return $targetData; }
Get specific data set in the mailer @return Array
entailment
public function getTemplate($templateId, $language=null) { if (!$language) { $language = $this->getLanguage(); } $select = $this->db->select(); $select->from('gems__comm_template_translations') ->where('gctt_id_template = ?', $templateId) ->where('gctt_lang = ?', $language); $template = $this->db->fetchRow($select); if ($template && !empty($template['gctt_subject'])) { return $template; } if ($language !== $this->project->getLocaleDefault()) { $language = $this->project->getLocaleDefault(); $select = $this->db->select(); $select->from('gems__comm_template_translations') ->where('gctt_id_template = ?', $templateId) ->where('gctt_lang = ?', $language); $template = $this->db->fetchRow($select); if ($template && !empty($template['gctt_subject'])) { return $template; } } $select = $this->db->select(); $select->from('gems__comm_template_translations') ->where('gctt_id_template = ?', $templateId) ->where('gctt_subject <> ""') ->where('gctt_body <> ""'); $template = $this->db->fetchRow($select); if ($template && !empty($template['gctt_subject'])) { return $template; } else { return false; } }
get a specific template. If the selected translation exists, get that translation Else if the selected translation isn't the default, select the default translation Else select the first not empty translation Else return false @param integer $templateId Template ID
entailment
protected function loadMailFields() { if ($this->organization) { $this->mailFields = array_merge($this->project->getMailFields(), $this->organization->getMailFields()); } else { $this->mailFields = $this->project->getMailFields(); } }
Initialize the mailfields
entailment
protected function loadOrganization() { if (!$this->organizationId) { $this->loadOrganizationId(); } $this->organization = $this->loader->getOrganization($this->organizationId); }
Load the organization from the given organization id
entailment
public function markMailFields($mailFields) { $markedMailFields = \MUtil_Ra::braceKeys($mailFields, $this->mailFieldMarkers['start'], $this->mailFieldMarkers['end']); return $markedMailFields; }
Add specified markers to the mailfield keys @param Array $mailfields @return Array The marked mailfields
entailment
public function send() { $mail = $this->loader->getMail(); $mail->setFrom($this->from); $mail->addTo($this->to, '', $this->bounceCheck()); if (isset($this->project->email['bcc'])) { $mail->addBcc($this->project->email['bcc']); } $mail->setSubject($this->applyFields($this->subject)); $mail->setTemplateStyle($this->getTemplateStyle()); if ($this->bodyBb) { $mail->setBodyBBCode($this->applyFields($this->bodyBb)); } elseif ($this->bodyHtml) { $mail->setBodyHtml($this->applyFields($this->bodyHtml)); } elseif ($this->bodyText) { $mail->setBodyText($this->applyFields($this->bodyText)); } $this->beforeMail(); $mail->send(); $this->afterMail(); }
Send the mail
entailment
public function setFrom($newFrom) { $this->from = $newFrom; $this->mailFields['from'] = $this->mailFields['reply_to'] = $newFrom; }
set the from field
entailment
public function setTemplate($templateId) { if ($template = $this->getTemplate($templateId)) { $this->subject = $template['gctt_subject']; $this->bodyBb = $template['gctt_body']; $this->setTemplateId($templateId); } }
set a specific template as subject/body @param integer $templateId Template ID
entailment
public function setTemplateByCode($templateCode) { $select = $this->loader->getModels()->getCommTemplateModel()->getSelect(); $select->where('gct_code = ?', $templateCode); $template = $this->db->fetchRow($select); if ($template) { $this->setTemplate($template['gct_id_template']); return true; } else { return false; } }
Use the Mail template code to select and set the template @param string mail
entailment
public function setTo($newTo, $newToName = '') { if (is_array($newTo)) { $this->to = $newTo; } else { $this->to = array(); if (empty($newToName)) { $this->to[] = $newTo; } else { $this->to[$newToName] = $newTo; } } }
set the To field, overwriting earlier settings completely @param [type] $to [description]
entailment
protected function getAutoSearchElements(array $data) { $elements = []; $this->addTrackSelect($elements, $data, 'gtf_id_track'); $this->addOrgSelect($elements, $data, 'gr2t_id_organization'); $elements[] = null; $this->addPeriodSelect($elements, $data); $elements[] = null; 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 _addJoinTables() { $this->addTable('gems__respondents', array('gec_id_user' => 'grs_id_user')); if ($this->has('gec_id_organization')) { $this->addTable( 'gems__organizations', array('gec_id_organization' => 'gor_id_organization'), 'gor', false ); } if ($this->has('gec_id_attended_by')) { $this->addLeftTable( 'gems__agenda_staff', array('gec_id_attended_by' => 'gas_id_staff'), 'gas', false ); } }
Add the join tables instead of lookup tables.
entailment
public function applyBrowseSettings() { $this->_addJoinTables(); $this->resetOrder(); $agenda = $this->loader->getAgenda(); $this->setIfExists('gec_status', 'label', $this->_('Status'), 'multiOptions', $agenda->getEpisodeStatusCodes()); $this->setIfExists('gec_startdate', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy', 'description', $this->_('dd-mm-yyyy')); $this->setIfExists('gec_enddate', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy', 'description', $this->_('dd-mm-yyyy')); $this->setIfExists('gec_subject', 'label', $this->_('Subject')); $this->setIfExists('gec_diagnosis', 'label', $this->_('Diagnosis')); $this->set('appointment_count', 'label', $this->_('Appointments')); $jsonType = new JsonData(10); $jsonType->apply($this, 'gec_diagnosis_data', false); $jsonType->apply($this, 'gec_extra_data', false); $this->refreshGroupSettings(); return $this; }
Set those settings needed for the browse display @return \Gems_Model_AppointmentModel
entailment
public function applyDetailSettings() { $this->resetOrder(); $agenda = $this->loader->getAgenda(); $dbLookup = $this->util->getDbLookup(); $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $this->setIfExists('gec_id_organization', 'label', $this->_('Organization'), 'elementClass', 'Exhibitor', 'multiOptions', $empty + $dbLookup->getOrganizations()); $this->setIfExists('gec_status', 'label', $this->_('Status'), 'multiOptions', $agenda->getEpisodeStatusCodes()); $this->setIfExists('gec_startdate', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy', 'description', $this->_('dd-mm-yyyy')); $this->setIfExists('gec_enddate', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy', 'description', $this->_('dd-mm-yyyy')); $this->setIfExists('gec_id_attended_by', 'label', $this->_('With'), 'multiOptions', $empty + $agenda->getHealthcareStaff()); $this->setIfExists('gec_subject', 'label', $this->_('Subject')); $this->setIfExists('gec_comment', 'label', $this->_('Comment')); $this->setIfExists('gec_diagnosis', 'label', $this->_('Diagnosis')); $this->set('appointment_count', 'label', $this->_('Appointments')); $jsonType = new JsonData(10); $jsonType->apply($this, 'gec_diagnosis_data', true); $jsonType->apply($this, 'gec_extra_data', true); if ($this->currentUser->hasPrivilege('pr.episodes.rawdata')) { $this->setIfExists('gec_diagnosis_data', 'label', $this->_('Diagnosis data')); $this->setIfExists('gec_extra_data', 'label', $this->_('Extra data')); } $this->refreshGroupSettings(); return $this; }
Set those settings needed for the detailed display @return \Gems_Model_AppointmentModel
entailment
public function applyEditSettings($orgId, $respId) { $this->applyDetailSettings(); $agenda = $this->loader->getAgenda(); $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $this->setIfExists('gec_id_user', 'default', $respId, 'elementClass', 'Hidden'); $this->setIfExists('gec_id_organization', 'default', $orgId, 'elementClass', 'Hidden'); $this->setIfExists('gec_status', 'required', true); $this->setIfExists('gec_startdate', 'default', new \MUtil_Date(), 'elementClass', 'Date', 'required', true); $this->setIfExists('gec_enddate', 'elementClass', 'Date'); $this->setIfExists('gec_subject', 'required', true); $this->setIfExists('gec_comment', 'elementClass', 'Textarea', 'rows', 5); $this->setIfExists('gec_diagnosis', 'required', true); $this->set('appointment_count', 'elementClass', 'Exhibitor'); if ($this->currentUser->hasPrivilege('pr.episodes.rawdata')) { $this->setIfExists('gec_diagnosis_data', 'elementClass', 'Exhibitor'); $this->setIfExists('gec_extra_data', 'elementClass', 'Exhibitor'); } return $this; }
Set those values needed for editing @param int $orgId The id of the current organization @param int $respId The id of the current respondent @return \Gems_Model_AppointmentModel
entailment
public function _($text, $locale = null) { if (! isset($this->request)) { // Locale is fixed by request. $this->setException(new \Gems_Exception_Coding('Requested translation before request was made available.')); } return $this->translateAdapter->_($text, $locale); }
Copy from \Zend_Translate_Adapter Translates the given string returns the translation @param string $text Translation string @param string|\Zend_Locale $locale (optional) Locale/Language to use, identical with locale identifier, @see \Zend_Locale for more information @return string
entailment
protected function _checkParameters(array $params, array $posts) { foreach ($params as $key => $value) { $rest = strpbrk($key, '<>=%&"\''); if (false !== $rest) { $this->setError( $this->_('Illegal request parameter'), 422, sprintf($this->_('Illegal character %s in parameter name.'), $rest[0]), true ); } if ($value && (!is_object($value)) && (!array_key_exists($key, $posts))) { foreach ((array) $value as $val) { // Quickfix // If $val is an array preg_match fails. This is true for export options // If the elements of the array should be checked too, feel free to do so if (is_array($val)) { continue; } // Find not allowed words after <>%& $checks = ['iframe', 'img', 'script']; $pattern = '/([<>%&])(' . join('|', $checks) . ')/i'; if (preg_match($pattern, $val, $matches)) { $this->setError( $this->_('Illegal request parameter'), 422, sprintf($this->_('Illegal parameter value containing the text "%s" after a %s character.'), $matches[2], $matches[1]), true ); } } } } }
Check all parameters for security violations All variables are checked for name contents: the <>=%&"' characters should not occur in the name. The non-post variables are checked for value contents as well: after a <>&% there should not occur a frame, script or img stext. @param array $params @param array $posts
entailment
protected function _copyVariables($object) { // Store for _updateVariable $this->_copyDestinations[] = $object; // Extra object $object->escort = $this; foreach ($this->getContainer() as $key => $value) { // Prevent self referencing if ($value !== $object) { // \MUtil_Echo::r(get_class($value), $key); // echo get_class($value) . ' => ' . $key . '<br/>'; $object->$key = $value; } } // viewRenderer is not in the container so has to be copied separately foreach (get_object_vars($this) as $name => $value) { if ('_' != $name[0]) { // \MUtil_Echo::r(get_class($value), $key); $object->$name = $value; } } }
Function to maintain uniformity of access to variables from the bootstrap object. Copies all variables to the target object. @param Object $object An object who gets all variables from this object. @return void
entailment
protected function _initProject() { $projectArray = $this->includeFile(APPLICATION_PATH . '/configs/project'); if ($projectArray instanceof \Gems_Project_ProjectSettings) { $project = $projectArray; } else { $project = $this->createProjectClass('Project_ProjectSettings', $projectArray); } return $project; }
Initialize the GEMS project component. The project component contains information about this project that are not Zend specific. For example: -- the super administrator, -- the project name, version and description, -- locales used, -- css and image directories used. This is the place for you to store any project specific data that should not be in the code. I.e. if you make a controllor that needs a setting to work, then put the setting in this settings file. Use $this->project to access afterwards @return \Gems_Project_ProjectSettings
entailment
protected function _initLogger() { $this->bootstrap('project'); // Make sure the project object is available $logger = \Gems_Log::getLogger(); $logPath = GEMS_ROOT_DIR . '/var/logs'; try { $writer = new \Zend_Log_Writer_Stream($logPath . '/errors.log'); } catch (Exception $exc) { try { // Try to solve the problem, otherwise fail heroically \MUtil_File::ensureDir($logPath); $writer = new \Zend_Log_Writer_Stream($logPath . '/errors.log'); } catch (Exception $exc) { $this->bootstrap(array('locale', 'translate')); die(str_replace(GEMS_ROOT_DIR . '/', '', sprintf( $this->translateAdapter->_('Path %s not writable') . "\n%s\n", $logPath, $exc->getMessage() ))); } } $filter = new \Zend_Log_Filter_Priority($this->project->getLogLevel()); $writer->addFilter($filter); $logger->addWriter($writer); // OPTIONAL STARTY OF FIREBUG LOGGING. if ($this->_startFirebird) { $logger->addWriter(new \Zend_Log_Writer_Firebug()); //We do not add the logLevel here, as the firebug window is intended for use by //developers only and it is only written to the active users' own screen. } \Zend_Registry::set('logger', $logger); return $logger; }
Initialize the logger @return \Gems_Log
entailment
protected function _initCache() { $this->bootstrap('project'); $useCache = $this->getResource('project')->getCache(); $cache = null; $exists = false; $cachePrefix = GEMS_PROJECT_NAME . '_'; // Check if APC extension is loaded and enabled if (\MUtil_Console::isConsole() && !ini_get('apc.enable_cli') && $useCache === 'apc') { // To keep the rest readable, we just fall back to File when apc is disabled on cli $useCache = "File"; } if ($useCache === 'apc' && extension_loaded('apc') && ini_get('apc.enabled')) { //Add path to the prefix as APC is a SHARED cache $cachePrefix .= md5(APPLICATION_PATH); $cacheBackendOptions = array('cache_id_prefix' => $cachePrefix); $cacheBackend = new \Gems\Cache\Backend\Apc($cacheBackendOptions); $exists = true; } else { $cacheBackend = 'File'; $cacheDir = GEMS_ROOT_DIR . "/var/cache/"; $cacheBackendOptions = array('cache_dir' => $cacheDir); if (!file_exists($cacheDir)) { if (@mkdir($cacheDir, 0777, true)) { $exists = true; } } else { $exists = true; } } if ($exists && $useCache <> 'none') { /** * automatic_cleaning_factor disables automatic cleaning of the cache and should get rid of * random delays on heavy traffic sites with File cache. Apc does * not support automatic cleaning. */ $cacheFrontendOptions = array('automatic_serialization' => true, 'cache_id_prefix' => $cachePrefix, 'automatic_cleaning_factor' => 0); $cache = \Zend_Cache::factory('Core', $cacheBackend, $cacheFrontendOptions, $cacheBackendOptions); } else { $cache = \Zend_Cache::factory('Core', 'Static', array('caching' => false), array('disable_caching' => true)); } \Zend_Db_Table_Abstract::setDefaultMetadataCache($cache); \Zend_Translate::setCache($cache); \Zend_Locale::setCache($cache); return $cache; }
Create a default file cache for the Translate and DB adapters to speed up execution @return \Zend_Cache_Core
entailment
protected function _initDb() { // DATABASE CONNECTION $resource = $this->getPluginResource('db'); if (! $resource) { // Do not throw error here. Error is throw in frontDispatchLoopStartup() // and no, you should not try to access the database in any earlier // code anyway. // // You are free to change this, but then you get an ugly error message on // the screen, while this way the ErrorController is used. return null; } $db = $resource->getDbAdapter(); // Firebug if ($this->_startFirebird) { $profiler = new \Zend_Db_Profiler_Firebug(GEMS_PROJECT_NAME); $profiler->setEnabled(true); $db->setProfiler($profiler); } \Zend_Db_Table::setDefaultAdapter($db); \Zend_Registry::set('db', $db); return $db; }
Initialize the database. Use $this->db to access afterwards @return \Zend_Db
entailment
protected function _initLoader() { $loader = $this->createProjectClass('Loader', $this->getContainer(), $this->_loaderDirs); \MUtil_Model::setSource($loader, true); return $loader; }
Initialize the Project or Gems loader. Use $this->loader to access afterwards @return \Gems_Loader
entailment
protected function _initAccesslog() { $this->bootstrap(array('cache', 'db', 'loader')); $accesslog = $this->createProjectClass('AccessLog', $this->cache, $this->db, $this->loader); return $accesslog; }
Initialize the access log. Use $this->accesslog to access afterwards @return \Gems_AccessLog
entailment
protected function _initAcl() { $this->bootstrap(array('db', 'loader', 'logger')); $acl = $this->getLoader()->getRoles($this); return $acl->getAcl(); }
Initialize the database. Use $this->acl to access afterwards @return \MUtil_Acl
entailment
protected function _initSession() { $this->bootstrap('project'); // Make sure the project is available $session = new \Zend_Session_Namespace('gems.' . GEMS_PROJECT_NAME . '.session'); $idleTimeout = $this->project->getSessionTimeOut(); $session->setExpirationSeconds($idleTimeout); if (! isset($session->user_role)) { $session->user_role = 'nologin'; } // Since userloading can clear the session, we put stuff that should remain (like redirect info) // in a different namespace that we call a 'static session', use getStaticSession to access. $this->staticSession = new \Zend_Session_Namespace('gems.' . GEMS_PROJECT_NAME . '.sessionStatic'); return $session; }
Initialize the Gems session. The session contains information on the registered user from @see $this->loadLoginInfo($username) This includes: -- user_id -- user_login -- user_name -- user_role -- user_locale -- user_organization_id Use $this->session to access afterwards @deprecated since 1.5 @return \Zend_Session_Namespace
entailment
protected function _initLocale() { $this->bootstrap(array('project', 'session')); // Get the choosen language if (isset($this->session->user_locale)) { $localeId = $this->session->user_locale; // \MUtil_Echo::r('sess: ' . $localeId); } else { if (isset($this->project->locale, $this->project->locale['default'])) { // As set in project $localeId = $this->project->locale['default']; // \MUtil_Echo::r('def: ' . $localeId); } elseif (isset($this->project->locales)) { // First of the locales array. $localeId = reset($this->project->locales); // \MUtil_Echo::r('locales: ' . $localeId); } else { // Default. $localeId = 'en'; } $this->session->user_locale = $localeId; } $locale = new \Zend_Locale($localeId); \Zend_Registry::set('Zend_Locale', $locale); return $locale; }
Initialize the locale. We use this function instead of the standard application.ini setting to simplify overruling the settings. Also Firefox tends to overrule the locale settings. You can overrule this function to specify your own project translation method / file. Use $this->locale to access afterwards @return \Zend_Locale
entailment
protected function _initOpenRosa() { $this->bootstrap(array('loader', 'translate')); if ($this->getOption('useOpenRosa')) { // First handle dependencies $this->bootstrap(array('db', 'loader', 'util')); $this->getLoader()->addPrefixPath('OpenRosa', GEMS_LIBRARY_DIR . '/classes/OpenRosa', true); /** * Add Source for OpenRosa */ $tracker = $this->loader->getTracker(); $tracker->addSourceClasses(array('OpenRosa'=>'OpenRosa form')); } }
Initialize the OpenRosa survey source
entailment