sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function hasHtmlOutput()
{
if ($this->user && $this->user->isTwoFactorRequired($this->_getIp())) {
if (! $this->user->hasTwoFactor()) {
$this->addMessage($this->_('Two factor authentication is required to login from this location!'));
$this->loadForm();
$this->addCancelButton();
return true;
}
parent::hasHtmlOutput();
return ! $this->_result;
}
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 |
protected function onInValid()
{
// We disable this standard error message as we are not changing anything here
//$this->addMessage(sprintf($this->_('Input error! Changes to %s not saved!'), $this->getTopic()));
if ($this->_csrf) {
if ($this->_csrf->getMessages()) {
$this->addMessage($this->_('The form was open for too long or was opened in multiple windows.'));
}
}
} | Hook that allows actions when the input is invalid
When not rerouted, the form will be populated afterwards | entailment |
public function createModel($detailed, $action)
{
$select = $this->getSelect();
// \MUtil_Model::$verbose = true;
$model = new \MUtil_Model_SelectModel($select, 'summary');
// Make sure of filter and sort for these fields
$model->set('gro_id_order');
$model->set('gto_id_track');
$model->set('gto_id_organization');
$model->resetOrder();
$model->set('gro_round_description', 'label', $this->_('Round'));
$model->set('gsu_survey_name', 'label', $this->_('Survey'));
$model->set('answered', 'label', $this->_('Answered'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
$model->set('missed', 'label', $this->_('Missed'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
$model->set('open', 'label', $this->_('Open'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
$model->set('total', 'label', $this->_('Total'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
// $model->set('future', 'label', $this->_('Future'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
// $model->set('unknown', 'label', $this->_('Unknown'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
// $model->set('is', 'label', ' ', 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
// $model->set('success', 'label', $this->_('Success'), 'tdClass', 'centerAlign', 'thClass', 'centerAlign');
// $model->set('removed', 'label', $this->_('Removed'), 'tdClass', 'deleted centerAlign',
// 'thClass', 'centerAlign');
$model->set('filler', 'label', $this->_('Filler'));
$filter = $this->getSearchFilter($action !== 'export');
if (! (isset($filter['gto_id_organization']) && $filter['gto_id_organization'])) {
$model->addFilter(array('gto_id_organization' => $this->currentUser->getRespondentOrgFilter()));
}
if (isset($filter['gto_id_track']) && $filter['gto_id_track']) {
// Add the period filter
if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
$select->joinInner('gems__respondent2track', 'gto_id_respondent_track = gr2t_id_respondent_track', array());
$model->addFilter(array($where));
}
} else {
$model->setFilter(array('1=0'));
$this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
}
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 getSelect()
{
$select = $this->db->select();
$fields['answered'] = new \Zend_Db_Expr("SUM(
CASE
WHEN grc_success = 1 AND gto_completion_time IS NOT NULL
THEN 1 ELSE 0 END
)");
$fields['missed'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1 AND
gto_completion_time IS NULL AND
gto_valid_until < CURRENT_TIMESTAMP AND
(gto_valid_from IS NOT NULL AND gto_valid_from <= CURRENT_TIMESTAMP)
THEN 1 ELSE 0 END
)');
$fields['open'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1 AND gto_completion_time IS NULL AND
gto_valid_from <= CURRENT_TIMESTAMP AND
(gto_valid_until >= CURRENT_TIMESTAMP OR gto_valid_until IS NULL)
THEN 1 ELSE 0 END
)');
$fields['total'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1 AND (
gto_completion_time IS NOT NULL OR
(gto_valid_from IS NOT NULL AND gto_valid_from <= CURRENT_TIMESTAMP)
)
THEN 1 ELSE 0 END
)');
/*
$fields['future'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1 AND gto_completion_time IS NULL AND gto_valid_from > CURRENT_TIMESTAMP
THEN 1 ELSE 0 END
)');
$fields['unknown'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1 AND gto_completion_time IS NULL AND gto_valid_from IS NULL
THEN 1 ELSE 0 END
)');
$fields['is'] = new \Zend_Db_Expr("'='");
$fields['success'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 1
THEN 1 ELSE 0 END
)');
$fields['removed'] = new \Zend_Db_Expr('SUM(
CASE
WHEN grc_success = 0
THEN 1 ELSE 0 END
)');
// */
$fields['filler'] = new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)');
$select = $this->db->select();
$select->from('gems__tokens', $fields)
->joinInner('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array())
->joinInner('gems__rounds', 'gto_id_round = gro_id_round',
array('gro_round_description', 'gro_id_survey'))
->joinInner('gems__surveys', 'gro_id_survey = gsu_id_survey',
array('gsu_survey_name'))
->joinInner('gems__groups', 'gsu_id_primary_group = ggp_id_group', array())
->joinLeft('gems__track_fields', 'gto_id_relationfield = gtf_id_field AND gtf_field_type = "relation"', array())
->group(array('gro_id_order', 'gro_round_description', 'gsu_survey_name', 'filler'));
$filter = $this->getSearchFilter();
if (array_key_exists('fillerfilter', $filter)) {
$select->having('filler = ?', $filter['fillerfilter']);
}
return $select;
} | Select creation function, allowes overruling in child classes
@return \Zend_Db_Select | entailment |
protected function addModelSettings(array &$settings)
{
$settings['elementClass'] = 'Date';
$settings['dateFormat'] = $this->getDateFormat();
$settings['storageFormat'] = $this->getStorageFormat();
$settings['type'] = $this->type;
} | Add the model settings like the elementClass for this field.
elementClass is overwritten when this field is read only, unless you override it again in getDataModelSettings()
@param array $settings The settings set so far | entailment |
public function calculateFieldInfo($currentValue, array $fieldData)
{
if ((null === $currentValue) ||
($currentValue instanceof \Zend_Db_Expr) ||
\MUtil_String::startsWith($currentValue, 'current_', true)) {
return null;
}
if ($currentValue instanceof \Zend_Date) {
$value = $currentValue->toString($this->zendDateTimeFormat);
} elseif ($currentValue instanceof DateTime) {
$value = date($this->phpDateTimeFormat, $currentValue->getTimestamp());
} else {
$value = $currentValue;
}
if ($currentValue) {
return $value;
} else {
return null;
}
} | Calculation the field info display for this type
@param array $currentValue The current value
@param array $fieldData The other values loaded so far
@return mixed the new value | entailment |
public function calculateFieldValue($currentValue, array $fieldData, array $trackData)
{
$calcUsing = $this->getCalculationFields($fieldData);
if ($calcUsing) {
$agenda = $this->loader->getAgenda();
// Get the used fields with values
foreach (array_filter($calcUsing) as $value) {
$appointment = $agenda->getAppointment($value);
if ($appointment->exists) {
return $appointment->getAdmissionTime();
}
}
}
if ($currentValue instanceof \MUtil_Date) {
return $currentValue;
}
if ($currentValue) {
return \MUtil_Date::ifDate($currentValue, $this->allowedDateFormats);
}
return $currentValue;
} | Calculate the field value using the current values
@param array $currentValue The current value
@param array $fieldData The other known field values
@param array $trackData The currently available track data (track id may be empty)
@return mixed the new value | entailment |
public function onFieldDataLoad($currentValue, array $fieldData)
{
if (empty($currentValue)) {
return null;
}
return new \MUtil_Date($currentValue, $this->getStorageFormat());
} | Calculate the field value using the current values
@param array $currentValue The current value
@param array $fieldData The other values loaded so far
@return mixed the new value | entailment |
public function onFieldDataSave($currentValue, array $fieldData)
{
if ((null === $currentValue) ||
($currentValue instanceof \Zend_Db_Expr) ||
\MUtil_String::startsWith($currentValue, 'current_', true)) {
return $currentValue;
}
$saveFormat = $this->getStorageFormat();
if ($currentValue instanceof \Zend_Date) {
return $currentValue->toString($saveFormat);
} else {
$displayFormat = $this->getDateFormat();
$saveDate = \MUtil_Date::ifDate($currentValue, array($displayFormat, $saveFormat, \Gems_Tracker::DB_DATETIME_FORMAT));
if ($saveDate instanceof \Zend_Date) {
return $saveDate->toString($saveFormat);
}
}
return (string) $currentValue;
} | Converting the field value when saving to a respondent track
@param array $currentValue The current value
@param array $fieldData The other values loaded so far
@return mixed the new value | entailment |
public function execute($respTrackData = null, $userId = null)
{
$batch = $this->getBatch();
$tracker = $this->loader->getTracker();
$respTrack = $tracker->getRespondentTrack($respTrackData);
$i = $batch->addToCounter('checkedRespondentTracks');
if ($result = $respTrack->checkTrackTokens($userId)) {
$a = $batch->addToCounter('tokenDateCauses');
$b = $batch->addToCounter('tokenDateChanges', $result);
$batch->setMessage('tokenDateChanges',
sprintf($this->_('%2$d token date changes in %1$d tracks.'), $a, $b)
);
}
$batch->setMessage('checkedRespondentTracks', sprintf($this->_('Checked %d tracks.'), $i));
} | 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 getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
if ($this->organizationField) {
$user = $this->loader->getCurrentUser();
if ($this->respondentOrganizations) {
$availableOrganizations = $this->util->getDbLookup()->getOrganizationsWithRespondents();
} else {
$availableOrganizations = $this->util->getDbLookup()->getActiveOrganizations();
}
if ($user->hasPrivilege('pr.staff.see.all')) {
// Select organization
$options = $availableOrganizations;
} else {
$options = array_intersect($availableOrganizations, $user->getAllowedOrganizations());
}
if ($options) {
$elements[] = $this->_createSelectElement(
$this->organizationField,
$options,
$this->_('(all organizations)')
);
}
}
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 |
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if ( ! $request->headers->has($this->header)) {
$request->headers->set($this->header, $this->generator->generate());
}
$response = $this->app->handle($request, $type, $catch);
if (null !== $this->responseHeader) {
$response->headers->set($this->responseHeader, $request->headers->get($this->header));
}
return $response;
} | {@inheritDoc} | entailment |
protected function getSurveySelectElements(array $data)
{
$dbLookup = $this->util->getDbLookup();
// get the current selections
$roundDescr = isset($data['gto_round_description']) ? $data['gto_round_description'] : null;
$surveyId = isset($data['gto_id_survey']) ? $data['gto_id_survey'] : null;
$trackId = isset($data['gto_id_track']) ? $data['gto_id_track'] : null;
// Get the selection data
$rounds = $dbLookup->getRoundsForExport($trackId, $surveyId);
$surveys = $dbLookup->getSurveysForExport($trackId, $roundDescr);
if ($surveyId) {
$tracks = $this->util->getTrackData()->getTracksBySurvey($surveyId);
} else {
$tracks = $this->util->getTrackData()->getTracksForOrgs($this->currentUser->getRespondentOrganizations());
}
$elements['gto_id_survey'] = $this->_createSelectElement(
'gto_id_survey',
$surveys,
$this->_('(select a survey)')
);
$elements['gto_id_track'] = $this->_createSelectElement(
'gto_id_track',
$tracks,
$this->_('(select a track)')
);
$elements['gto_round_description'] = $this->_createSelectElement(
'gto_round_description',
[parent::NoRound => $this->_('No round description')] + $rounds,
$this->_('(select a round)')
);
foreach ($elements as $element) {
if ($element instanceof \Zend_Form_Element_Multi) {
$element->setAttrib('onchange', 'this.form.submit();');
}
}
return $elements;
} | Returns start elements for auto search.
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 |
public function execute($text = null)
{
if ($this->cache instanceof \Zend_Cache_Core) {
$this->cache->clean(\Zend_Cache::CLEANING_MODE_ALL);
$this->getBatch()->addMessage($this->_('Cache cleaned'));
}
} | 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 _($text, $locale = null)
{
if (! $this->translateAdapter) {
$this->initTranslateable();
}
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 |
public function addLeftTable($table, array $joinFields, $fieldPrefix = null, $saveable = null)
{
parent::addLeftTable($table, $joinFields, $this->_checkSaveable($saveable, $fieldPrefix));
if ($fieldPrefix) {
\Gems_Model::setChangeFieldsByPrefix($this, $fieldPrefix);
}
return $this;
} | Add a table to the model with a left join
@param mixed $table The name of the table to join or a table object or an array(corr_name => tablename) or array(int => tablename, corr_name)
@param array $joinFields Array of source->dest primary keys for this join
@param string $fieldPrefix Prefix to use for change fields (date/userid), if $saveable empty sets it to true
@param mixed $saveable Will changes to this table be saved, true or a combination of SAVE_MODE constants
@return \Gems_Model_JoinModel | entailment |
public function plural($singular, $plural, $number, $locale = null)
{
if (! $this->translateAdapter) {
$this->initTranslateable();
}
$args = func_get_args();
return call_user_func_array(array($this->translateAdapter, 'plural'), $args);
} | Copy from \Zend_Translate_Adapter
Translates the given string using plural notations
Returns the translated string
@see \Zend_Locale
@param string $singular Singular translation string
@param string $plural Plural translation string
@param integer $number Number for detecting the correct plural
@param string|\Zend_Locale $locale (Optional) Locale/Language to use, identical with
locale identifier, @see \Zend_Locale for more information
@return string | entailment |
public function afterRegistry()
{
parent::afterRegistry();
if ($this->calSearchFilter instanceof AppointmentFilterInterface) {
if ($this->calSearchFilter instanceof AppointmentFilterInterface) {
$this->searchFilter = [
\MUtil_Model::SORT_DESC_PARAM => 'gec_startdate',
$this->calSearchFilter->getSqlEpisodeWhere(),
'limit' => 10,
];
// \MUtil_Echo::track($this->calSearchFilter->getSqlEpisodeWhere());
$this->bridgeMode = \MUtil_Model_Bridge_BridgeAbstract::MODE_ROWS;
$this->caption = $this->_('Example episodes');
$this->onEmpty = $this->_('No example episodes found');
} else {
$this->searchFilter = $this->calSearchFilter;
}
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function createModel()
{
if (! $this->model instanceof EpisodeOfCareModel) {
$this->model = $this->loader->getModels()->createEpisodeOfCareModel();
$this->model->applyBrowseSettings();
}
if ($this->calSearchFilter instanceof AppointmentFilterInterface) {
$this->model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'), 'order', 3);
\Gems_Model_RespondentModel::addNameToModel($this->model, $this->_('Name'));
$this->model->set('name', 'order', 6);
}
// \MUtil_Model::$verbose = true;
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$seq = $this->getHtmlSequence();
$seq->h2($this->_('Export to R'));
$seq->pre($this->_("Open the downloaded zip file when finished and open the .R file using:\n" .
" source(\"filename.R\", encoding=\"UTF-8\")\n" .
"or use File -> Reopen with Encoding... when using RStudio and choose UTF-8 and run all lines.\n" .
"\n" .
"Your data is now in a frame called 'data'"
));
return $seq;
} | 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 |
protected function addCheckFields()
{
$check = 1;
foreach ($this->checkFields as $label => &$value) {
if ($value instanceof \Zend_Form_Element) {
$element = $value;
} else {
if ($value) {
$element = new \Zend_Form_Element_Text('check_' . $check);
$element->setAllowEmpty(false);
$element->setLabel($label);
$validator = new \Zend_Validate_Identical($value);
$validator->setMessage(
sprintf($this->_('%s is not correct.'), $label),
\Zend_Validate_Identical::NOT_SAME
);
$element->addValidator($validator);
$value = $element;
$check++;
} else {
// Nothing to check for
unset($this->checkFields[$label]);
continue;
}
}
$this->addElement($element);
}
} | Add user defined checkfields
@return void | entailment |
public function getAskOld()
{
if (null === $this->askOld) {
// By default only ask for the old password if the user just entered
// it but is required to change it.
$this->askOld = (! $this->user->isPasswordResetRequired());
}
// Never ask for the old password if it does not exist
//
// A password does not always exist, e.g. when using embedded login in Pulse
// or after creating a new user.
return $this->askOld && $this->user->hasPassword();
} | Should the for asking for an old password
@return boolean | entailment |
public function getNewPasswordElement()
{
$element = $this->getElement($this->_newPasswordFieldName);
if (! $element) {
// Field new password
$element = new \Zend_Form_Element_Password($this->_newPasswordFieldName);
$element->setLabel($this->_('New password'));
$element->setAttrib('size', 40);
$element->setRequired(true);
$element->setRenderPassword(true);
$element->addValidator(new \Gems_User_Validate_NewPasswordValidator($this->user));
$validator = new \MUtil_Validate_IsConfirmed($this->_newPasswordFieldName, $this->_('Repeat password'));
$validator->setMessage(
$this->_("Must be the same as %fieldDescription%."),
\MUtil_Validate_IsConfirmed::NOT_SAME
);
$element->addValidator($validator);
$this->addElement($element);
}
return $element;
} | Returns/sets a new password element.
@return \Zend_Form_Element_Password | entailment |
public function getOldPasswordElement()
{
$element = $this->getElement($this->_oldPasswordFieldName);
if (! $element) {
// Field current password
$element = new \Zend_Form_Element_Password($this->_oldPasswordFieldName);
$element->setLabel($this->_('Current password'));
$element->setAttrib('size', 40);
$element->setRenderPassword(true);
$element->setRequired(true);
$element->addValidator(
new \Gems_User_Validate_UserPasswordValidator($this->user, $this->_('Wrong password.'))
);
$this->addElement($element);
}
return $element;
} | Returns/sets a check old password element.
@return \Zend_Form_Element_Password | entailment |
public function getRepeatPasswordElement()
{
$element = $this->getElement($this->_repeatPasswordFieldName);
if (! $element) {
// Field repeat password
$element = new \Zend_Form_Element_Password($this->_repeatPasswordFieldName);
$element->setLabel($this->_('Repeat password'));
$element->setAttrib('size', 40);
$element->setRequired(true);
$element->setRenderPassword(true);
$validator = new \MUtil_Validate_IsConfirmed($this->_newPasswordFieldName, $this->_('New password'));
$validator->setMessage(
$this->_("Must be the same as %fieldDescription%."),
\MUtil_Validate_IsConfirmed::NOT_SAME
);
$element->addValidator($validator);
$this->addElement($element);
}
return $element;
} | Returns/sets a repeat password element.
@return \Zend_Form_Element_Password | entailment |
public function getReportNoEnforcementElement()
{
$element = $this->getElement($this->_reportNoEnforcementFieldName);
if (! $element) {
// Show no enforcement info
$element = new \MUtil_Form_Element_Html($this->_reportNoEnforcementFieldName);
$element->setLabel($this->_('Rule enforcement'));
$element->div()->strong($this->_('Choose a non-compliant password to force a password change at login.'));
$this->addElement($element);
}
return $element;
} | Returns/sets an element showing the password rules
@return \MUtil_Form_Element_Html | entailment |
public function getReportRulesElement()
{
$element = $this->getElement($this->_reportRulesFieldName);
if (! $element) {
$info = $this->user->reportPasswordWeakness();
// Show password info
if ($info) {
$element = new \MUtil_Form_Element_Html($this->_reportRulesFieldName);
$element->setLabel($this->_('Password rules'));
if (1 == count($info)) {
$element->div(sprintf($this->_('A password %s.'), reset($info)));
} else {
foreach ($info as &$line) {
$line .= ';';
}
$line[strlen($line) - 1] = '.';
$element->div($this->_('A password:'))->ul($info);
}
$this->addElement($element);
}
}
return $element;
} | Returns/sets an element showing the password rules
@return \MUtil_Form_Element_Html | entailment |
public function isValid($data, $disableTranslateValidators = null)
{
$valid = parent::isValid($data, $disableTranslateValidators);
if ($valid === false && $this->forceRules === false) {
$messages = $this->getMessages();
// If we don't enforce password rules, we pass validation but leave error messages in place.
if (count($messages) == 1 && array_key_exists('new_password', $messages)) {
$valid = true;
}
}
if ($valid) {
$this->user->setPassword($data['new_password']);
} else {
if ($this ->getAskOld() && isset($data['old_password'])) {
if ($data['old_password'] === strtoupper($data['old_password'])) {
$this->addError($this->_('Caps Lock seems to be on!'));
}
}
$this->populate($data);
}
return $valid;
} | 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 loadDefaultElements()
{
if ($this->getAskOld()) {
$this->getOldPasswordElement();
}
if ($this->getAskCheck()) {
$this->addCheckFields();
}
$this->getNewPasswordElement();
$this->getRepeatPasswordElement();
$this->getSubmitButton();
if (! $this->forceRules) {
$this->getReportNoEnforcementElement();
}
if ($this->reportRules) {
$this->getReportRulesElement();
}
if ($this->useTableLayout) {
/****************
* Display form *
****************/
$this->_table = new \MUtil_Html_TableElement(array('class' => 'formTable'));
$this->_table->setAsFormLayout($this, true, true);
$this->_table['tbody'][0][0]->class = 'label'; // Is only one row with formLayout, so all in output fields get class.
}
return $this;
} | The function that determines the element load order
@return \Gems_User_Form_LoginForm (continuation pattern) | entailment |
public function loadDefaultDecorators()
{
parent::loadDefaultDecorators();
if (\MUtil_Bootstrap::enabled() === true) {
$this->addDecorator('Description', array('tag' => 'p', 'class' => 'help-block'))
->addDecorator('HtmlTag', array(
'tag' => 'div',
'id' => array('callback' => array(get_class($this), 'resolveElementId')),
'class' => 'element-container'
))
->addDecorator('Label')
->addDecorator('BootstrapRow');
}
return $this;
} | Load default decorators
@return \Zend_Form_Element | entailment |
protected function setAfterDeleteRoute()
{
parent::setAfterDeleteRoute();
if ($this->afterSaveRouteUrl) {
$this->afterSaveRouteUrl[\MUtil_Model::REQUEST_ID] = $this->request->getParam(\MUtil_Model::REQUEST_ID);
}
} | Set what to do when the form is 'finished'.
@return \Gems_Snippets_Tracker_Fields_FieldDeleteSnippet (continuation pattern) | entailment |
public function addListModel(\MUtil_Model_ModelAbstract $model, array $joins, $name = null)
{
if (null === $name) {
$name = $model->getName();
}
$trans = new \MUtil_Model_Transform_NestedTransformer();
$trans->skipSave = true;
$trans->addModel($model, $joins);
$this->addTransformer($trans);
$this->set($name,
'model', $model,
'elementClass', 'FormTable',
'type', \MUtil_Model::TYPE_CHILD_MODEL
);
$bridge = $model->getBridgeFor('table');
$this->set($name, 'formatFunction', array($bridge, 'displayListTable'));
return $trans;
} | Add a 'submodel' field to the model.
You get a nested join where a set of rows is placed in the $name field
of each row of the parent model.
@param \MUtil_Model_ModelAbstract $model
@param array $joins The join fields for the sub model
@param string $name Optional 'field' name, otherwise model name is used
@return \MUtil_Model_Transform_NestedTransformer The added transformer | entailment |
public function processBeforeSave(array $row)
{
if ($this->getMeta('nested', false)) {
$nestedNames = $this->getMeta('nestedNames');
foreach($nestedNames as $nestedName) {
if (isset($row[$nestedName])) {
foreach($row[$nestedName] as $key => $answer) {
$a = array_shift($answer);
if (empty($a)) {
unset($row[$nestedName][$key]);
}
}
}
}
}
if (!isset($row['gto_completion_time']) || $row['gto_completion_time']) {
$row['gto_completion_time'] = new \MUtil_Date;
}
$row = parent::processBeforeSave($row);
return $row;
} | Helper function that procesess the raw data before a save.
@param array $row Row array containing saved (and maybe not saved data)
@return array Nested | entailment |
protected function getAutoSearchElements(array $data)
{
// Search text
$elements = parent::getAutoSearchElements($data);
$respondentList[''] = $this->_('(all organizations)');
$respondentList['maybePatient'] = $this->_('Organizations that may have respondents');
$respondentList['createPatient'] = $this->_('Organizations that create respondents');
$respondentList['hasPatient'] = $this->_('Organizations that have respondents');
$respondentList['noNewPatient'] = $this->_('Organizations that cannot create new respondents');
$respondentList['noPatient'] = $this->_('Organizations that have no respondents');
$elements['pats'] = $this->_createSelectElement('respondentstatus', $respondentList);
$elements['orgs'] = $this->_createSelectElement('accessible_by', $this->currentUser->getAllowedOrganizations(), $this->_('(accessible by any organization)'));
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 |
public function checkRegistryRequestsAnswers()
{
if ((! $this->userId) && $this->currentUser) {
$this->userId = $this->currentUser->getUserId();
}
return $this->loader && $this->request && parent::checkRegistryRequestsAnswers();
} | 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 |
protected function createModel()
{
$tracker = $this->loader->getTracker();
$model = $tracker->getRespondentTrackModel();
if (! $this->trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
if (! $this->respondentTrack) {
$this->respondentTrack = $tracker->getRespondentTrack($this->respondentTrackId);
}
$this->trackEngine = $this->respondentTrack->getTrackEngine();
}
$model->applyEditSettings($this->trackEngine);
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function hasHtmlOutput()
{
if ($this->respondent instanceof \Gems_Tracker_Respondent) {
if (! $this->patientId) {
$this->patientId = $this->respondent->getPatientNumber();
}
if (! $this->organizationId) {
$this->organizationId = $this->respondent->getOrganizationId();
}
}
// Try to get $this->respondentTrackId filled
if (! $this->respondentTrackId) {
if ($this->respondentTrack) {
$this->respondentTrackId = $this->respondentTrack->getRespondentTrackId();
} else {
$this->respondentTrackId = $this->request->getParam(\Gems_Model::RESPONDENT_TRACK);
}
}
// Try to get $this->respondentTrack filled
if ($this->respondentTrackId && (! $this->respondentTrack)) {
$this->respondentTrack = $this->loader->getTracker()->getRespondentTrack($this->respondentTrackId);
}
// Set the user id
if (! $this->userId) {
$this->userId = $this->loader->getCurrentUser()->getUserId();
}
if ($this->respondentTrack) {
// We are updating
$this->createData = false;
// Try to get $this->trackEngine filled
if (! $this->trackEngine) {
// Set the engine used
$this->trackEngine = $this->respondentTrack->getTrackEngine();
}
} else {
// We are inserting
$this->createData = true;
$this->saveLabel = $this->_($this->_('Add track'));
// Try to get $this->trackId filled
if (! $this->trackId) {
if ($this->trackEngine) {
$this->trackId = $this->trackEngine->getTrackId();
} else {
$this->trackId = $this->request->getParam(\Gems_Model::TRACK_ID);
}
}
// Try to get $this->trackEngine filled
if ($this->trackId && (! $this->trackEngine)) {
$this->trackEngine = $this->loader->getTracker()->getTrackEngine($this->trackId);
}
if (! ($this->trackEngine && $this->patientId && $this->organizationId && $this->userId)) {
throw new \Gems_Exception_Coding('Missing parameter for ' . __CLASS__ .
': could not find data for editing a respondent track nor the track engine, patientId and organizationId needed for creating one.');
}
}
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 loadFormData()
{
$model = $this->getModel();
// When creating and not posting nor having $this->formData set already
// we gotta make a special call
if ($this->createData && (! ($this->formData || $this->request->isPost()))) {
$filter['gtr_id_track'] = $this->trackId;
$filter['gr2o_patient_nr'] = $this->patientId;
$filter['gr2o_id_organization'] = $this->organizationId;
$this->formData = $model->loadNew(null, $filter);
} else {
parent::loadFormData();
}
if (isset($this->formData['gr2t_completed']) && $this->formData['gr2t_completed']) {
// Cannot change start date after first answered token
$model->set('gr2t_start_date', 'elementClass', 'Exhibitor',
'formatFunction', $this->util->getTranslated()->formatDateUnknown,
'description', $this->_('Cannot be changed after first answered token.')
);
}
if ((! $this->createData) && isset($this->formData['grc_success']) && (! $this->formData['grc_success'])) {
$model->set('grc_description', 'label', $this->_('Rejection code'),
'elementClass', 'Exhibitor'
);
}
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function setAfterSaveRoute()
{
parent::setAfterSaveRoute();
if (is_array($this->afterSaveRouteUrl)) {
if (isset($this->afterSaveRouteUrl['action'], $this->formData['gr2t_id_respondent_track']) &&
'index' !== $this->afterSaveRouteUrl['action']) {
$this->afterSaveRouteUrl[\Gems_Model::RESPONDENT_TRACK] = $this->formData['gr2t_id_respondent_track'];
}
}
} | If menu item does not exist or is not allowed, redirect to index
@return \Gems_Snippets_ModelFormSnippetAbstract | entailment |
protected function capsCount($parameter, $password)
{
$len = intval($parameter);
$results = array();
if ($len && (preg_match_all('/[A-Z]/', $password, $results) < $len)) {
$this->_addError(sprintf(
$this->translate->plural('should contain at least one uppercase character', 'should contain at least %d uppercase characters', $len),
$len));
}
} | Test the password for minimum number of upper case characters.
@param mixed $parameter
@param string $password | entailment |
protected function inPasswordList($parameter, $password)
{
if (empty($parameter)) {
return;
}
if ($this->cache) {
$passwordList = $this->cache->load('weakpasswordlist');
}
if (empty($passwordList)) {
$filename = __DIR__ . '/../../../docs/' . ltrim($parameter, '/');;
if (! file_exists($filename)) {
throw new \Gems_Exception("Unable to load password list '{$filename}'");
}
$passwordList = explode("\n", file_get_contents($filename));
if ($this->cache) {
$this->cache->save($passwordList, 'weakpasswordlist');
}
}
if (null === $password) {
$this->_addError($this->translate->_('should not appear in the list of common passwords'));
} elseif (in_array(strtolower($password), $passwordList)) {
$this->_addError($this->translate->_('appears in the list of common passwords'));
}
} | Tests if the password appears on a (weak) password list. The list should
be a simpe newline separated list of (lowercase) passwords.
@param string $parameter Filename of the password list, relative to APPLICATION_PATH
@param string $password The password | entailment |
protected function maxAge($parameter, $password)
{
$age = intval($parameter);
if (is_null($password)) {
// We return the description of this rule
$this->_addError(sprintf($this->translate->_('should be changed at least every %d days'), $age));
} elseif ($age > 0 && !$this->user->isPasswordResetRequired() && $this->user->getPasswordAge() > $age) {
// Skip this if we already should change the password
$this->_addError(sprintf($this->translate->_('has not been changed the last %d days and should be changed'), $age));
$this->user->setPasswordResetRequired();
}
} | Test the password for maximum age (in days).
@param mixed $parameter
@param string $password | entailment |
protected function minLength($parameter, $password)
{
$len = intval($parameter);
if ($len && (strlen($password) < $len)) {
$this->_addError(sprintf($this->translate->_('should be at least %d characters long'), $len));
}
} | Test the password for minimum length.
@param mixed $parameter
@param string $password | entailment |
protected function notAlphaNumCount($parameter, $password)
{
$len = intval($parameter);
if ($len) {
$results = array(); // Not used but required
$count = strlen($password) - preg_match_all('/[0-9A-Za-z]/', $password, $results);
if (($len > 0) && ($count < $len)) {
$this->_addError(sprintf(
$this->translate->plural('should contain at least one non alphanumeric character', 'should contain at least %d non alphanumeric characters', $len),
$len));
} elseif (($len < 0) && (($count > 0) || (null === $password))) {
$this->_addError($this->translate->_('should not contain non alphanumeric characters'));
}
}
} | Test the password for minimum number not alphanumeric characters.
@param mixed $parameter
@param string $password | entailment |
protected function notTheName($parameter, $password)
{
$on = $parameter != 0;
if ($on) {
$lpwd = strtolower($password);
if ((false !== strpos($lpwd, strtolower($this->user->getLoginName()))) || (null === $password)) {
$this->_addError($this->translate->_('should not contain your login name'));
}
}
} | The password should not contain the name of the user or the login name.
@param mixed $parameter
@param string $password | entailment |
public function reportPasswordWeakness(\Gems_User_User $user, $password, array $codes, $skipAge = false)
{
$this->user = $user;
$this->_errors = array();
$rules = $this->project->getPasswordRules($codes);
if ($skipAge) {
unset($rules['maxAge']);
}
// \MUtil_Echo::track($rules);
foreach ($rules as $rule => $parameter) {
if (method_exists($this, $rule)) {
$this->$rule($parameter, $password);
}
}
// \MUtil_Echo::track($this->_errors);
return $this->_errors;
} | Check for password weakness.
@param \Gems_User_User $user
@param string $password Or null when you want a report on all the rules for this password.
@param array $codes An array of code names that identify rules that should be used only for those codes.
@param boolean $skipAge When setting a new password, we should not check for age
@return mixed String or array of strings containing warning messages | entailment |
protected function createModel()
{
if (! $this->model instanceof \Gems_Tracker_Model_TrackModel) {
$tracker = $this->loader->getTracker();
$this->model = $tracker->getRespondentTrackModel();
if (! $this->trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
$this->trackEngine = $this->respondentTrack->getTrackEngine();
}
$this->model->applyEditSettings($this->trackEngine);
}
$this->model->set('restore_tokens', 'label', $this->_('Restore tokens'),
'description', $this->_('Restores tokens with the same code as the track.'),
'elementClass', 'Checkbox'
);
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getReceptionCodes()
{
$rcLib = $this->util->getReceptionCodeLibrary();
if ($this->unDelete) {
return $rcLib->getTrackRestoreCodes();
}
return $rcLib->getTrackDeletionCodes();
} | Called after loadFormData() and isUndeleting() but before the form is created
@return array | entailment |
public function setReceptionCode($newCode, $userId)
{
$oldCode = $this->respondentTrack->getReceptionCode();
if (! $newCode instanceof \Gems_Util_ReceptionCode) {
$newCode = $this->util->getReceptionCode($newCode);
}
// Use the repesondent track function as that cascades the consent code
$changed = $this->respondentTrack->setReceptionCode($newCode, $this->formData['gr2t_comment'], $userId);
if ($this->unDelete) {
$this->addMessage($this->_('Track restored.'));
if (isset($this->formData['restore_tokens']) && $this->formData['restore_tokens']) {
$count = $this->respondentTrack->restoreTokens($oldCode, $newCode);
$this->addMessage(sprintf($this->plural(
'%d token reception codes restored.',
'%d tokens reception codes restored.',
$count
), $count));
}
} else {
if ($newCode->isStopCode()) {
$this->addMessage($this->_('Track stopped.'));
} else {
$this->addMessage($this->_('Track deleted.'));
}
}
return $changed;
} | Hook performing actual save
@param string $newCode
@param int $userId
@return $changed | entailment |
protected function createModel()
{
$model = $this->loader->getTracker()->getRespondentTrackModel();
$model->addColumn('CONCAT(gr2t_completed, \'' . $this->_(' of ') . '\', gr2t_count)', 'progress');
$model->resetOrder();
$model->set('gtr_track_name', 'label', $this->_('Track'));
$model->set('gr2t_track_info', 'label', $this->_('Description'));
$model->set('gr2t_start_date', 'label', $this->_('Start'),
'formatFunction', $this->util->getTranslated()->formatDate,
'default', \MUtil_Date::format(new \Zend_Date(), 'dd-MM-yyyy'));
$model->set('gr2t_reception_code');
$model->set('progress', 'label', $this->_('Progress')); // , 'tdClass', 'rightAlign', 'thClass', 'rightAlign');
$model->set('assigned_by', 'label', $this->_('Assigned by'));
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getAnswerDisplaySnippets(\Gems_Tracker_Token $token)
{
$snippets = parent::getAnswerDisplaySnippets($token);
if (!is_array($snippets)) {
$snippets = array($snippets);
}
// Add the ScoreChartsSnippet
$snippets[] = 'Survey_Display_ScoreChartsSnippet';
return $snippets;
} | Function that returns the snippets to use for this display.
@param \Gems_Tracker_Token $token The token to get the snippets for
@return array of Snippet names or nothing | entailment |
public function getLostPasswordElement()
{
$element = $this->getElement($this->_lostPasswordFieldName);
if (! $element) {
// Reset password
$element = new \MUtil_Form_Element_Html($this->_lostPasswordFieldName);
// $element->br();
$element->setValue($this->getLostPasswordLink());
$this->addElement($element);
}
return $element;
} | Returns/sets a link to the reset password page
@return \MUtil_Form_Element_Html | entailment |
public function getPasswordElement()
{
$element = $this->getElement($this->passwordFieldName);
if (! $element) {
// Veld password
$element = $this->createElement('password', $this->passwordFieldName);
$element->setLabel($this->translate->_('Password'));
$element->setAttrib('size', 40);
$element->setRequired(true);
if ($this->getOrganizationElement() instanceof \Zend_Form_Element_Hidden) {
$explain = $this->translate->_('Combination of user and password not found.');
} else {
$explain = $this->translate->_('Combination of user and password not found for this organization.');
}
$element->addValidator(new \Gems_User_Validate_GetUserPasswordValidator($this, $explain));
$this->addElement($element);
}
return $element;
} | Returns/sets a password element.
@return \Zend_Form_Element_Password | entailment |
public function getTokenElement()
{
$element = $this->getElement($this->_tokenFieldName);
if (! $element) {
// Veld token
$element = $this->createElement('html', $this->_tokenFieldName);
// $element->br();
$element->setValue($this->getTokenLink());
$this->addElement($element);
}
return $element;
} | Returns/sets a link for the token input page.
@return \MUtil_Form_Element_Html | entailment |
public function loadDefaultElements()
{
$this->getOrganizationElement();
$this->getUserNameElement();
$this->getPasswordElement();
$this->getSubmitButton();
if ($this->showPasswordLost) {
$this->getLostPasswordElement();
}
if ($this->showToken) {
$this->getTokenElement();
}
return $this;
} | The function that determines the element load order
@return \Gems_User_Form_LoginForm (continuation pattern) | entailment |
protected function _getEventClass($eventType)
{
if (isset($this->_eventClasses[$eventType])) {
return $this->_eventClasses[$eventType];
} else {
throw new \Gems_Exception_Coding("No event class exists for event type '$eventType'.");
}
} | Lookup event class for an event type. This class or interface should at the very least
implement the EventInterface.
@see \Gems_Event_EventInterface
@param string $eventType The type (i.e. lookup directory) to find the associated class for
@return string Class/interface name associated with the type | entailment |
protected function _listEvents($eventType)
{
$classType = $this->_getEventClass($eventType);
$paths = $this->_getEventDirs($eventType);
return $this->util->getTranslated()->getEmptyDropdownArray() + $this->listClasses($classType, $paths, 'getEventName');
} | Returns a list of selectable events with an empty element as the first option.
@param string $eventType The type (i.e. lookup directory with an associated class) of the events to list
@return \Gems_tracker_TrackerEventInterface or more specific a $eventClass type object | entailment |
protected function _loadEvent($eventName, $eventType)
{
$eventClass = $this->_getEventClass($eventType);
// \MUtil_Echo::track($eventName);
if (! class_exists($eventName, true)) {
// Autoload is used for Zend standard defined classnames,
// so if the class is not autoloaded, define the path here.
$filename = APPLICATION_PATH . '/events/' . strtolower($eventType) . '/' . $eventName . '.php';
if (! file_exists($filename)) {
throw new \Gems_Exception_Coding("The event '$eventName' of type '$eventType' does not exist at location: $filename.");
}
// \MUtil_Echo::track($filename);
include($filename);
}
$event = new $eventName();
if (! $event instanceof $eventClass) {
throw new \Gems_Exception_Coding("The event '$eventName' of type '$eventType' is not an instance of '$eventClass'.");
}
if ($event instanceof \MUtil_Registry_TargetInterface) {
$this->applySource($event);
}
return $event;
} | Loads and initiates an event class and returns the class (without triggering the event itself).
@param string $eventName The class name of the individual event to load
@param string $eventType The type (i.e. lookup directory with an associated class) of the event
@return \Gems_tracker_TrackerEventInterface or more specific a $eventClass type object | entailment |
protected function getRouteInformation(Route $route, $filter, $namespace)
{
$data = parent::getRouteInformation($route, $filter, $namespace);
if (!$data || empty($data['name'])) {
return null;
}
return array_only($data, ['uri', 'name']);
} | Get the route information for a given route.
@param $route \Illuminate\Routing\Route
@param $filter string
@param $namespace string
@return array | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$seq = $this->getHtmlSequence();
$seq->h2($this->_('Checks'));
$seq->pInfo($this->_(
'Check tokens for being answered or not, reruns survey and round event code on completed tokens and recalculates the start and end times of all tokens in tracks that have completed tokens.'
));
$seq->pInfo($this->_(
'Run this code when survey result fields, survey or round events or the event code has changed or after bulk changes in a survey source.'
));
if ($this->itemDescription) {
$seq->pInfo($this->itemDescription);
}
return $seq;
} | 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 transformLoad(\MUtil_Model_ModelAbstract $model, array $data, $new = false, $isPostData = false)
{
// get tokens
$tokens = \MUtil_Ra::column('gto_id_token', $data);
$answerRows = $this->source->getRawTokenAnswerRows(array('token' => $tokens), $this->survey->getSurveyId());
$resultRows = array();
$emptyRow = array_fill_keys($model->getItemNames(), null);
foreach ($data as $row) {
$tokenId = $row['gto_id_token'];
if (isset($answerRows[$tokenId])) {
$resultRows[$tokenId] = $row + $answerRows[$tokenId] + $emptyRow;
} else {
$resultRows[$tokenId] = $row + $emptyRow;
}
}
//\MUtil_Echo::track($tokens);
//\MUtil_Echo::track($resultRows);
// No changes
return $resultRows;
} | The transform function performs the actual transformation of the data and is called after
the loading of the data in the source model.
@param \MUtil_Model_ModelAbstract $model The parent model
@param array $data Nested array
@param boolean $new True when loading a new item
@param boolean $isPostData With post data, unselected multiOptions values are not set so should be added
@return array Nested array containing (optionally) transformed data | entailment |
public function transformRowAfterSave(\MUtil_Model_ModelAbstract $model, array $row)
{
$token = $this->source->getToken($row['gto_id_token']);
$answers = $row;
$surveyId = $this->survey->getSurveyId();
if ($this->source->setRawTokenAnswers($token, $answers, $surveyId)) {
$this->changed++;
}
// No changes
return $row;
} | This transform function performs the actual save (if any) of the transformer data and is called after
the saving of the data in the source model.
@param \MUtil_Model_ModelAbstract $model The parent model
@param array $row Array containing row
@return array Row array containing (optionally) transformed data | entailment |
public function translateRowValues($row, $key)
{
$row = parent::translateRowValues($row, $key);
if (! $row) {
return false;
}
// Default to active and can login
if (!isset($row['gsf_active'])) {
$row['gsf_active'] = 1;
}
if (!isset($row['gul_can_login'])) {
$row['gul_can_login'] = 1;
}
// Make sure we have an organization
if (!isset($row['gsf_id_organization'])) {
$row['gsf_id_organization'] = $this->_organization->getId();
}
// Use organization default userclass is not specified
if (!isset($row['gul_user_class'])) {
$row['gul_user_class'] = $this->loader->getUserLoader()->getOrganization($row['gsf_id_organization'])->get('gor_user_class');
}
return $row;
} | Add organization id and gul_user_class when needed
@param mixed $row array or \Traversable row
@param scalar $key
@return mixed Row array or false when errors occurred | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
// Has no function here
unset($elements['token_status']);
$elements[] = new \Zend_Form_Element_Hidden(\Gems_Selector_DateSelectorAbstract::DATE_FACTOR);
$elements[] = new \Zend_Form_Element_Hidden(\Gems_Selector_DateSelectorAbstract::DATE_GROUP);
$elements[] = new \Zend_Form_Element_Hidden(\Gems_Selector_DateSelectorAbstract::DATE_TYPE);
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 _set($name, $value)
{
$this->_data[$name] = $value;
// Do not reload / save here:
// 1: other changes might follow,
// 2: it might not be used,
// 3: e.g. database saves may change other data.
$this->invalidateCache();
return $this;
} | Changes a value and signals the cache.
@param string $name
@param mixed $value
@return \Gems_Registry_CachedArrayTargetAbstract (continuation pattern) | entailment |
public function checkRegistryRequestsAnswers()
{
if ($this->cache) {
$cacheId = $this->_getCacheId();
$this->_data = $this->cache->load($cacheId);
} else {
$cacheId = false;
}
if (! $this->_data) {
$this->_data = $this->loadData($this->_id);
if ($cacheId) {
$this->cache->save($this->_data, $cacheId, $this->_cacheTags);
}
}
// \MUtil_Echo::track($this->_data);
$this->exists = is_array($this->_data);
return ($this->exists || (! $this->requireArray)) && parent::checkRegistryRequestsAnswers();
} | 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 invalidateCache()
{
if ($this->cache) {
$cacheId = $this->_getCacheId();
$this->cache->remove($cacheId);
}
return $this;
} | Empty the cache of the organization
@return \Gems_User_Organization (continutation pattern) | entailment |
public function getSearchDefaults()
{
if (! $this->defaultSearchData) {
$orgId = $this->currentOrganization->getId();
$this->defaultSearchData[-1] = "gtr_organizations LIKE '%|$orgId|%'";
}
return parent::getSearchDefaults();
} | Function to allow the creation of search defaults in code
@see getSearchFilter()
@return array | entailment |
public function questionsAction()
{
$this->addSnippet('Survey\\SurveyQuestionsSnippet',
'menu', $this->menu,
'surveyId', $this->_getParam(\Gems_Model::SURVEY_ID),
'trackId', $this->_getIdParam()
);
} | Show the questions in a survey | entailment |
protected function createModel($detailed, $action)
{
$dbLookup = $this->util->getDbLookup();
$dbTracks = $this->util->getTrackData();
$translated = $this->util->getTranslated();
$unselected = array('' => '');
$model = new \MUtil_Model_TableModel('gems__comm_jobs');
\Gems_Model::setChangeFieldsByPrefix($model, 'gcj');
$model->set('gcj_id_order', 'label', $this->_('Order'), 'description', $this->_('Execution order of the communication jobs, lower numbers are executed first.'));
if ($detailed) {
$model->set('gcj_id_order', 'validator', $model->createUniqueValidator('gcj_id_order'));
if ($action == 'create') {
// Set the default round order
$newOrder = $this->db->fetchOne("SELECT MAX(gcj_id_order) FROM gems__comm_jobs");
if ($newOrder) {
$model->set('gcj_id_order', 'default', $newOrder + 10);
}
}
}
$model->set('gcj_id_message', 'label', $this->_('Template'), 'multiOptions', $unselected + $dbLookup->getCommTemplates('token'));
$model->set('gcj_id_user_as', 'label', $this->_('By staff member'),
'multiOptions', $unselected + $dbLookup->getActiveStaff(), 'default', $this->currentUser->getUserId(),
'description', $this->_('Used for logging and possibly from address.'));
$activeOptions = [
0 => $this->_('Disabled'),
1 => $this->_('Automatic'),
2 => $this->_('By hand')
];
$model->set('gcj_active', 'label', $this->_('Execution'),
'multiOptions', $activeOptions, 'required', true,
'description', $this->_('Job is only run when not disabled.'));
$fromMethods = $unselected + $this->getBulkMailFromOptions();
$model->set('gcj_from_method', 'label', $this->_('From address used'), 'multiOptions', $fromMethods);
if ($detailed) {
// Show other field only when last $fromMethod is select
end($fromMethods); // Move array pointer to the end
$lastKey = key($fromMethods);
$switches = array($lastKey => array( 'gcj_from_fixed' => array('elementClass' => 'Text', 'label' => $this->_('From other'))));
$model->addDependency(array('ValueSwitchDependency', $switches), 'gcj_from_method');
$model->set('gcj_from_fixed', 'label', '',
'elementClass', 'Hidden');
}
if ($detailed) {
$bulkProcessOptions = $translated->getBulkMailProcessOptions();
} else {
$bulkProcessOptions = $translated->getBulkMailProcessOptionsShort();
}
$model->set('gcj_process_method', 'label', $this->_('Processing Method'), 'default', 'O', 'multiOptions', $bulkProcessOptions);
$model->set('gcj_filter_mode', 'label', $this->_('Filter for'), 'multiOptions', $unselected + $this->getBulkMailFilterOptions());
if ($detailed) {
// Only show reminder fields when needed
$switches = array(
'R' => array(
'gcj_filter_days_between' => array('elementClass' => 'Text', 'label' => $this->_('Days between reminders'),'description', $this->_('1 day means the reminder is send the next day')),
'gcj_filter_max_reminders' => array('elementClass' => 'Text', 'label' => $this->_('Maximum reminders'))
),
'E' => array(
'gcj_filter_days_between' => array('elementClass' => 'Text', 'label' => $this->_('Days before expiration'),'description', ''),
)
);
$model->addDependency(array('ValueSwitchDependency', $switches), 'gcj_filter_mode');
$model->set('gcj_filter_days_between', 'label', '',
'elementClass', 'Hidden',
'validators[]', 'Digits');
$model->set('gcj_filter_max_reminders','label', '',
'elementClass', 'Hidden',
'description', $this->_('1 means only one reminder will be send'),
'validators[]', 'Digits');
}
// If you really want to see this information in the overview, uncomment for the shorter labels
// $model->set('gcj_filter_days_between', 'label', $this->_('Interval'), 'validators[]', 'Digits');
// $model->set('gcj_filter_max_reminders','label', $this->_('Max'), 'validators[]', 'Digits');
$model->set('gcj_target', 'label', $this->_('Filler'),
'default', 0, 'multiOptions', $translated->getBulkMailTargetOptions());
$anyTrack[''] = $this->_('(all tracks)');
$model->set('gcj_id_track', 'label', $this->_('Track'),
'multiOptions', $anyTrack + $dbTracks->getAllTracks(),
'onchange', 'this.form.submit();'
);
$anyRound[''] = $this->_('(all rounds)');
$defaultRounds = $anyRound + $dbTracks->getAllRoundDescriptions();
$model->set('gcj_round_description', 'label', $this->_('Round'),
'multiOptions', $defaultRounds,
'variableSelect', array(
'source' => 'gcj_id_track',
'baseQuery' => $this->roundDescQuery,
'ajax' => array('controller' => 'comm-job', 'action' => 'roundselect'),
'firstValue' => $anyRound,
'defaultValues' => $defaultRounds,
));
$anySurvey[''] = $this->_('(all surveys)');
$model->set('gcj_id_survey', 'label', $this->_('Survey'),
'multiOptions', $anySurvey + $dbTracks->getAllSurveys(true)
);
$organizations = $dbLookup->getOrganizations();
$anyOrganization[''] = $this->_('(all organizations)');
$model->set('gcj_id_organization',
'multiOptions', $anyOrganization + $organizations);
if ($detailed || count($organizations) > 1) {
$model->set('gcj_id_organization', 'label', $this->_('Organization'));
}
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 executeAction($preview = false)
{
$jobId = intval($this->getParam(\MUtil_Model::REQUEST_ID));
$batch = $this->loader->getTaskRunnerBatch('commjob-execute-' . $jobId);
$batch->setMessageLogFile($this->project->getCronLogfile());
$batch->minimalStepDurationMs = 3000; // 3 seconds max before sending feedback
if (!$batch->isLoaded() && !is_null(($jobId))) {
$batch->addMessage(sprintf(
$this->_('Starting single %s mail job %s'),
$this->project->getName(),
$jobId
));
// Check for unprocessed tokens
$tracker = $this->loader->getTracker();
$tracker->loadCompletedTokensBatch($batch, null, $this->currentUser->getUserId());
// We could skip this, but a check before starting the batch is better
$sql = $this->db->select()->from('gems__comm_jobs', array('gcj_id_job'))
->where('gcj_active > 0')
->where('gcj_id_job = ?', $jobId);
$job = $this->db->fetchOne($sql);
if (!empty($job)) {
$batch->addTask('Mail\\ExecuteMailJobTask', $job, null, null, $preview);
} else {
$batch->reset();
$this->addMessage($this->_("Mailjob is inactive and won't be executed"), 'danger');
}
if ($preview === true) {
$batch->autoStart = true;
}
}
if ($batch->isFinished()) {
// Add the messages to the view and forward
$messages = $batch->getMessages(true);
if (count($messages)) {
$this->addMessage($messages, 'info');
}
$this->_reroute(array('action'=>'show'));
}
if ($preview === true) {
$title = sprintf($this->_('Preview single mail job %s'), $jobId);
} else {
$title = sprintf($this->_('Executing single mail job %s'), $jobId);
}
$this->_helper->BatchRunner($batch, $title, $this->accesslog);
} | Execute a single mail job | entailment |
public function executeAllAction()
{
$this->_helper->BatchRunner(
$this->loader->getMailLoader()->getCronBatch('commjob-execute-all'),
$this->_('Execute all mail jobs'),
$this->accesslog
);
} | Execute all mail jobs | entailment |
protected function getBulkMailFromOptions()
{
$results['O'] = $this->_('Use organizational from address');
if (isset($project->email['site']) && $project->email['site']) {
$results['S'] = sprintf($this->_('Use site %s address'), $project->email['site']);
}
$results['U'] = $this->_("Use the 'By staff member' address");
$results['F'] = $this->_('Other');
return $results;
} | Options for from address use.
@return array | entailment |
public function indexAction()
{
$lock = $this->util->getCronJobLock();
if ($lock->isLocked()) {
$this->addMessage(sprintf($this->_('Automatic mails have been turned off since %s.'), $lock->getLockTime()));
if ($menuItem = $this->menu->findController('cron', 'cron-lock')) {
$menuItem->set('label', $this->_('Turn Automatic Mail Jobs ON'));
}
}
parent::indexAction();
$this->html->pInfo($this->_('With automatic mail jobs and a cron job on the server, mails can be sent without manual user action.'));
} | Action for showing a browse page | entailment |
public function roundselectAction()
{
\Zend_Layout::resetMvcInstance();
$trackId = $this->getRequest()->getParam('sourceValue');
$rounds = $this->db->fetchPairs($this->roundDescQuery, $trackId);
echo json_encode($rounds);
} | Ajax return function for round selection | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->routeController = $this->request->getControllerName();
$this->routeAction = $this->request->getActionName();
} | Called after the check that all required registry values
have been set correctly has run.
This function is no needed if the classes are setup correctly
@return void | entailment |
public function hasHtmlOutput()
{
$this->user = $this->loginStatusTracker->getUser();
if (! ($this->user && $this->user->canSetPassword())) {
return false;
}
if (! $this->loginStatusTracker->isPasswordResetActive()) {
$messages = $this->user->reportPasswordWeakness($this->loginStatusTracker->getPasswordText());
if ($messages) {
$this->addMessage($this->_('Your password must be changed.'));
foreach ($messages as &$message) {
$message = ucfirst($message) . '.';
}
$this->addMessage($messages);
$this->loginStatusTracker->setPasswordResetActive(true);
}
}
if ($this->loginStatusTracker->isPasswordResetActive()) {
// Skip parent::hasHtmlOutput()
// will trigger an error loop because you can only your password if set as current user
$this->user->setPasswordResetRequired(true);
$this->processForm();
}
return $this->loginStatusTracker->isPasswordResetActive();
} | 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()
{
parent::saveData();
$this->user->setPasswordResetRequired(false);
$this->loginStatusTracker->setPasswordResetActive(false);
} | Hook containing the actual save code.
@return int The number of "row level" items changed | entailment |
public function ajaxAction($table, $idField, $orderField)
{
$request = $this->getRequest();
if ($request->isPost()) {
$ids = $request->getPost('ids');
foreach($ids as $id) {
$cleanIds[] = (int) $id;
}
$db = $this->getActionController()->db;
$select = $db->select()->from($table, array($idField, $orderField))
->where($idField . ' in(?)', $cleanIds)
->order($orderField);
$oldOrder = $db->fetchPairs($select);
if(count($oldOrder) == count($cleanIds)) {
$newOrder = array_combine($cleanIds, $oldOrder);
$changed = 0;
foreach($newOrder as $id => $order)
{
$changed = $changed + $db->update($table,
array($orderField => $order),
$db->quoteInto($idField . ' = ?', $id)
);
}
$this->getActionController()->addMessage(sprintf($this->getActionController()->plural('%s record updated due to sorting.', '%s records updated due to sorting.', $changed), $changed));
return;
}
}
throw new \Gems_Exception($this->_('Sorting failed'), 403);
} | Handles sort in an ajax request
@param string $table The table used
@param string $idField The name of the field with the primary key
@param string $orderField The name of the field that holds the order
@return void
@throws Gems_Exception | entailment |
public function direct($sortAction = 'sort', $urlIdParam = 'id')
{
$view = $this->getView();
\MUtil_JQuery::enableView($view);
$jquery = $view->jQuery();
$jquery->enable(); //Just to make sure
$handler = \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler();
$url = $view->serverUrl() . $view->baseUrl() . '/' . $this->getRequest()->getControllerName() . '/' . $sortAction;
$script = file_get_contents(__DIR__ . '/js/SortableTable.js');
$fields = array(
'jQuery' => $handler,
'AJAXURL' => $url,
'IDPARAM' => $urlIdParam
);
$js = str_replace(array_keys($fields), $fields, $script);
$jquery->addOnLoad($js);
$buttons = \Mutil_Html::div();
$buttons->class = 'buttons pull-right';
$buttons->div($this->getActionController()->_('Sort'), array('id' => 'sort', 'class' => "btn"));
$buttons->div($this->getActionController()->_('Ok'), array('id' => 'sort-ok', 'class' => "btn btn-success", 'style' => 'display:none;'));
$buttons->div($this->getActionController()->_('Cancel'), array('id' => 'sort-cancel', 'class' => "btn btn-warning", 'style' => 'display:none;'));
return $buttons;
} | Get the sort buttons to add under the table with sortable rows
@param string $sortAction The name of the ajax action
@param string $urlIdParam The namr used to refer to the record ID in the url
@return MUtil_Html_HtmlElement | entailment |
public function getView()
{
$controller = $this->getActionController();
if (null === $controller) {
$controller = $this->getFrontController();
}
return $controller->view;
} | Get the view
@return Zend_View_Interface | entailment |
protected function createModel($detailed, $action)
{
$model = new \Gems_Model_JoinModel('log_maint', 'gems__log_setup', 'gls', true);
$model->set('gls_name', 'label', $this->_('Action'),
'elementClass', ('create' == $action) ? 'Text' : 'Exhibitor',
'validators[unique]', $model->createUniqueValidator('gls_name'));
$model->set('gls_when_no_user', 'label', $this->_('Log when no user'),
'description', $this->_('Always log this action, even when no one is logged in.'),
'elementClass', 'CheckBox',
'multiOptions', $this->util->getTranslated()->getYesNo()
);
$model->set('gls_on_action', 'label', $this->_('Log view'),
'description', $this->_('Always log when viewed / opened.'),
'elementClass', 'CheckBox',
'multiOptions', $this->util->getTranslated()->getYesNo()
);
$model->set('gls_on_post', 'label', $this->_('Log change tries'),
'description', $this->_('Log when trying to change the data.'),
'elementClass', 'CheckBox',
'multiOptions', $this->util->getTranslated()->getYesNo()
);
$model->set('gls_on_change', 'label', $this->_('Log data change'),
'description', $this->_('Log when data changes.'),
'elementClass', 'CheckBox',
'multiOptions', $this->util->getTranslated()->getYesNo()
);
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 |
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
{
parent::processFilterAndSort($model);
$filter = $model->getFilter();
if (isset($filter['gr2o_id_organization'])) {
$otherOrgs = $this->util->getOtherOrgsFor($filter['gr2o_id_organization']);
if (is_array($otherOrgs)) {
// If more than one org, do not use patient number but resp id
if (isset($filter['gr2o_patient_nr'])) {
$filter['gr2o_id_user'] = $this->respondent->getId();
unset($filter['gr2o_patient_nr']);
}
$filter['gr2o_id_organization'] = $otherOrgs;
// Second filter, should be changed as well
if (isset($this->extraFilter['gr2t_id_organization'])) {
$this->extraFilter['gr2t_id_organization'] = $otherOrgs;
}
$model->setFilter($filter);
}
}
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function createModel($detailed, $action)
{
$token = $this->getToken();
$model = $token->getSurveyAnswerModel($this->locale->getLanguage());
$items = $model->getItemNames();
$model->remove('token', 'label');
$model->set('orf_id', 'elementClass', 'Hidden');
if ($model->getMeta('nested', false)) {
// We have a nested model, add the nested questions
$nestedNames = $model->getMeta('nestedNames');
$requiredRows = array();
for ($i=1; $i<21; $i++) {
$row = array('orfr_id' => $i);
$requiredRows[] = $row;
}
$transformer = new \MUtil_Model_Transform_RequiredRowsTransformer();
$transformer->setRequiredRows($requiredRows);
foreach($nestedNames as $nestedName) {
$nestedModel = $model->get($nestedName, 'model');
$nestedModel->addTransformer($transformer);
}
}
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 continueClicked()
{
$html = $this->getHtmlSequence();
$org = $this->token->getOrganization();
$html->h3($this->_('Token'));
$mailLoader = $this->loader->getMailLoader();
/** @var \Gems_Mail_TokenMailer $mail */
$mail = $mailLoader->getMailer('token', $this->showToken->getTokenId());
$mail->setFrom($this->showToken->getOrganization()->getFrom());
if ($mail->setTemplateByCode('continue')) {
$lastMailedDate = \MUtil_Date::ifDate($this->showToken->getMailSentDate(), 'yyyy-MM-dd');
// Do not send multiple mails a day
if (! is_null($lastMailedDate) && $lastMailedDate->isToday()) {
$html->pInfo($this->_('An email with information to continue later was already sent to your registered email address today.'));
} else {
$mail->send();
$html->pInfo($this->_('An email with information to continue later was sent to your registered email address.'));
}
$html->pInfo($this->_('Delivery can take a while. If you do not receive an email please check your spam-box.'));
}
if ($sig = $org->getSignature()) {
$html->pInfo()->raw(\MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html'));
}
return $html;
} | Handle the situation when the continue later link was clicked
@return \MUtil_Html_HtmlInterface | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
if ($this->wasAnswered) {
if (!($this->showToken instanceof \Gems_Tracker_Token)) {
// Last token was answered, return info
return $this->lastCompleted();
} elseif ($this->checkContinueLinkClicked()) {
// Continue later was clicked, handle the click
return $this->continueClicked();
}
}
$delay = $this->project->getAskDelay($this->request, $this->wasAnswered);
$href = $this->getTokenHref($this->showToken);
$url = $href->render($this->view);
switch ($delay) {
case 0:
// Redirect at once
header('Location: ' . $url);
exit();
case -1:
break;
default:
// Let the page load after stated interval
$this->view->headMeta()->appendHttpEquiv('Refresh', $delay . '; url=' . $url);
}
$html = $this->getHtmlSequence();
$org = $this->showToken->getOrganization();
$html->h3($this->_('Token'));
$this->addWelcome($html);
if ($this->showToken && $this->showToken->hasRelation()) {
$html->pInfo(sprintf($this->_('We kindly ask you to answer a survey about %s.'), $this->showToken->getRespondent()->getName()));
}
if ($this->wasAnswered) {
$html->pInfo(sprintf($this->_('Thank you for answering the "%s" survey.'), $this->token->getSurveyName()));
$html->pInfo($this->_('Please click the button below to answer the next survey.'));
} else {
if ($welcome = $org->getWelcome()) {
$html->pInfo()->raw(\MUtil_Markup::render($this->_($welcome), 'Bbcode', 'Html'));
}
$html->pInfo(sprintf($this->_('Please click the button below to answer the survey for token %s.'), strtoupper($this->showToken->getTokenId())));
}
if ($delay > 0) {
$html->pInfo(sprintf($this->plural(
'Wait one second to open the survey automatically or click on Cancel to stop.',
'Wait %d seconds to open the survey automatically or click on Cancel to stop.',
$delay), $delay));
}
$buttonDiv = $html->buttonDiv(array('class' => 'centerAlign'));
$buttonDiv->actionLink($href, $this->showToken->getSurveyName());
$buttonDiv->append(' ');
$buttonDiv->append($this->formatDuration($this->showToken->getSurvey()->getDuration()));
$buttonDiv->append($this->formatUntil($this->showToken->getValidUntil()));
if ($delay > 0) {
$buttonDiv->actionLink(array('delay_cancelled' => 1), $this->_('Cancel'));
}
if ($this->wasAnswered) {
// Provide continue later link only when the first survey was answered
$this->addContinueLink($html);
}
if ($next = $this->showToken->getTokenCountUnanswered()) {
$html->pInfo(sprintf(
$this->plural(
'After this survey there is one other survey we would like you to answer.',
'After this survey there are another %d surveys we would like you to answer.',
$next), $next));
}
if ($sig = $org->getSignature()) {
$html->pInfo()->raw(\MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html'));
}
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 |
public function hasHtmlOutput()
{
if ($this->wasAnswered) {
$this->showToken = $this->token->getNextUnansweredToken();
} else {
$this->showToken = $this->token;
}
$validToken = ($this->showToken instanceof \Gems_Tracker_Token) && $this->showToken->exists;
if (!$validToken && $this->wasAnswered) {
// The token was answered, but there are no more tokens to show
$validToken = $this->showEndScreen;
}
return $validToken;
} | 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 lastCompleted()
{
// We use $this->token since there is no showToken anymore
$html = $this->getHtmlSequence();
$org = $this->token->getOrganization();
$html->h3($this->_('Token'));
$this->addWelcome($html);
$html->pInfo($this->_('Thank you for answering. At the moment we have no further surveys for you to take.'));
if ($sig = $org->getSignature()) {
$html->pInfo()->raw(\MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html'));
}
return $html;
} | The last token was answered, there are no more tokens to answer
@return \MUtil_Html_HtmlInterface | entailment |
protected function afterLoad()
{
if ($this->_data &&
$this->db instanceof \Zend_Db_Adapter_Abstract &&
! $this->_staff) {
if ($this->_data['gaf_filter_text1']) {
$sqlActivites = "SELECT gas_id_staff, gas_id_staff
FROM gems__agenda_staff
WHERE gas_active = 1 AND gas_name LIKE '%s'
ORDER BY gas_id_staff";
$this->_staff = $this->db->fetchPairs(sprintf(
$sqlActivites,
addslashes($this->_data['gaf_filter_text1']))
);
} else {
$this->_staff = true;
}
}
} | Override this function when you need to perform any actions when the data is loaded.
Test for the availability of variables as these objects can be loaded data first after
deserialization or registry variables first after normal instantiation.
That is why this function called both at the end of afterRegistry() and after exchangeArray(),
but NOT after unserialize().
After this the object should be ready for serialization | entailment |
public function getSqlAppointmentsWhere()
{
if ($this->_staff && ($this->_staff !== true)) {
$where = 'gap_id_attended_by IN (' . implode(', ', $this->_staff) . ')';
} else {
$where = '';
}
if ($where) {
return "($where)";
} else {
return parent::NO_MATCH_SQL;
}
} | Generate a where statement to filter the appointment model
@return string | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
if (true !== $this->_staff) {
if (isset($this->_staff[$appointment->getAttendedById()])) {
return true;
}
}
return false;
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
protected function getLookup($respondentId = null, $organizationId = null)
{
if ($respondentId !== null && $organizationId !== null) {
$respondentTracks = $this->loader->getTracker()->getRespondentTracks($respondentId, $organizationId);
$respondentTrackPairs = [];
foreach($respondentTracks as $respondentTrack) {
$name = $respondentTrack->getTrackName();
$startDate = $respondentTrack->getStartDate();
if ($startDate) {
$name .= ' (' . $startDate->toString('dd-MM-yyyy') . ')';
}
$respondentTrackPairs[$respondentTrack->getRespondentTrackId()] = $name;
}
return $respondentTrackPairs;
}
return [];
} | Return the lookup array for this field
@param int $organizationId Organization Id
@return array | entailment |
public function showTrack($value)
{
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
if (! $value || in_array($value, $empty)) {
return null;
}
if (!$value instanceof \Gems_Tracker_RespondentTrack) {
$value = $this->loader->getTracker()->getRespondentTrack($value);
}
if (!$value instanceof \Gems_Tracker_RespondentTrack) {
return null;
}
$name = $value->getTrackName();
/*$startDate = $value->getStartDate();
if ($startDate) {
$name .= ' (' . $startDate->toString('dd-MM-yyyy') . ')';
}*/
if (! $this->menu instanceof \Gems_Menu) {
$this->menu = $this->loader->getMenu();
}
$menuItem = $this->menu->findAllowedController('track', 'show-track');
if ($menuItem instanceof \Gems_Menu_SubMenuItem) {
if (!$this->request) {
$this->request = \Zend_Controller_Front::getInstance()->getRequest();
}
$href = $menuItem->toHRefAttribute([
'gr2t_id_respondent' => $value->getPatientNumber(),
'gr2t_id_organization' => $value->getOrganizationId(),
'gr2t_id_respondent_track' => $value->getRespondentTrackId(),
], $this->request);
if ($href) {
return \MUtil_Html::create('a', $href, $name);
}
}
return $name;
} | Display a respondent track as text
@param $value
@return string | entailment |
public function execute($tableName = '', $idField = '', $passwordField = '')
{
$passwords = $this->db->fetchPairs(
"SELECT $idField, $passwordField FROM $tableName WHERE $passwordField IS NOT NULL"
);
if ($passwords) {
foreach ($passwords as $key => $password) {
$values[$passwordField] = $this->project->encrypt($this->project->decrypt($password));
$this->db->update($tableName, $values, "$idField = '$key'");
}
$this->getBatch()->addMessage(sprintf($this->_('%d passwords encrypted for table %s.'), count($passwords), $tableName));
} else {
$this->getBatch()->addMessage(sprintf($this->_('No passwords found in table %s.'), $tableName));
}
} | 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 _write($event)
{
// $output = '<table cellspacing="10">';
$output = '<tr>';
$output .= '<td style="color:%color%;text-align:right;padding-right:1em">%priorityName%</td>';
$output .= '<td style="color:%color%;text-align:right;padding-right:1em">%memory%</td>';
$output .= '<td style="color:%color%;">%message%</td></tr>'; // (%priority%)
$event['color'] = '#C9C9C9';
// Count errors
if ($event['priority'] < 7) {
$event['color'] = 'green';
}
if ($event['priority'] < 6) {
$event['color'] = '#fd9600';
}
if ($event['priority'] < 5) {
$event['color'] = 'red';
$this->_errors++;
}
if ($event['priority'] == ZFDebug_Controller_Plugin_Debug_Plugin_Log::ZFLOG) {
$event['priorityName'] = $event['message']['time'];
$event['memory'] = $event['message']['memory'];
$event['message'] = $event['message']['message'];
} else {
// self::$_lastEvent = null;
$event['message'] = $event['priorityName'] .': '. $event['message'];
$event['priorityName'] = ' ';
$event['memory'] = ' ';
}
foreach ($event as $name => $value) {
if ('message' == $name) {
$measure = ' ';
if ((is_object($value) && !method_exists($value,'__toString'))) {
$value = gettype($value);
} elseif (is_array($value)) {
$measure = $value[0];
$value = $value[1];
}
}
$output = str_replace("%$name%", $value, $output);
}
$this->_messages[] = $output;
} | Write a message to the log.
@param array $event event data
@return void | entailment |
public function processTokenInsertion(\Gems_Tracker_Token $token)
{
if ($token->hasSuccesCode() && (! $token->isCompleted())) {
// Preparation for a more general object class
$surveyId = $token->getSurveyId();
$next = $token->getRespondentTrack()->getFirstToken();
while ($next) {
if ($next->hasSuccesCode() && $next->isCompleted()) {
// Check first on survey id and when that does not work by name.
if ($next->getSurveyId() == $surveyId) {
return $next->getRawAnswers();
}
}
$next = $next->getNextToken();
}
}
} | Process the data and return the answers that should be filled in beforehand.
Storing the changed values is handled by the calling function.
@param \Gems_Tracker_Token $token Gems token object
@return array Containing the changed values | entailment |
protected function addButtons(\Gems_Menu_MenuList $menuList)
{
if ($this->addCurrentParent) {
$menuList->addCurrentParent($this->_('Cancel'));
}
if ($this->addCurrentSiblings) {
$menuList->addCurrentSiblings($this->anyParameterSiblings);
}
if ($this->addCurrentChildren) {
$menuList->addCurrentChildren();
}
// \MUtil_Echo::track($this->addCurrentParent, $this->addCurrentSiblings, $this->addCurrentChildren, count($menuList));
} | Set the menu items (allows for overruling in subclasses)
@param \Gems_Menu_MenuList $menuList | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$menuList = $this->menu->getMenuList();
$menuList->addParameterSources($this->request, $this->menu->getParameterSource());
// \MUtil_Echo::track($this->request->getParams(), $this->menu->getParameterSource()->getArrayCopy());
$this->addButtons($menuList);
if ($menuList->render($view)) {
return \MUtil_Html::create('div', array('class' => 'buttons', 'renderClosingTag' => true), $menuList);
}
} | 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 getHtmlOutput(\Zend_View_Abstract $view)
{
$html = $this->getHtmlSequence();
$html->h3($this->_('Choose an organization'));
$url[$this->request->getControllerKey()] = $this->request->getControllerName();
$url[$this->request->getActionKey()] = $this->action;
if ($this->info) {
$html->pInfo($this->info);
}
foreach ($this->orgs as $orgId => $name) {
$url['org'] = $orgId;
$html->pInfo()->actionLink($url, $name)->appendAttrib('class', 'larger');
}
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 |
public function processFieldUpdate(\Gems_Tracker_RespondentTrack $respTrack, $userId)
{
$agenda = $this->loader->getAgenda();
$change = false;
$token = $respTrack->getFirstToken();
if (! $token) {
return;
}
do {
if ($token->isCompleted()) {
continue;
}
$appId = $respTrack->getRoundAfterAppointmentId($token->getRoundId());
// Not a round without appointment id
if ($appId !== false) {
if ($appId) {
$appointment = $agenda->getAppointment($appId);
} else {
$appointment = null;
}
if ($appointment && $appointment->isActive()) {
$newCode = \GemsEscort::RECEPTION_OK;
$newText = null;
} else {
$newCode = 'skip';
$newText = $this->_('Skipped until appointment is set');
}
$oldCode = \GemsEscort::RECEPTION_OK === $newCode ? 'skip' : \GemsEscort::RECEPTION_OK;
$curCode = $token->getReceptionCode()->getCode();
// \MUtil_Echo::track($token->getTokenId(), $curCode, $oldCode, $newCode);
if (($oldCode === $curCode) && ($curCode !== $newCode)) {
$change = true;
$token->setReceptionCode($newCode, $newText, $userId);
}
}
} while ($token = $token->getNextToken());
if ($change) {
$respTrack->refresh();
}
} | Process the data and do what must be done
Storing the changed $values is handled by the calling function.
@param \Gems_Tracker_RespondentTrack $respTrack Gems respondent track object
@param int $userId The current userId
@return void | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.