sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function isConsoleAllowed()
{
if ($this->offsetExists('console')) {
$cons = $this->offsetGet('console');
if (isset($cons['allow'])) {
return (boolean) $cons['allow'];
}
}
return false;
} | Is running GemsTracker from the console allowed
If allowed you can call index.php from the command line.
Use -h as a parameter to get more info, e.g:
<code>
php.exe -f index.php -- -f
</code>
The -- is needed because otherwise the command is interpreted
as php.exe -h.
@return string | entailment |
protected function addTableCells(\MUtil_Model_Bridge_VerticalTableBridge $bridge)
{
$HTML = \MUtil_Html::create();
$bridge->caption($this->getCaption());
$br = $HTML->br();
// ROW 0
$label = $this->model->get('gr2o_patient_nr', 'label'); // Try to read label from model...
if (empty($label)) {
$label = $this->_('Respondent nr: '); // ...but have a fall-back
}
$bridge->addItem($bridge->gr2o_patient_nr, $label);
if (! $this->currentUser->areAllFieldsMaskedWhole('grs_last_name', 'grs_first_name', 'grs_gender', 'grs_surname_prefix')) {
$bridge->addItem(
$HTML->spaced(
$bridge->itemIf('grs_last_name', array($bridge->grs_last_name, ',')),
$bridge->grs_gender,
$bridge->grs_first_name,
$bridge->grs_surname_prefix
),
$this->_('Respondent'));
}
// ROW 1
if ($this->model->has('grs_birthday') && (! $this->currentUser->isFieldMaskedWhole('grs_birthday'))) {
$bridge->addItem('grs_birthday');
}
if ($this->model->has('grs_phone_1') && (! $this->currentUser->isFieldMaskedWhole('grs_phone_1'))) {
$bridge->addItem('grs_phone_1');
}
// ROW 2
if ($this->model->has('gr2o_email') && (! $this->currentUser->isFieldMaskedWhole('gr2o_email'))) {
$bridge->addItem('gr2o_email');
}
$address = [];
if ($this->model->has('grs_address_1') && (! $this->currentUser->isFieldMaskedWhole('grs_address_1'))) {
$address[] = $bridge->grs_address_1;
$address[] = $br;
}
if ($this->model->has('grs_address_2') && (! $this->currentUser->isFieldMaskedWhole('grs_address_2'))) {
$address[] = $bridge->grs_address_2;
$address[] = $bridge->itemIf('grs_address_2', $br);
}
if ($this->model->has('grs_zipcode') && (! $this->currentUser->isFieldMaskedWhole('grs_zipcode'))) {
$address[] = $bridge->grs_zipcode;
$address[] = $bridge->itemIf('grs_zipcode', new \MUtil_Html_Raw(' '));
}
if ($this->model->has('grs_city') && (! $this->currentUser->isFieldMaskedWhole('grs_city'))) {
$address[] = $bridge->grs_city;
}
if ($address) {
$bridge->addItem($address, $this->_('Address'));
}
} | Place to set the data to display
@param \MUtil_Model_Bridge_VerticalTableBridge $bridge
@return void | entailment |
protected function _getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
{
$url = $this->_getQRCodeUrl($title, $name, $secret);
list($width, $height, $level) = $this->_getQRParams($params);
return 'https://chart.googleapis.com/chart?chs=' . $width . 'x' . $height . '&chld=' . $level . '|0&cht=qr&chl=' . $url . '';
} | Get QR-Code URL for image, from google charts.
@param string $name The person using it
@param string $secret Above code in authenticator
@param string $title
@param array $params
@return string | entailment |
protected function _getQRCodeInline($name, $secret, $title = null, $params = array())
{
$url = $this->_getQRCodeUrl($title, $name, $secret);
list($width, $height, $level) = $this->_getQRParams($params);
$renderer = new \BaconQrCode\Renderer\Image\Png();
$renderer->setWidth($width)
->setHeight($height)
->setMargin(0);
$bacon = new \BaconQrCode\Writer($renderer);
$data = $bacon->writeString($urlencoded, $encoding, \BaconQrCode\Common\ErrorCorrectionLevel::M);
return 'data:image/png;base64,' . base64_encode($data);
} | Get QR-Code URL for image, using inline data uri.
@param string $name The person using it
@param string $secret Above code in authenticator
@param string $title
@param array $params
@return string | entailment |
protected function _getQRCodeUrl($title, $name, $secret)
{
if (empty($title)) {
return 'otpauth://totp/'.rawurlencode($name).'?secret='.$secret;
} else {
return 'otpauth://totp/'.rawurlencode($title).':'.rawurlencode($name).'?secret='.$secret.'&issuer='.rawurlencode($title);
}
} | Get otpauth url
@param $title
@param $name
@param $secret
@return string | entailment |
public function addSetupFormElements(\Zend_Form $form, \Gems_User_User $user, array &$formData)
{
$name = $user->getLoginName();
$title = $this->project->getName() . ' - GemsTracker';
$params['alt'] = $this->_('QR Code');
$params['class'] = 'floatLeft';
$params['height'] = 200;
$params['width'] = 200;
$params['src'] = \MUtil_Html::raw($this->_getQRCodeGoogleUrl(
$name,
$formData['twoFactorKey'],
$title,
$params
));
// \MUtil_Echo::track($params);
$imgElement = $form->createElement('Html', 'image');
$imgElement->setLabel($this->_('Scan this QR Code'))
->setDescription($this->_('Install the Google Authenticator app on your phone and scan this code.'));
$imgElement->img($params);
$form->addElement($imgElement);
if ($user->canSaveTwoFactorKey()) {
$orElement = $form->createElement('Html', 'orelem');
$orElement->setLabel($this->_('or'));
$form->addElement($orElement);
$options = [
'label' => $this->_('Enter new authenticator code'),
'description' => $this->_('An uppercase string containing A through Z, 2 to 7 and maybe = at the end.'),
'maxlength' => 16,
'minlength' => 16,
'required' => true,
'size' => 30,
];
$keyElement = $form->createElement('Text', 'twoFactorKey', $options);
$keyElement->addFilter('StringToUpper')
->addValidator('Base32')
->addValidator('StringLength', true, ['min' => 16, 'max' => 16]);
$form->addElement($keyElement);
}
} | Add the elements to the setup form
@param \Zend_Form $form
@param \Gems_User_User $user The user to setup for
@param array $formData Current form data | entailment |
public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
{
if ($currentTimeSlice === null) {
$currentTimeSlice = floor(time() / 30);
}
if (strlen($code) != 6) {
return false;
}
for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
if ($this->_timingSafeEquals($calculatedCode, $code)) {
return true;
}
}
return false;
} | Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
@param string $secret
@param string $code
@param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
@param int|null $currentTimeSlice time slice if we want use other that time()
@return bool | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$onOffFields = array('gr2t_track_info', 'gto_round_description', 'grc_description');
foreach ($onOffFields as $field) {
if (! (isset($this->formData[$field]) && $this->formData[$field])) {
$model->set($field, 'elementClass', 'None');
}
}
parent::addFormElements($bridge, $model);
} | Adds elements from the model to the bridge that creates the form.
Overrule this function to add different elements to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function initItems()
{
if (is_null($this->_items)) {
$this->_items = array_merge(
array(
'gto_id_respondent',
'gr2o_patient_nr',
'respondent_name',
'gto_id_organization',
'gtr_track_name',
'gr2t_track_info',
'gto_round_description',
'gsu_survey_name',
'ggp_name',
'gto_valid_from_manual',
'gto_valid_from',
'gto_valid_until_manual',
'gto_valid_until',
'gto_comment',
'gto_mail_sent_date',
'gto_completion_time',
'grc_description',
'gto_changed',
'assigned_by',
),
$this->getModel()->getMeta(\MUtil_Model_Type_ChangeTracker::HIDDEN_FIELDS, array())
);
if (! $this->createData) {
array_unshift($this->_items, 'gto_id_token');
}
}
} | Initialize the _items variable to hold all items from the model | entailment |
public function saveData()
{
$model = $this->getModel();
if ($this->formData['gto_valid_until']) {
// Make sure date based units are valid until the end of the day.
$date = new \MUtil_Date(
$this->formData['gto_valid_until'],
$model->get('gto_valid_until', 'dateFormat')
);
$date->setTimeToDayEnd();
$this->formData['gto_valid_until'] = $date;
}
// Save the token using the model
parent::saveData();
// $this->token->setValidFrom($this->formData['gto_valid_from'], $this->formData['gto_valid_until'], $this->loader->getCurrentUser()->getUserId());
// \MUtil_Echo::track($this->formData);
// Refresh (NOT UPDATE!) token with current form data
$updateData['gto_valid_from'] = $this->formData['gto_valid_from'];
$updateData['gto_valid_from_manual'] = $this->formData['gto_valid_from_manual'];
$updateData['gto_valid_until'] = $this->formData['gto_valid_until'];
$updateData['gto_valid_until_manual'] = $this->formData['gto_valid_until_manual'];
$updateData['gto_comment'] = $this->formData['gto_comment'];
$this->token->refresh($updateData);
$respTrack = $this->token->getRespondentTrack();
$userId = $this->loader->getCurrentUser()->getUserId();
$changed = $respTrack->checkTrackTokens($userId, $this->token);
if ($changed) {
$this->addMessage(sprintf($this->plural(
'%d token changed by recalculation.',
'%d tokens changed by recalculation.',
$changed
), $changed));
}
} | Hook containing the actual save code.
Call's afterSave() for user interaction.
@see afterSave() | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
if (! $bridge->getForm() instanceof \Gems_TabForm) {
parent::addFormElements($bridge, $model);
return;
}
//Get all elements in the model if not already done
$this->initItems();
// Add 'tooltip' to the allowed displayoptions
$displayOptions = $bridge->getAllowedOptions(\MUtil_Model_Bridge_FormBridge::DISPLAY_OPTIONS);
if (!array_search('tooltip', $displayOptions)) {
$displayOptions[] = 'tooltip';
$bridge->setAllowedOptions(\MUtil_Model_Bridge_FormBridge::DISPLAY_OPTIONS, $displayOptions);
}
$tab = 0;
$group = 0;
$oldTab = null;
// \MUtil_Echo::track($model->getItemsOrdered());
foreach ($model->getItemsOrdered() as $name) {
// Get all options at once
$modelOptions = $model->get($name);
$tabName = $model->get($name, 'tab');
if ($tabName && ($tabName !== $oldTab)) {
if (isset($modelOptions['elementClass']) && ('tab' == strtolower($modelOptions['elementClass']))) {
$bridge->addTab('tab' . $tab, $modelOptions + array('value' => $tabName));
} else {
$bridge->addTab('tab' . $tab, 'value', $tabName);
}
$oldTab = $tabName;
$tab++;
}
if ($model->has($name, 'label') || $model->has($name, 'elementClass')) {
$bridge->add($name);
if ($theName = $model->get($name, 'startGroup')) {
//We start a new group here!
$groupElements = array();
$groupElements[] = $name;
$groupName = $theName;
} elseif ($theName = $model->get($name, 'endGroup')) {
//Ok, last element define the group
$groupElements[] = $name;
$bridge->addDisplayGroup('grp_' . $groupElements[0], $groupElements,
'description', $groupName,
'showLabels', ($theName == 'showLabels'),
'class', 'grp' . $group);
$group++;
unset($groupElements);
unset($groupName);
} else {
//If we are in a group, add the elements to the group
if (isset($groupElements)) {
$groupElements[] = $name;
}
}
} else {
$bridge->addHidden($name);
}
unset($this->_items[$name]);
}
} | Adds elements from the model to the bridge that creates the form.
Overrule this function to add different elements to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
public function afterRegistry()
{
parent::afterRegistry();
if ($this->project instanceof \Gems_Project_ProjectSettings) {
$this->useCsrf = $this->project->useCsrfCheck();
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function afterSave($changed)
{
parent::afterSave($changed);
if ($changed) {
$this->accesslog->logChange($this->request, null, $this->formData);
}
} | 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 |
public function beforeDisplay()
{
if ($this->_form instanceof \Gems_TabForm) {
if ($links = $this->getMenuList()) {
$linkContainer = \MUtil_Html::create()->div(array('class' => 'element-container-labelless'));
$linkContainer[] = $links;
$element = $this->_form->createElement('html', 'formLinks');
$element->setValue($linkContainer)
->setOrder(999)
->removeDecorator('HtmlTag')
->removeDecorator('Label')
->removeDecorator('DtDdWrapper');
$this->_form->resetContext();
$this->_form->addElement($element);
if (is_null($this->_form->getDisplayGroup(\Gems_TabForm::GROUP_OTHER))) {
$this->_form->addDisplayGroup(array($element), \Gems_TabForm::GROUP_OTHER);
} else {
$this->_form->getDisplayGroup(\Gems_TabForm::GROUP_OTHER)->addElement($element);
}
}
} else {
if (\MUtil_Bootstrap::enabled() !== true) {
$table = new \MUtil_Html_TableElement(array('class' => $this->class));
$table->setAsFormLayout($this->_form, true, true);
// There is only one row with formLayout, so all in output fields get class.
$table['tbody'][0][0]->appendAttrib('class', $this->labelClass);
if ($links = $this->getMenuList()) {
$table->tf(); // Add empty cell, no label
$table->tf($links);
}
} elseif($links = $this->getMenuList()) {
$element = $this->_form->createElement('html', 'menuLinks');
$element->setValue($links);
$element->setOrder(999);
$this->_form->addElement($element);
}
}
} | Perform some actions on the form, right before it is displayed but already populated
Here we add the table display to the form.
@return \Zend_Form | entailment |
protected function createForm($options = null)
{
if ($this->useTabbedForm) {
return new \Gems_TabForm($options);
}
if (\MUtil_Bootstrap::enabled()) {
if (!isset($options['class'])) {
$options['class'] = 'form-horizontal';
}
if (!isset($options['role'])) {
$options['role'] = 'form';
}
}
return new \Gems_Form($options);
} | Creates an empty form. Allows overruling in sub-classes.
@param mixed $options
@return \Zend_Form | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$htmlDiv = \MUtil_Html::div();
$title = $this->getTitle();
if ($title) {
$htmlDiv->h3($title, array('class' => 'title'));
}
$form = parent::getHtmlOutput($view);
$htmlDiv[] = $form;
return $htmlDiv;
} | 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 getMenuList()
{
$links = $this->menu->getMenuList();
$links->addParameterSources($this->request, $this->menu->getParameterSource());
$links->addCurrentParent($this->_('Cancel'));
if ($this->menuShowSiblings) {
$links->addCurrentSiblings();
}
if ($this->menuShowChildren) {
$links->addCurrentChildren();
}
return $links;
} | overrule to add your own buttons.
@return \Gems_Menu_MenuList | entailment |
protected function getTitle()
{
if ($this->formTitle) {
return $this->formTitle;
} elseif ($this->createData) {
return sprintf($this->_('New %s...'), $this->getTopic());
} else {
return sprintf($this->_('Edit %s'), $this->getTopic());
}
} | Retrieve the header title to display
@return string | entailment |
public function getTopic($count = 1)
{
if (is_callable($this->topicCallable)) {
return call_user_func($this->topicCallable, $count);
} else {
return parent::getTopic($count);
}
} | Helper function to allow generalized statements about the items in the model to used specific item names.
@param int $count
@return $string | entailment |
protected function setAfterSaveRoute()
{
parent::setAfterSaveRoute();
if (is_array($this->afterSaveRouteUrl)) {
// Make sure controller is set
if (!array_key_exists('controller', $this->afterSaveRouteUrl)) {
$this->afterSaveRouteUrl['controller'] = $this->request->getControllerName();
}
// Search array for menu item
$find['controller'] = $this->afterSaveRouteUrl['controller'];
$find['action'] = $this->afterSaveRouteUrl['action'];
// If not allowed, redirect to index
if (null == $this->menu->find($find)) {
$this->afterSaveRouteUrl['action'] = 'index';
$this->resetRoute = true;
}
}
// \MUtil_Echo::track($this->routeAction, $this->resetRoute);
return $this;
} | If menu item does not exist or is not allowed, redirect to index
@return \Gems_Snippets_ModelFormSnippetAbstract | entailment |
public function isValid($value, $context = array())
{
$this->_report = $this->_user->reportPasswordWeakness($value, true);
foreach ($this->_report as &$report) {
$report = ucfirst($report) . '.';
}
// \MUtil_Echo::track($value, $this->_report);
return ! (boolean) $this->_report;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@param mixed $content
@return boolean
@throws \Zend_Validate_Exception If validation of $value is impossible | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
$user = $this->loader->getCurrentUser();
if ($user->hasPrivilege('pr.respondent.select-on-track')) {
$tracks = $this->searchData['__active_tracks'];
$masks['show_all'] = $this->_('(all)');
$masks['show_without_track'] = $this->_('(no track)');
if (count($tracks) > 1) {
$masks['show_with_track'] = $this->_('(with track)');
}
if (count($tracks) > 1) {
$elements['gr2t_id_track'] = $this->_createSelectElement('gr2t_id_track', $masks + $tracks);
} else {
$element = $this->_createRadioElement('gr2t_id_track', $masks + $tracks);
$element->setSeparator(' ');
$elements['gr2t_id_track'] = $element;
}
$lineBreak = true;
} else {
$lineBreak = false;
}
if ($user->hasPrivilege('pr.respondent.show-deleted')) {
$elements['grc_success'] = $this->_createCheckboxElement('grc_success', $this->_('Show active'));
}
if ($this->model->isMultiOrganization()) {
$element = $this->_createSelectElement(
\MUtil_Model::REQUEST_ID2,
$user->getRespondentOrganizations(),
$this->_('(all organizations)')
);
if ($lineBreak) {
$element->setLabel($this->_('Organization'))
->setAttrib('onchange', 'this.form.submit();');
$elements[] = \MUtil_Html::create('br');
}
$elements[\MUtil_Model::REQUEST_ID2] = $element;
}
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 _fillAttributeMap(\Gems_Tracker_Token $token)
{
$values = parent::_fillAttributeMap($token);
// Not really an attribute, but it is the best place to set this
$values['usesleft'] = $token->isCompleted() ? 0 : 1;
return $values;
} | Returns a list of field names that should be set in a newly inserted token.
Added the usesleft value.
@param \Gems_Tracker_Token $token
@return array Of fieldname => value type | entailment |
protected function _checkTokenTable(array $tokenTable)
{
$missingFields = parent::_checkTokenTable($tokenTable);
if (! isset($tokenTable['usesleft'])) {
$missingFields['usesleft'] = "ADD `usesleft` INT( 11 ) NULL DEFAULT '1' AFTER `completed`";
}
return $missingFields;
} | Check a token table for any changes needed by this version.
@param array $tokenTable
@return array Fieldname => change field commands | entailment |
public function _checkTrackCount($userId)
{
$sqlCount = 'SELECT COUNT(*) AS count,
SUM(CASE WHEN gto_completion_time IS NULL THEN 0 ELSE 1 END) AS completed
FROM gems__tokens INNER JOIN
gems__reception_codes ON gto_reception_code = grc_id_reception_code AND grc_success = 1
WHERE gto_id_respondent_track = ?';
$counts = $this->db->fetchRow($sqlCount, $this->_respTrackId);
if (! $counts) {
$counts = array('count' => 0, 'completed' => 0);
}
$values['gr2t_count'] = intval($counts['count']);
$values['gr2t_completed'] = intval($counts['completed']);
if (! $this->_respTrackData['gr2t_end_date_manual']) {
$values['gr2t_end_date'] = $this->calculateEndDate();
}
if ($values['gr2t_count'] == $values['gr2t_completed']) {
if (null === $this->_respTrackData['gr2t_end_date']) {
$now = new \MUtil_Date();
$values['gr2t_end_date'] = $now->toString(\Gems_Tracker::DB_DATETIME_FORMAT);
}
//Handle TrackCompletionEvent, send only changed fields in $values array
$this->handleTrackCompletion($values, $userId);
}
// Remove unchanged values
$this->tracker->filterChangesOnly($this->_respTrackData, $values);
return $this->_updateTrack($values, $userId);
} | Check this respondent track for the number of tokens completed / to do
@param int $userId Id of the user who takes the action (for logging)
@return int 1 if the track was changed by this code | entailment |
private function _ensureFieldData($reload = false)
{
if ($this->_respTrackData && (null === $this->_fieldData) || $reload) {
$this->_fieldData = $this->getTrackEngine()->getFieldsData($this->_respTrackId);
$this->_fixFieldData();
}
} | Makes sure the fieldData is in $this->_fieldData
@param boolean $reload Optional parameter to force reload. | entailment |
public function _fixFieldData()
{
$fieldMap = $this->getTrackEngine()->getFieldCodes();
foreach ($this->_fieldData as $key => $value) {
if (isset($fieldMap[$key])) {
// The old name remains in the data set of course,
// using the code is a second occurence
$this->_fieldData[$fieldMap[$key]] = $value;
}
}
} | Adds the code fields to the fieldData array | entailment |
protected function _ensureRespondentData()
{
if (! isset($this->_respTrackData['grs_id_user'], $this->_respTrackData['gr2o_id_user'], $this->_respTrackData['gco_code'])) {
$sql = "SELECT *
FROM gems__respondents INNER JOIN
gems__respondent2org ON grs_id_user = gr2o_id_user INNER JOIN
gems__consents ON gr2o_consent = gco_description
WHERE gr2o_id_user = ? AND gr2o_id_organization = ? LIMIT 1";
$respId = $this->_respTrackData['gr2t_id_user'];
$orgId = $this->_respTrackData['gr2t_id_organization'];
if ($row = $this->db->fetchRow($sql, array($respId, $orgId))) {
$this->_respTrackData = $this->_respTrackData + $row;
} else {
$trackId = $this->_respTrackId;
throw new \Gems_Exception("Respondent data missing for track $trackId.");
}
}
} | Makes sure the respondent data is part of the $this->_respTrackData | entailment |
protected function _ensureRounds($reload = false)
{
if ((null === $this->_rounds) || $reload) {
$rounds = $this->getTrackEngine()->getRoundModel(true, 'index')->load(array('gro_id_track'=>$this->getTrackId()));
$this->_rounds = array();
foreach($rounds as $round) {
$this->_rounds[$round['gro_id_round']] = $round;
}
}
} | Makes sure the rounds info is loaded
@param boolean $reload | entailment |
protected function _ensureTrackData()
{
if (! isset($this->_respTrackData['gtr_code'], $this->_respTrackData['gtr_name'])) {
$select = $this->db->select();
$select->from('gems__tracks')
->where('gtr_id_track = ?', $this->_respTrackData['gr2t_id_track']);
if ($trackData = $this->db->fetchRow($select)) {
$this->_respTrackData = $this->_respTrackData + $trackData;
} else {
$trackId = $this->_respTrackId;
throw new \Gems_Exception("Track data missing for respondent track $trackId.");
}
}
} | Makes sure the track data is part of the $this->_respTrackData | entailment |
protected function _mergeFieldValues(array $newFieldData, array $oldFieldData, \Gems_Tracker_Engine_TrackEngineInterface $trackEngine)
{
$fieldMap = $trackEngine->getFieldsDefinition()->getFieldCodes();
$output = array();
foreach ($fieldMap as $key => $code) {
if ($code) {
if (array_key_exists($code, $newFieldData)) {
$output[$key] = $newFieldData[$code];
$output[$code] = $newFieldData[$code];
} elseif (array_key_exists($key, $newFieldData)) {
$output[$key] = $newFieldData[$key];
$output[$code] = $newFieldData[$key];
} elseif (isset($oldFieldData[$code])) {
$output[$key] = $oldFieldData[$code];
$output[$code] = $oldFieldData[$code];
} elseif (isset($oldFieldData[$key])) {
$output[$key] = $oldFieldData[$key];
$output[$code] = $oldFieldData[$key];
} else {
$output[$key] = null;
$output[$code] = null;
}
} else {
if (array_key_exists($key, $newFieldData)) {
$output[$key] = $newFieldData[$key];
} elseif (isset($oldFieldData[$key])) {
$output[$key] = $oldFieldData[$key];
} else {
$output[$key] = null;
}
}
}
return $output;
} | Processes the field values and returns the new complete field data
@param array $newFieldData The new field values, may be partial, field set by code overwrite field set by key
@param array $oldFieldData The old field values
@param \Gems_Tracker_Engine_TrackEngineInterface $trackEngine
@return array The processed data in the format key1 => val1, code1 => val1, key2 => val2 | entailment |
protected function _updateTrack(array $values, $userId = null)
{
if (null === $userId) {
$userId = $this->currentUser->getUserId();
}
// \MUtil_Echo::track($values);
if ($this->tracker->filterChangesOnly($this->_respTrackData, $values)) {
$where = $this->db->quoteInto('gr2t_id_respondent_track = ?', $this->_respTrackId);
if (\Gems_Tracker::$verbose) {
$echo = '';
foreach ($values as $key => $val) {
$echo .= $key . ': ' . $this->_respTrackData[$key] . ' => ' . $val . "\n";
}
\MUtil_Echo::r($echo, 'Updated values for ' . $this->_respTrackId);
}
if (! isset($values['gr2t_changed'])) {
$values['gr2t_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
}
if (! isset($values['gr2t_changed_by'])) {
$values['gr2t_changed_by'] = $userId;
}
$this->_respTrackData = $values + $this->_respTrackData;
// \MUtil_Echo::track($values);
// return 1;
return $this->db->update('gems__respondent2track', $values, $where);
} else {
return 0;
}
} | Save the values if any have been changed
@param array $values
@param int $userId
@return int | entailment |
public function addSurveyToTrack($surveyId, $surveyData, $userId, $checkTrack = true )
{
//Do something to get a token and add it
$tokenLibrary = $this->tracker->getTokenLibrary();
//Now make sure the data to add is correct:
$surveyData['gto_id_respondent_track'] = $this->_respTrackId;
$surveyData['gto_id_organization'] = $this->_respTrackData['gr2t_id_organization'];
$surveyData['gto_id_track'] = $this->_respTrackData['gr2t_id_track'];
$surveyData['gto_id_respondent'] = $this->_respTrackData['gr2t_id_user'];
$surveyData['gto_id_survey'] = $surveyId;
if (! isset($surveyData['gto_id_round'])) {
$surveyData['gto_id_round'] = 0;
}
$tokenId = $tokenLibrary->createToken($surveyData, $userId);
if ($checkTrack === true) {
//Now refresh the track to include the survey we just added (easiest way as order may change)
$this->getTokens(true);
$this->checkTrackTokens($userId, $this->_tokens[$tokenId]);
// Update the track counter
//$this->_checkTrackCount($userId);
return $this->_tokens[$tokenId];
}
return $this->tracker->getToken($tokenId);
} | Add a one-off survey to the existing track.
@param type $surveyId the gsu_id of the survey to add
@param type $surveyData
@param int $userId
@param boolean $checkTrack Should the track be checked? Set to false when adding more then one and check manually
@return \Gems_Tracker_Token | entailment |
public function addTokenToTrack(\Gems_Tracker_Token $token, $tokenData, $userId, $checkTrack = true)
{
//Now make sure the data to add is correct:
$tokenData['gto_id_respondent_track'] = $this->_respTrackId;
$tokenData['gto_id_organization'] = $this->_respTrackData['gr2t_id_organization'];
$tokenData['gto_id_track'] = $this->_respTrackData['gr2t_id_track'];
$tokenData['gto_id_respondent'] = $this->_respTrackData['gr2t_id_user'];
$tokenData['gto_changed'] = new \MUtil_Db_Expr_CurrentTimestamp();
$tokenData['gto_changed_by'] = $userId;
$where = $this->db->quoteInto('gto_id_token = ?', $token->getTokenId());
$this->db->update('gems__tokens', $tokenData, $where);
$token->refresh();
if ($checkTrack === true) {
//Now refresh the track to include the survey we just added (easiest way as order may change)
$this->getTokens(true);
$this->checkTrackTokens($userId, $token);
// Update the track counter
//$this->_checkTrackCount($userId);
}
return $token;
} | Add a one-off survey to the existing track.
@param type $surveyId the gsu_id of the survey to add
@param type $surveyData
@param int $userId
@param boolean $checkTrack Should the track be checked? Set to false when adding more then one and check manually
@return \Gems_Tracker_Token | entailment |
public function applyToMenuSource(\Gems_Menu_ParameterSource $source)
{
$source->setRespondentTrackId($this->_respTrackId);
$source->offsetSet(
'gr2t_active',
(isset($this->_respTrackData['gr2t_active']) ? $this->_respTrackData['gr2t_active'] : 0)
);
$source->offsetSet('can_edit', $this->hasSuccesCode() ? 1 : 0);
$source->offsetSet('track_can_be_created', 0);
$this->getRespondent()->applyToMenuSource($source);
$this->getTrackEngine()->applyToMenuSource($source);
return $this;
} | Set menu parameters from this token
@param \Gems_Menu_ParameterSource $source
@return \Gems_Tracker_RespondentTrack (continuation pattern) | entailment |
public function assignTokensToRelations()
{
// Find out if we have relation fields and return when none exists in this track
$relationFields = $this->getTrackEngine()->getFieldsOfType('relation');
if (empty($relationFields)) {
return 0;
}
// Check if we have a respondent relation id (grr_id) in the track fields
// and assign the token to the correct relation or leave open when no
// relation is defined.
$this->_ensureRounds();
$relationFields = $this->getFieldData();
$fieldPrefix = \Gems\Tracker\Model\FieldMaintenanceModel::FIELDS_NAME . \Gems\Tracker\Engine\FieldsDefinition::FIELD_KEY_SEPARATOR;
$changes = 0;
foreach ($this->getTokens() as $token) {
/* @var $token Gems_Tracker_Token */
if (!$token->isCompleted() && $token->getReceptionCode()->isSuccess()) {
$roundId = $token->getRoundId();
if (!array_key_exists($roundId, $this->_rounds)) {
// If not a current round for this track, do check the round when it still exists
$round = $this->getTrackEngine()->getRoundModel(true, 'index')->loadFirst(array('gro_id_round' => $roundId));
} else {
$round = $this->_rounds[$roundId];
}
$relationFieldId = null;
$relationId = null;
// Read from the round
if (!empty($round) && $round['gro_id_track'] == $this->getTrackId() && $round['gro_active'] == 1) {
if ($round['gro_id_relationfield'] > 0) {
$relationFieldId = $round['gro_id_relationfield'];
}
} else {
// Try to read from token, as this is a token without a round
$relationFieldId = $token->getRelationFieldId();
}
if ($relationFieldId>0) {
$fieldKey = $fieldPrefix . $relationFieldId;
if (isset($relationFields[$fieldKey])) {
$relationId = (int) $relationFields[$fieldKey];
} else {
$relationId = -1 * $relationFieldId;
}
}
$changes = $changes + $token->assignTo($relationId, $relationFieldId);
}
}
if (MUtil_Model::$verbose && $changes > 0) {
MUtil_Echo::r(sprintf('%s tokens changed due to changes in respondent relation assignments.', $changes));
}
return $changes;
} | Assign the tokens to the correct relation
Only surveys that have not yet been answered will be assigned to the correct relation.
@return int Number of changes tokens | entailment |
public function calculateEndDate()
{
// Exclude the tokens whose end date is calculated from the track end date
$excludeWheres[] = sprintf(
"gro_valid_for_source = '%s' AND gro_valid_for_field = 'gr2t_end_date'",
\Gems_Tracker_Engine_StepEngineAbstract::RESPONDENT_TRACK_TABLE
);
// Exclude the tokens whose start date is calculated from the track end date, while the
// end date is calculated using that same start date
$excludeWheres[] = sprintf(
"gro_valid_after_source = '%s' AND gro_valid_after_field = 'gr2t_end_date' AND
gro_id_round = gro_valid_for_id AND
gro_valid_for_source = '%s' AND gro_valid_for_field = 'gto_valid_from'",
\Gems_Tracker_Engine_StepEngineAbstract::RESPONDENT_TRACK_TABLE,
\Gems_Tracker_Engine_StepEngineAbstract::TOKEN_TABLE
);
// In future we may want to add some nesting to this, e.g. tokens with an end date calculated
// from another token whose... for the time being users should use the end date directly in
// each token, otherwise the end date will not be calculated
$maxExpression = "
CASE
WHEN SUM(
CASE WHEN COALESCE(gto_completion_time, gto_valid_until) IS NULL THEN 1 ELSE 0 END
) > 0
THEN NULL
ELSE MAX(COALESCE(gto_completion_time, gto_valid_until))
END as enddate";
$tokenSelect = $this->tracker->getTokenSelect(array(new \Zend_Db_Expr($maxExpression)));
$tokenSelect->andReceptionCodes(array())
->andRounds(array())
->forRespondentTrack($this->_respTrackId)
->onlySucces();
foreach ($excludeWheres as $where) {
$tokenSelect->forWhere('NOT (' . $where . ')');
}
$endDate = $tokenSelect->fetchOne();
// \MUtil_Echo::track($endDate, $tokenSelect->getSelect()->__toString());
if (false === $endDate) {
return null;;
} else {
return $endDate;
}
} | Calculates the track end date
The end date can be calculated when:
- all active tokens have a completion date
- or all active tokens have a valid until date
- or the end date of the tokens is calculated using the end date
You can overrule this calculation at the project level.
@return string or null | entailment |
public function checkRegistryRequestsAnswers()
{
if ($this->_respTrackData && $this->currentUser instanceof \Gems_User_User) {
$this->_respTrackData = $this->currentUser->applyGroupMask($this->_respTrackData);
} else {
if ($this->db instanceof \Zend_Db_Adapter_Abstract) {
$this->refresh();
}
}
return (boolean) $this->_respTrackData;
} | 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 checkTrackTokens($userId, \Gems_Tracker_Token $fromToken = null, \Gems_Tracker_Token $skipToken = null)
{
// Execute any defined functions
$count = $this->handleTrackCalculation($userId);
$engine = $this->getTrackEngine();
$this->db->beginTransaction();
// Check for validFrom and validUntil dates that have changed.
if ($fromToken) {
$count += $engine->checkTokensFrom($this, $fromToken, $userId, $skipToken);
} elseif ($this->_checkStart) {
$count += $engine->checkTokensFrom($this, $this->_checkStart, $userId);
} else {
$count += $engine->checkTokensFromStart($this, $userId);
}
$this->db->commit();
// Update token completion count and possible enddate
$this->_checkTrackCount($userId);
return $count;
} | Check this respondent track for changes to the tokens
@param int $userId Id of the user who takes the action (for logging)
@param \Gems_Tracker_Token $fromToken Optional token to start from
@param \Gems_Tracker_Token $skipToken Optional token to skip in the recalculation when $fromToken is used
@return int The number of tokens changed by this code | entailment |
public function getActiveRoundToken($roundId, \Gems_Tracker_Token $token = null)
{
if ((null !== $token) && $token->hasSuccesCode()) {
// Cache the token
//
// WARNING: This may cause bugs for tracks where two tokens exists
// with this roundId and a success reception code, but this does speed
// this function with track engines where that should not occur.
$this->_activeTokens[$token->getRoundId()] = $token;
}
// Nothing to find
if (! $roundId) {
return null;
}
// Use array_key_exists since there may not be a valid round
if (! array_key_exists($roundId, $this->_activeTokens)) {
$tokenSelect = $this->tracker->getTokenSelect();
$tokenSelect->andReceptionCodes()
->forRespondentTrack($this->_respTrackId)
->forRound($roundId)
->onlySucces();
// \MUtil_Echo::track($tokenSelect->__toString());
if ($tokenData = $tokenSelect->fetchRow()) {
$this->_activeTokens[$roundId] = $this->tracker->getToken($tokenData);
} else {
$this->_activeTokens[$roundId] = null;
}
}
return $this->_activeTokens[$roundId];
} | Returns a token with a success reception code for this round or null
@param type $roundId Gems round id
@param \Gems_Tracker_Token $token Optional token to add as a round (for speed optimization)
@return \Gems_Tracker_Token | entailment |
public function getCodeFields()
{
$fieldDef = $this->getTrackEngine()->getFieldsDefinition();
$codes = $this->tracker->getAllCodeFields();
$results = array_fill_keys($codes, null);
$this->_ensureFieldData();
foreach ($this->_fieldData as $id => $value) {
if (!isset($codes[$id])) {
continue;
}
$fieldCode = $codes[$id];
$results[$fieldCode] = $value;
$field = $fieldDef->getFieldByCode($fieldCode);
if (!is_null($field)) {
$results[$fieldCode] = $field->calculateFieldInfo($value, $this->_fieldData);
}
}
return $results;
} | Return all possible code fields with the values filled for those that exist for this track,
optionally with a prefix
@return array code => value | entailment |
public function getCurrentRound()
{
$isStop = false;
$today = new \Zend_Date();
$tokens = $this->getTokens();
$stop = $this->util->getReceptionCodeLibrary()->getStopString();
foreach ($tokens as $token) {
$validUntil = $token->getValidUntil();
if (! empty($validUntil) && $validUntil->isEarlier($today)) {
continue;
}
if ($token->isCompleted()) {
continue;
}
$code = $token->getReceptionCode();
if (! $code->isSuccess()) {
if ($code->getCode() === $stop) {
$isStop = true;
}
continue;
}
return $token->getRoundDescription();
}
if ($isStop) {
return $this->translate->_('Track stopped');
}
return $this->translate->_('Track completed');
} | The round description of the first round that has not been answered.
@return string Round description or Stopped/Completed if not found. | entailment |
public function getFirstToken()
{
if (! $this->_firstToken) {
if (! $this->_tokens) {
//No cache yet, but we might need all tokens later
$this->getTokens();
}
$this->_firstToken = reset($this->_tokens);
}
return $this->_firstToken;
} | Returns the first token in this track
@return \Gems_Tracker_Token | entailment |
public function getRespondentLanguage()
{
if (! isset($this->_respTrackData['grs_iso_lang'])) {
$this->_ensureRespondentData();
if (! isset($this->_respTrackData['grs_iso_lang'])) {
// Still not set in a project? The it is single language
$this->_respTrackData['grs_iso_lang'] = $this->locale->getLanguage();
}
}
return $this->_respTrackData['grs_iso_lang'];
} | Return the default language for the respondent
@return string Two letter language code | entailment |
public function getRespondentName()
{
if (! isset($this->_respTrackData['grs_first_name'], $this->_respTrackData['grs_last_name'])) {
$this->_ensureRespondentData();
}
return trim($this->_respTrackData['grs_first_name'] . ' ' . $this->_respTrackData['grs_surname_prefix']) . ' ' . $this->_respTrackData['grs_last_name'];
} | Return the name of the respondent
@return string The respondents name | entailment |
public function getRoundAfterAppointmentId($roundId)
{
$this->_ensureFieldData();
$this->_ensureRounds();
if (isset($this->_rounds[$roundId])) {
$round = $this->_rounds[$roundId];
if (isset($round['gro_valid_after_source'], $round['gro_valid_after_field']) &&
('app' === $round['gro_valid_after_source'])) {
if (isset($this->_fieldData[$round['gro_valid_after_field']])) {
return $this->_fieldData[$round['gro_valid_after_field']];
} else {
return null;
}
}
}
return false;
} | Return the appointment (if any) linked to the valid after setting of given roundId
@param int $roundId
@return int | null | false False when RoundId not found or not an appointment otherwise appointment id or null when not set | entailment |
public function getRoundCode($roundId)
{
$this->_ensureRounds();
$roundCode = null;
if (array_key_exists($roundId, $this->_rounds) && array_key_exists('gro_code', $this->_rounds[$roundId])) {
$roundCode = $this->_rounds[$roundId]['gro_code'];
}
return $roundCode;
} | Return the round code for a given roundId
@param int $roundId
@return string|null Null when RoundId not found | entailment |
public function getTokens($refresh = false)
{
if (! $this->_tokens || $refresh) {
if ($refresh) {
$this->_firstToken = null;
}
$this->_tokens = array();
$this->_activeTokens = array();
$tokenSelect = $this->tracker->getTokenSelect();
$tokenSelect->andReceptionCodes()
->forRespondentTrack($this->_respTrackId);
$tokenRows = $tokenSelect->fetchAll();
$prevToken = null;
foreach ($tokenRows as $tokenData) {
$token = $this->tracker->getToken($tokenData);
$this->_tokens[$token->getTokenId()] = $token;
// While we are busy, set this
if ($token->hasSuccesCode()) {
$this->_activeTokens[$token->getRoundId()] = $token;
}
// Link the tokens
if ($prevToken) {
$prevToken->setNextToken($token);
}
$prevToken = $token;
}
}
return $this->_tokens;
} | Returns all the tokens in this track
@param boolean $refresh When true, always reload
@return \Gems_Tracker_Token[] | entailment |
public function handleBeforeFieldUpdate(array $fieldData)
{
static $running = array();
// Process any events
$trackEngine = $this->getTrackEngine();
if (! $trackEngine) {
return array();
}
$event = $trackEngine->getFieldBeforeUpdateEvent();
if (! $event) {
return array();
}
if (isset($running[$this->_respTrackId])) {
throw new \Gems_Exception(sprintf(
"Nested calls to '%s' track before field update event are not allowed.",
$trackEngine->getName()
));
}
$running[$this->_respTrackId] = true;
$output = $event->prepareFieldUpdate($fieldData, $this);
unset($running[$this->_respTrackId]);
return $output;
} | Find out if there are before field update events and delegate to the event if needed
@param array $fieldData fieldname => value + codename => value
@return array Of changed fields. Codename using items overwrite any key using items | entailment |
public function handleFieldUpdate()
{
static $running = array();
// Process any events
$trackEngine = $this->getTrackEngine();
if (! $trackEngine) {
return;
}
$event = $trackEngine->getFieldUpdateEvent();
if (! $event) {
return;
}
if (isset($running[$this->_respTrackId])) {
throw new \Gems_Exception(sprintf(
"Nested calls to '%s' track after field update event are not allowed.",
$trackEngine->getName()
));
}
$running[$this->_respTrackId] = true;
$event->processFieldUpdate($this, $this->currentUser->getUserId());
unset($running[$this->_respTrackId]);
} | Find out if there are field update events and delegate to the event if needed
@return void | entailment |
public function handleTrackCalculation($userId)
{
// Process any events
$trackEngine = $this->getTrackEngine();
// Places here instead of only in handle field update so it will run on new tracks too
$this->assignTokensToRelations();
if ($event = $trackEngine->getTrackCalculationEvent()) {
return $event->processTrackCalculation($this, $userId);
}
return 0;
} | Find out if there are track calculation events and delegate to the event if needed
@param int $userId | entailment |
public function handleTrackCompletion(&$values, $userId)
{
// Process any events
$trackEngine = $this->getTrackEngine();
if ($event = $trackEngine->getTrackCompletionEvent()) {
$event->processTrackCompletion($this, $values, $userId);
}
} | Find out if there are track completion events and delegate to the event if needed
@param array $values The values changed before entering this event
@param int $userId | entailment |
public function isOpen()
{
if (isset($this->_respTrackData['gr2t_count'], $this->_respTrackData['gr2t_completed'])) {
return $this->_respTrackData['gr2t_count'] > $this->_respTrackData['gr2t_completed'];
}
return true;
} | Are there still unanswered rounds
@return boolean | entailment |
public function processFieldsBeforeSave(array $newFieldData)
{
$trackEngine = $this->getTrackEngine();
if (! $trackEngine) {
return $newFieldData;
}
$step1Data = $this->_mergeFieldValues($newFieldData, $this->getFieldData(), $trackEngine);
$step2Data = $trackEngine->getFieldsDefinition()->processBeforeSave($step1Data, $this->_respTrackData);
$step3Data = $this->handleBeforeFieldUpdate($this->_mergeFieldValues($step2Data, $step1Data, $trackEngine));
if ($step3Data) {
return $this->_mergeFieldValues($step3Data, $step2Data, $trackEngine);
} else {
return $step2Data;
}
} | Processes the field values and and changes them as required
@param array $newFieldData The new field values, may be partial, field set by code overwrite field set by key
@return array The processed data in the format key1 => val1, code1 => val1, key2 => val2 | entailment |
public function recalculateFields(&$fieldsChanged = false)
{
$fieldDef = $this->getTrackEngine()->getFieldsDefinition();
$this->_ensureFieldData();
$this->_fieldData = $this->processFieldsBeforeSave($this->_fieldData, $this->_respTrackData);
$fieldsChanged = $fieldDef->changed;
$changes = $fieldDef->saveFields($this->_respTrackId, $this->_fieldData);
$fieldsChanged = (boolean) $changes;
$this->handleFieldUpdate();
$info = $fieldDef->calculateFieldsInfo($this->_fieldData);
if ($info != $this->_respTrackData['gr2t_track_info']) {
$this->_updateTrack(array('gr2t_track_info' => $info), $this->currentUser->getUserId());
}
// We always update the fields, but recalculate the token dates
// only when this respondent track is still running.
if ($this->hasSuccesCode() && $this->isOpen()) {
return $this->checkTrackTokens($this->currentUser->getUserId());
}
} | Refresh the fields (to reflect any changed appointments)
@param boolean $trackEngine Set to true when changed
@return int The number of tokens changed as a result of this update | entailment |
public function restoreTokens(\Gems_Util_ReceptionCode $oldCode, \Gems_Util_ReceptionCode $newCode) {
$count = 0;
if (!$oldCode->isSuccess() && $newCode->isSuccess()) {
foreach ($this->getTokens() as $token) {
if ($token instanceof \Gems_Tracker_Token) {
if ($oldCode->getCode() === $token->getReceptionCode()->getCode()) {
$token->setReceptionCode($newCode, null, $this->currentUser->getUserId());
$count++;
}
}
}
}
return $count;
} | Restores tokens for this track, when the reception code matches the given $oldCode
Used when restoring a respondent or this tracks, and the restore tracks/tokens
box is checked.
@param \Gems_Util_ReceptionCode $oldCode The old reception code
@param \Gems_Util_ReceptionCode $newCode the new reception code
@return int The number of restored tokens | entailment |
public function saveFields(array $fieldData)
{
$trackEngine = $this->getTrackEngine();
if (! $trackEngine) {
return 0;
}
//\MUtil_Echo::track($fieldData);
$this->_fieldData = $this->_mergeFieldValues($fieldData, $this->getFieldData(), $trackEngine);
$changed = $trackEngine->getFieldsDefinition()->saveFields($this->_respTrackId, $this->_fieldData);
if ($changed) {
$this->_ensureFieldData(true);
}
$this->handleFieldUpdate();
return $changed;
} | Saves the field data for the respondent track id.
@param array $fieldData The values to save, only the key is used, not the code
@return int The number of changed fields | entailment |
public function setFieldData($newFieldData)
{
$trackEngine = $this->getTrackEngine();
if (! $trackEngine) {
return $newFieldData;
}
$this->_fieldData = $this->processFieldsBeforeSave($newFieldData);
$changes = $this->saveFields(array());
if ($changes) {
$info = $trackEngine->getFieldsDefinition()->calculateFieldsInfo($this->_fieldData);
if ($info != $this->_respTrackData['gr2t_track_info']) {
$this->_updateTrack(array('gr2t_track_info' => $info), $this->currentUser->getUserId());
}
}
return $this->_fieldData;
} | Update one or more values for this track's fields.
Return the complete set of fielddata
@param array $newFieldData The new field values, may be partial, field set by code overwrite field set by key
@return array | entailment |
public function setMailable($mailable)
{
$values['gr2t_mailable'] = $mailable ? 1 : 0;
return $this->_updateTrack($values, $this->currentUser->getUserId());
} | Set the mailability for this respondent track.
@param boolean $mailable Should this respondent track be st to mailable
@param int $userId The current user
@return int 1 if the token has changed, 0 otherwise | entailment |
public function setReceptionCode($code, $comment, $userId)
{
// Make sure it is a \Gems_Util_ReceptionCode object
if (! $code instanceof \Gems_Util_ReceptionCode) {
$code = $this->util->getReceptionCode($code);
}
$changed = 0;
// Apply this code both only when it is a track code.
// Patient level codes are just cascaded to the tokens.
//
// The exception is of course when the exiting values must
// be overwritten, e.g. when cooperation is retracted.
if ($code->isForTracks() || $code->isOverwriter()) {
$values['gr2t_reception_code'] = $code->getCode();
}
$values['gr2t_comment'] = $comment;
$changed = $this->_updateTrack($values, $userId);
// Stopcodes have a different logic.
if ($code->isStopCode()) {
// Cascade stop to unanswered tokens
foreach ($this->getTokens() as $token) {
if ($token->hasSuccesCode() && (! $token->isCompleted())) {
$changed += $token->setReceptionCode($code, $comment, $userId);
}
}
$changed = max($changed, 1);
// Update token count / completion
$this->_checkTrackCount($userId);
} elseif (! $code->isSuccess()) {
// Cascade code to tokens
foreach ($this->getTokens() as $token) {
if ($token->hasSuccesCode()) {
$token->setReceptionCode($code, $comment, $userId);
}
}
}
return $changed;
} | Set the reception code for this respondent track and make sure the
necessary cascade to the tokens and thus the source takes place.
@param string $code The new (non-success) reception code or a \Gems_Util_ReceptionCode object
@param string $comment Comment for tokens. False values leave value unchanged
@param int $userId The current user
@return int 1 if the token has changed, 0 otherwise | entailment |
public function getChanges(array $context, $new)
{
$agenda = $this->loader->getAgenda();
$options = $this->util->getTranslated()->getEmptyDropdownArray();
if (isset($context['gap_id_user'], $context['gap_id_organization'])) {
if (isset($context['gap_admission_time'])) {
if ($context['gap_admission_time'] instanceof \MUtil_Date) {
$admission = $context['gap_admission_time']->toString(\Gems_Tracker::DB_DATE_FORMAT);
} elseif ($context['gap_admission_time'] instanceof \DateTimeInterface) {
$admission = $context['gap_admission_time']->format('Y-m-d');
} else {
$admission = $context['gap_admission_time'];
}
$where['gec_startdate <= ?'] = $admission;
$where['gec_enddate IS NULL OR gec_enddate > ?'] = $admission;
} else {
$where = null;
}
$options = $options + $agenda->getEpisodesAsOptions(
$agenda->getEpisodesForRespId($context['gap_id_user'], $context['gap_id_organization'], $where)
);
}
return ['gap_id_episode' => ['multiOptions' => $options]];
} | Returns the changes that must be made in an array consisting of
<code>
array(
field1 => array(setting1 => $value1, setting2 => $value2, ...),
field2 => array(setting3 => $value3, setting4 => $value4, ...),
</code>
By using [] array notation in the setting name you can append to existing
values.
Use the setting 'value' to change a value in the original data.
When a 'model' setting is set, the workings cascade.
@param array $context The current data this object is dependent on
@param boolean $new True when the item is a new record not yet saved
@return array name => array(setting => value) | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$html = $this->getHtmlSequence();
$html->h3($this->_('System is in maintenance mode'));
if ($this->token instanceof \Gems_Tracker_Token) {
if ($this->token->isCompleted()) {
if ($this->token->getNextUnansweredToken()) {
$html->pInfo()->strong($this->_('Your answers were processed correctly.'));
$html->pInfo($this->_(
'Unfortunately this system has just entered maintenance mode so you cannot continue.'
));
$html->pInfo($this->_(
'Please try to continue at a later moment. Reuse your link or refresh this page.'
));
} else {
$html->pInfo($this->_('This system has just entered maintenance mode.'));
$html->pInfo($this->_(
'All your surveys have been processed correctly and there are no further questions.'
));
}
return $html;
}
}
$html->pInfo($this->_('Unfortunately you cannot answer surveys while the system is in maintenance mode.'));
$html->pInfo($this->_('Please try again later.'));
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 |
protected function createModel($detailed, $action)
{
$translated = $this->util->getTranslated();
$model = new \MUtil_Model_TableModel('gems__agenda_diagnoses');
\Gems_Model::setChangeFieldsByPrefix($model, 'gad');
$model->setDeleteValues('gapr_active', 0);
$model->set('gad_diagnosis_code', 'label', $this->_('Diagnosis code'),
'description', $this->_('A code as defined by the coding system'),
'required', true
);
$model->set('gad_description', 'label', $this->_('Activity'),
'description', $this->_('Description of the diagnosis'),
'required', true
);
$model->setIfExists('gad_coding_method', 'label', $this->_('Coding system'),
'description', $this->_('The coding system used.'),
'multiOptions', $translated->getEmptyDropdownArray() + $this->loader->getAgenda()->getDiagnosisCodingSystems()
);
$model->setIfExists('gad_code', 'label', $this->_('Diagnosis code'),
'size', 10,
'description', $this->_('Optional code name to link the diagnosis to program code.'));
$model->setIfExists('gad_active', 'label', $this->_('Active'),
'description', $this->_('Inactive means assignable only through automatich processes.'),
'elementClass', 'Checkbox',
'multiOptions', $translated->getYesNo()
);
$model->setIfExists('gad_filter', 'label', $this->_('Filter'),
'description', $this->_('When checked appointments with these diagnoses are not imported.'),
'elementClass', 'Checkbox',
'multiOptions', $translated->getYesNo()
);
$model->addColumn("CASE WHEN gad_active = 1 THEN '' ELSE 'deleted' END", 'row_class');
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)
{
if ($this->request) {
$this->processSortOnly($model);
if ($this->grouped) {
$filter['gto_id_respondent_track'] = $this->token->getRespondentTrackId();
$filter['gto_id_survey'] = $this->token->getSurveyId();
} else {
$filter['gto_id_token'] = $this->token->getTokenId();
}
$model->setFilter($filter);
}
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
public function getActiveOrganizations()
{
$sql = "SELECT gor_id_organization, gor_name
FROM gems__organizations
WHERE (gor_active = 1 AND
gor_id_organization IN (SELECT gr2o_id_organization FROM gems__respondent2org)) OR
gor_id_organization = ?
ORDER BY gor_name";
$orgId = $this->loader->getCurrentUser()->getCurrentOrganizationId();
return $this->_getSelectPairsCached(__FUNCTION__ . '_' . $orgId, $sql, $orgId, 'organizations', 'natsort');
} | Retrieve a list of orgid/name pairs
@return array | entailment |
public function getActiveStaffGroups()
{
$sql = "SELECT ggp_id_group, ggp_name
FROM gems__groups
WHERE ggp_group_active = 1 AND ggp_staff_members = 1
ORDER BY ggp_name";
try {
$staffGroups = $this->_getSelectPairsCached(__FUNCTION__, $sql, null, 'groups');
} catch (\Exception $exc) {
// Intentional fallthrough when no db present
$staffGroups = array();
}
return $staffGroups;
} | Return key/value pairs of all active staff groups
@return array | entailment |
public function getCommTemplates($mailTarget = false)
{
static $data;
if (! $data) {
$sql = 'SELECT gct_id_template, gct_name FROM gems__comm_templates ';
if ($mailTarget) {
$sql .= 'WHERE gct_target = ? ';
}
$sql .= 'ORDER BY gct_name';
if ($mailTarget) {
$data = $this->db->fetchPairs($sql, $mailTarget);
} else {
$data = $this->db->fetchPairs($sql);
}
}
return $data;
} | Return the available Comm templates.
@staticvar array $data
@return array The tempalteId => subject list | entailment |
public function getFilterForMailJob($job, $respondentId = null, $organizationId = null)
{
// Set up filter
$filter = array(
'can_email' => 1,
'gtr_active' => 1,
'gsu_active' => 1,
'grc_success' => 1,
'gto_completion_time' => NULL,
'gto_valid_from <= CURRENT_TIMESTAMP',
'(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'
);
switch ($job['gcj_filter_mode']) {
case 'E': // Reminder before expiry
$filter[] = 'gto_mail_sent_date < CURRENT_DATE() AND CURRENT_DATE() = DATE(DATE_SUB(gto_valid_until, INTERVAL ' . $job['gcj_filter_days_between'] . ' DAY))';
break;
case 'R': // Reminder after first email
$filter[] = 'gto_mail_sent_date <= DATE_SUB(CURRENT_DATE, INTERVAL ' . $job['gcj_filter_days_between'] . ' DAY)';
$filter[] = 'gto_mail_sent_num <= ' . $job['gcj_filter_max_reminders'];
break;
case 'N': // First email
default:
$filter['gto_mail_sent_date'] = NULL;
break;
}
if ($job['gcj_id_organization']) {
if ($organizationId && ($organizationId !== $job['gcj_id_organization'])) {
// Should never return any data
$filter[] = '1=0';
return $filter;
}
$filter['gto_id_organization'] = $job['gcj_id_organization'];
}
if ($job['gcj_id_track']) {
$filter['gto_id_track'] = $job['gcj_id_track'];
}
if ($job['gcj_round_description']) {
if ($job['gcj_id_track']) {
$roundIds = $this->db->fetchCol('
SELECT gro_id_round FROM gems__rounds WHERE gro_active = 1 AND gro_id_track = ? AND gro_round_description = ?', array(
$job['gcj_id_track'],
$job['gcj_round_description'])
);
} else {
$roundIds = $this->db->fetchCol('
SELECT gro_id_round FROM gems__rounds WHERE gro_active = 1 AND gro_round_description = ?', array(
$job['gcj_round_description'])
);
}
// Add round 0 for inserted rounds, and check if the description matches
$filter[] = sprintf('(gto_id_round IN (%s)) OR (gto_id_round = 0 AND gto_round_description = %s)', $this->db->quote($roundIds), $this->db->quote($job['gcj_round_description']));
}
if ($job['gcj_id_survey']) {
$filter['gto_id_survey'] = $job['gcj_id_survey'];
}
if ($respondentId) {
$filter['gto_id_respondent'] = $respondentId;
}
if ($job['gcj_target'] == 1) {
// Only relations
$filter[] = 'gto_id_relation <> 0';
} elseif ($job['gcj_target'] == 2) {
// Only respondents
$filter[] = '(gto_id_relation = 0 OR gto_id_relation IS NULL)';
}
return $filter;
} | Get the filter to use on the tokenmodel when working with a mailjob.
@param array $job
@param $respondentId Optional, get for just one respondent
@param $organizationId Optional, get for just one organization
@return array | entailment |
public function getGroups()
{
$sql = "SELECT ggp_id_group, ggp_name
FROM gems__groups
WHERE ggp_group_active = 1
ORDER BY ggp_name";
return $this->util->getTranslated()->getEmptyDropdownArray() +
$this->_getSelectPairsCached(__FUNCTION__, $sql, null, 'groups');
} | The active groups
@return array | entailment |
public function getOrganizations()
{
$sql = "SELECT gor_id_organization, gor_name
FROM gems__organizations
WHERE gor_active = 1
ORDER BY gor_name";
try {
$organizations = $this->_getSelectPairsCached(__FUNCTION__, $sql, null, 'organizations', 'natsort');
} catch (\Exception $exc) {
// Intentional fallthrough when no db present
$organizations = array();
}
return $organizations;
} | Get all active organizations
@return array List of the active organizations | entailment |
public function getOrganizationsByCode($code = null)
{
if (is_null($code)) {
return $this->getOrganizations();
}
$sql = "SELECT gor_id_organization, gor_name
FROM gems__organizations
WHERE gor_active = 1 and gor_code = ?
ORDER BY gor_name";
return $this->_getSelectPairsCached(__FUNCTION__ . '_' . $code, $sql, $code, 'organizations', 'natsort');
} | Get all organizations that share a given code
On empty this will return all organizations
@param string $code
@return array key = gor_id_organization, value = gor_name | entailment |
public function getPatientNr($respondentId, $organizationId)
{
$result = $this->db->fetchOne(
"SELECT gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ? AND gr2o_id_organization = ?",
array($respondentId, $organizationId)
);
if ($result !== false) {
return $result;
}
throw new \Gems_Exception(
sprintf($this->_('Respondent id %s not found.'), $respondentId),
200,
null,
sprintf($this->_('In the organization nr %d.'), $organizationId)
);
} | Find the patient nr corresponding to this respondentId / Orgid combo
@param int $respondentId
@param int $organizationId
@return string A patient nr or null
@throws \Gems_Exception When the patient does not exist | entailment |
public function getRespondentId($patientId, $organizationId)
{
$result = $this->db->fetchOne(
"SELECT gr2o_id_user FROM gems__respondent2org WHERE gr2o_patient_nr = ? AND gr2o_id_organization = ?",
array($patientId, $organizationId)
);
if ($result !== false) {
return $result;
}
throw new \Gems_Exception(
sprintf($this->_('Patient number %s not found.'), $patientId),
200,
null,
sprintf($this->_('In the organization nr %d.'), $organizationId)
);
} | Find the respondent id corresponding to this patientNr / Orgid combo
@param string $patientId
@param int $organizationId
@return int A respondent id or null
@throws \Gems_Exception When the respondent does not exist | entailment |
public function getRespondentIdAndName($patientId, $organizationId)
{
$output = $this->db->fetchRow(
"SELECT gr2o_id_user as id,
TRIM(CONCAT(
COALESCE(CONCAT(grs_last_name, ', '), '-, '),
COALESCE(CONCAT(grs_first_name, ' '), ''),
COALESCE(grs_surname_prefix, ''))) as name
FROM gems__respondent2org INNER JOIN
gems__respondents ON gr2o_id_user = grs_id_user
WHERE gr2o_patient_nr = ? AND gr2o_id_organization = ?",
array($patientId, $organizationId)
);
if ($output !== false) {
return $output;
}
throw new \Gems_Exception(
sprintf($this->_('Patient number %s not found.'), $patientId),
200,
null,
sprintf($this->_('In the organization nr %d.'), $organizationId)
);
} | Find the respondent id name corresponding to this patientNr / Orgid combo
@param string $patientId
@param int $organizationId
@return array ['id', 'name']
@throws \Gems_Exception When the respondent does not exist | entailment |
public function getRoles()
{
$roles = array();
if ($this->acl) {
foreach ($this->acl->getRoles() as $role) {
//Do not translate, only make first one uppercase
$roles[$role] = ucfirst($role);
}
}
asort($roles);
return $roles;
} | Returns the roles in the acl
@return array roleId => ucfirst(roleId) | entailment |
public function getRolesByPrivilege($privilege)
{
$roles = array();
if ($this->acl) {
foreach ($this->acl->getRoles() as $role) {
if ($this->acl->isAllowed($role, null, $privilege)) {
//Do not translate, only make first one uppercase
$roles[$role] = ucfirst($role);
}
}
}
return $roles;
} | Returns the roles in the acl with the privilege
@return array roleId => ucfirst(roleId) | entailment |
public function getRoundsForExport($trackId = null, $surveyId = null)
{
// Read some data from tables, initialize defaults...
$select = $this->db->select();
// Fetch all round descriptions
$select->from('gems__tokens', array('gto_round_description', 'gto_round_description'))
->distinct()
->where('gto_round_description IS NOT NULL AND gto_round_description != ""')
->order(array('gto_round_description'));
if (!empty($trackId)) {
$select->where('gto_id_track = ?', (int) $trackId);
}
if (!empty($surveyId)) {
$select->where('gto_id_survey = ?', (int) $surveyId);
}
$result = $this->db->fetchPairs($select);
return $result;
} | Get all round descriptions for exported
@param int $trackId Optional track id
@param int $surveyId Optional survey id
@return array | entailment |
public function getStaff()
{
$sql = "SELECT gsf_id_user,
CONCAT(
COALESCE(gsf_last_name, '-'),
', ',
COALESCE(gsf_first_name, ''),
COALESCE(CONCAT(' ', gsf_surname_prefix), '')
)
FROM gems__staff
ORDER BY gsf_last_name, gsf_first_name, gsf_surname_prefix";
return $this->_getSelectPairsCached(__FUNCTION__, $sql, null, 'staff') +
array(
\Gems_User_UserLoader::SYSTEM_USER_ID => \MUtil_Html::raw($this->_('«system»')),
);
} | Return key/value pairs of all staff members, currently active or not
@return array | entailment |
public function getSurveys($organizationId = null)
{
$where = "";
if ($organizationId !== null) {
$where = "AND EXISTS (SELECT 1 FROM gems__rounds
INNER JOIN gems__tracks ON gro_id_track = gtr_id_track
WHERE gro_id_survey = gsu_id_survey AND
gtr_organizations LIKE '%|" . (int) $organizationId . "|%')";
}
$sql = "SELECT gsu_id_survey, gsu_survey_name FROM gems__surveys WHERE gsu_active = 1 " .
$where . " ORDER BY gsu_survey_name ASC";
return $this->db->fetchPairs($sql);
} | Returns an array with key => value pairs containing all surveys
(for a specific organization)
@param string $organizationId
@return array | entailment |
public function getSurveysForExport($trackId = null, $roundDescription = null, $flat = false)
{
// Read some data from tables, initialize defaults...
$select = $this->db->select();
// Fetch all surveys
$select->from('gems__surveys')
->join('gems__sources', 'gsu_id_source = gso_id_source')
->where('gso_active = 1')
//->where('gsu_surveyor_active = 1')
// Leave inactive surveys, we toss out the inactive ones for limesurvey
// as it is no problem for OpenRosa to have them in
->order(array('gsu_active DESC', 'gsu_survey_name'));
if ($trackId) {
if ($roundDescription) {
$select->where('gsu_id_survey IN (SELECT gto_id_survey FROM gems__tokens WHERE gto_id_track = ? AND gto_round_description = ' . $this->db->quote($roundDescription) . ')', $trackId);
} else {
$select->where('gsu_id_survey IN (SELECT gto_id_survey FROM gems__tokens WHERE gto_id_track = ?)', $trackId);
}
} elseif ($roundDescription) {
$select->where('gsu_id_survey IN (SELECT gto_id_survey FROM gems__tokens WHERE gto_round_description = ?)', $roundDescription);
}
$result = $this->db->fetchAll($select);
if ($result) {
// And transform to have inactive surveys in gems and source in a
// different group at the bottom
$surveys = array();
$inactive = $this->_('inactive');
$sourceInactive = $this->_('source inactive');
foreach ($result as $survey) {
$id = $survey['gsu_id_survey'];
$name = $survey['gsu_survey_name'];
if ($survey['gsu_surveyor_active'] == 0) {
// Inactive in the source, for LimeSurvey this is a problem!
if (strpos($survey['gso_ls_class'], 'LimeSurvey') === false) {
if ($flat) {
$surveys[$id] = $name . " ($sourceInactive) ";
} else {
$surveys[$sourceInactive][$id] = $name;
}
}
} elseif ($survey['gsu_active'] == 0) {
if ($flat) {
$surveys[$id] = $name . " ($inactive) ";
} else {
$surveys[$inactive][$id] = $name;
}
} else {
$surveys[$id] = $name;
}
}
} else {
$surveys = array();
}
return $surveys;
} | Get all surveys that can be exported
For export not only active surveys should be returned, but all surveys that can be exported.
As this depends on the kind of source used it is in this method so projects can change to
adapt to their own sources.
@param int $trackId Optional track id
@return array | entailment |
public function addMessageInvalid($message_args)
{
$this->saveButtonId = null;
$this->saveLabel = null;
parent::addMessage(func_get_args());
} | Adds one or more messages to the session based message store.
@param mixed $message_args Can be an array or multiple argemuents. Each sub element is a single message string
@return self (continuation pattern) | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->saveLabel = $this->_('Insert survey');
$this->tracker = $this->loader->getTracker();
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function createModel()
{
$model = $this->tracker->getTokenModel();
if ($model instanceof \Gems_Tracker_Model_StandardTokenModel) {
$model->addEditTracking();
if ($this->createData) {
$model->applyInsertionFormatting();
}
}
// Valid from can not be calculated for inserted rounds, and should always be manual
$model->set('gto_valid_from_manual', 'elementClass', 'Hidden', 'default', '1');
$trackData = $this->util->getTrackData();
if (! $this->surveyList) {
$this->surveyList = $trackData->getInsertableSurveys($this->request->getParam(\MUtil_Model::REQUEST_ID2));
}
$model->set('gto_id_survey', 'label', $this->_('Suvey to insert'),
// 'elementClass' set in loadSurvey
'multiOptions', $this->surveyList,
'onchange', 'this.form.submit();'
);
$model->set('gto_id_track', 'label', $this->_('Existing track'),
'elementClass', 'Select',
//'multiOptions' set in loadTrackSettings
'onchange', 'this.form.submit();'
);
$model->set('gto_round_order', 'label', $this->_('In round'),
'elementClass', 'Select',
//'multiOptions' set in loadRoundSettings
'required', true
);
$model->set('gto_valid_from',
'required', true
);
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function getRoundSelect()
{
$select = $this->db->select();
$select->from('gems__tokens', array('gto_round_description AS round_description'))
->joinInner('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array())
->joinInner('gems__surveys', 'gto_id_survey = gsu_id_survey', array())
->where('grc_success = 1')
->group('gto_round_description');
if ($this->survey instanceof \Gems_Tracker_Survey) {
$groupId = $this->survey->getGroupId();
$select->columns(array(
// Round order is maximum for the survey's group unless this round had no surveys of the same group
'round_order' => new \Zend_Db_Expr(
"COALESCE(
MAX(CASE WHEN gsu_id_primary_group = $groupId THEN gto_round_order ELSE NULL END),
MAX(gto_round_order)
) + 1"
),
'has_group' => new \Zend_Db_Expr(
"SUM(CASE WHEN gsu_id_primary_group = $groupId THEN 1 ELSE 0 END)"
),
'group_answered' => new \Zend_Db_Expr(
"SUM(CASE WHEN gto_completion_time IS NOT NULL AND gsu_id_primary_group = $groupId
THEN 1
ELSE 0
END)"
),
'any_answered' => new \Zend_Db_Expr(
"SUM(CASE WHEN gto_completion_time IS NOT NULL THEN 1 ELSE 0 END)"
),
));
} else {
$select->columns(array(
'round_order' => new \Zend_Db_Expr("MAX(gto_round_order)+ 1"),
'has_group' => new \Zend_Db_Expr("0"),
'group_answered' => new \Zend_Db_Expr("0"),
'any_answered' => new \Zend_Db_Expr(
"SUM(CASE WHEN gto_completion_time IS NOT NULL THEN 1 ELSE 0 END)"
),
));
}
if (isset($this->formData['gto_id_track'])) {
$select->where('gto_id_respondent_track = ?', $this->formData['gto_id_track']);
} else {
$select->where('1=0');
}
$select->order('round_order');
return $select;
} | Get a select with the fields:
- round_order: The gto_round_order to use for this round
- has_group: True when has surveys for same group as current survey
- group_answered: True when has answers for same group as current survey
- any_answered: True when has answers for any survey
- round_description: The gto_round_description for the round
@return \Zend_Db_Select or you can return a nested array containing said output/ | entailment |
protected function getRoundsListAndSetDefault()
{
$model = $this->getModel();
$output = array();
$select = $this->getRoundSelect();
if ($select instanceof \Zend_Db_Select) {
$rows = $this->db->fetchAll($select);
} else {
$rows = $select;
}
if ($rows) {
// Initial values
$maxAnswered = 0;
$maxGroupAnswered = 0;
$minGroup = -1;
foreach ($rows as $row) {
$output[$row['round_order']] = $row['round_description'];
if ($row['has_group']) {
if (-1 === $minGroup) {
$minGroup = $row['round_order'];
}
if ($row['group_answered']) {
$maxGroupAnswered = $row['round_order'];
}
}
if ($row['any_answered']) {
$maxAnswered = $row['round_order'];
}
}
if ($maxGroupAnswered) {
$this->defaultRound = $maxGroupAnswered;
$model->set('gto_round_order', 'description', sprintf(
$this->_('The last round containing answers for surveys in the same user group is "%s".'),
$output[$this->defaultRound]
));
} elseif ($maxAnswered) {
$this->defaultRound = $maxAnswered;
$model->set('gto_round_order', 'description', sprintf(
$this->_('The last round containing answers is "%s".'),
$output[$this->defaultRound]
));
} elseif (-1 !== $minGroup) {
$this->defaultRound = $minGroup;
$model->set('gto_round_order', 'description', sprintf(
$this->_('No survey has been answered, the first round with surveys in the same user group is "%s".'),
$output[$this->defaultRound]
));
} else {
reset($output);
$this->defaultRound = key($output);
$model->set('gto_round_order',
'description', $this->_('No surveys have answers, nor are any in the same user group.')
);
}
} else {
$output[10] = $this->_('Added survey');
$this->defaultRound = 10;
$model->set('gto_round_order',
'description', $this->_('No current rounds available.')
);
}
return $output;
} | Get the list of rounds and set the default
@return array [roundInsertNr => RoundDescription | entailment |
protected function loadFormData()
{
if ($this->createData && (! $this->request->isPost())) {
$now = new \MUtil_Date();
$organizationId = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
$patientId = $this->request->getParam(\MUtil_Model::REQUEST_ID1);
$respondentData = $this->util->getDbLookup()->getRespondentIdAndName($patientId, $organizationId);
$this->formData = array(
'gr2o_patient_nr' => $patientId,
'gto_id_organization' => $organizationId,
'gto_id_respondent' => $respondentData['id'],
'respondent_name' => $respondentData['name'],
'gto_id_survey' => $this->request->getParam(\Gems_Model::SURVEY_ID),
'gto_id_track' => $this->request->getParam(\Gems_Model::TRACK_ID),
'gto_valid_from_manual' => 1,
'gto_valid_from' => $now,
'gto_valid_until_manual' => 0,
'gto_valid_until' => null, // Set in loadSurvey
);
$this->getModel()->processAfterLoad(array($this->formData), $this->createData, false);
} else {
parent::loadFormData();
}
$this->loadSurvey();
$this->loadTrackSettings();
$this->loadRoundSettings();
// \MUtil_Echo::track($this->formData);
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function loadRoundSettings()
{
$rounds = $this->getRoundsListAndSetDefault();
$model = $this->getModel();
$model->set('gto_round_order', 'multiOptions', $rounds, 'size', count($rounds));
if (count($rounds) === 1) {
$model->set('gto_round_order', 'elementClass', 'Exhibitor');
}
if (! isset($this->formData['gto_round_order'], $rounds[$this->formData['gto_round_order']])) {
$this->formData['gto_round_order'] = $this->defaultRound;
}
if (! isset($rounds[$this->formData['gto_round_order']])) {
reset($rounds);
$this->formData['gto_round_order'] = key($rounds);
}
} | Load the settings for the round | entailment |
protected function loadSurvey()
{
if (! $this->surveyList) {
$this->addMessageInvalid($this->_('Survey insertion impossible: no insertable survey exists!'));
}
if (count($this->surveyList) === 1) {
$model = $this->getModel();
$model->set('gto_id_survey', 'elementClass', 'Exhibitor');
reset($this->surveyList);
$this->formData['gto_id_survey'] = key($this->surveyList);
}
if (isset($this->formData['gto_id_survey'])) {
$this->survey = $this->tracker->getSurvey($this->formData['gto_id_survey']);
$groupId = $this->survey->getGroupId();
$groups = $this->util->getDbLookup()->getGroups();
if (isset($groups[$groupId])) {
$this->formData['ggp_name'] = $groups[$groupId];
}
$this->formData['gto_valid_until'] = $this->survey->getInsertDateUntil($this->formData['gto_valid_from']);
}
} | Load the survey object and use it | entailment |
protected function loadTrackSettings()
{
$respTracks = $this->tracker->getRespondentTracks(
$this->formData['gto_id_respondent'],
$this->formData['gto_id_organization']
);
$tracks = array();
foreach ($respTracks as $respTrack) {
if ($respTrack instanceof \Gems_Tracker_RespondentTrack) {
if ($respTrack->hasSuccesCode()) {
$tracks[$respTrack->getRespondentTrackId()] = substr(sprintf(
$this->_('%s - %s'),
$respTrack->getTrackEngine()->getTrackName(),
$respTrack->getFieldsInfo()
), 0, 100);
}
}
}
if ($tracks) {
if (! isset($this->formData['gto_id_track'])) {
reset($tracks);
$this->formData['gto_id_track'] = key($tracks);
}
} else {
$this->addMessageInvalid($this->_('Survey insertion impossible: respondent has no track!'));
$tracks = $this->util->getTranslated()->getEmptyDropdownArray();
}
asort($tracks);
$model = $this->getModel();
$model->set('gto_id_track', 'multiOptions', $tracks);
if (count($tracks) === 1) {
$model->set('gto_id_track', 'elementClass', 'Exhibitor');
}
if (isset($this->formData['gto_id_track'])) {
$this->respondentTrack = $respTracks[$this->formData['gto_id_track']];
// Add relation field when survey is not for staff
if ($this->survey && $this->survey->isTakenByStaff() === false) {
$engine = $this->respondentTrack->getTrackEngine();
if (method_exists($engine, 'getRespondentRelationFields')) {
$empty = array('-1' => $this->_('Patient'));
$relations = $empty + $engine->getRespondentRelationFields();
$model->set('gto_id_relationfield', 'label', $this->_('Fill out by'),
'multiOptions', $relations, 'elementClass', 'Select',
'required', true);
}
}
}
} | Load the settings for the survey | entailment |
protected function saveData()
{
$model = $this->getModel();
$userId = $this->currentUser->getUserId();
$tokenData = array();
foreach ($this->copyFields as $name) {
if (array_key_exists($name, $this->formData)) {
if ($model->hasOnSave($name)) {
$tokenData[$name] = $model->getOnSave($this->formData[$name], $this->createData, $name, $this->formData);
} elseif ('' === $this->formData[$name]) {
$tokenData[$name] = null;
} else {
$tokenData[$name] = $this->formData[$name];
}
} else {
$tokenData[$name] = null;
}
}
$rounds = $model->get('gto_round_order', 'multiOptions');
$tokenData['gto_id_round'] = '0';
$tokenData['gto_round_order'] = $this->formData['gto_round_order'];
$tokenData['gto_round_description'] = $rounds[$this->formData['gto_round_order']];
$surveyId = $this->formData['gto_id_survey'];
$this->token = $this->respondentTrack->addSurveyToTrack($surveyId, $tokenData, $userId);
$changed = 1;
// Communicate with the user
$this->afterSave($changed);
} | Hook containing the actual save code.
Calls afterSave() for user interaction.
@see afterSave() | entailment |
protected function setAfterSaveRoute()
{
// Default is just go to the index
if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
$this->afterSaveRouteUrl = array(
$this->request->getControllerKey() => 'track',
$this->request->getActionKey() => $this->routeAction,
\MUtil_Model::REQUEST_ID => $this->token->getTokenId(),
);
}
return $this;
} | Set what to do when the form is 'finished'.
@return self | entailment |
protected function _getScreenClass($screenType)
{
if (isset($this->_screenClasses[$screenType])) {
return $this->_screenClasses[$screenType];
} else {
throw new \Gems_Exception_Coding("No screen class exists for screen type '$screenType'.");
}
} | Lookup screen class for a screen type. This class or interface should at the very least
implement the ScreenInterface.
@see \Gems\Screens\ScreenInterface
@param string $screenType The type (i.e. lookup directory) to find the associated class for
@return string Class/interface name associated with the type | entailment |
protected function _listScreens($screenType)
{
$screenClass = $this->_getScreenClass($screenType);
$paths = $this->_getScreenDirs($screenType);
return $this->listClasses($screenClass, $paths, 'getScreenLabel');
} | Returns a list of selectable screens with an empty element as the first option.
@param string $screenType The type (i.e. lookup directory with an associated class) of the screens to list
@return \Gems_tracker_TrackerEventInterface or more specific a $screenClass type object | entailment |
protected function _loadScreen($screenName, $screenType)
{
$screenClass = $this->_getScreenClass($screenType);
// \MUtil_Echo::track($screenName);
if (! class_exists($screenName, true)) {
// Autoload is used for Zend standard defined classnames,
// so if the class is not autoloaded, define the path here.
$filename = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Screens' . DIRECTORY_SEPARATOR .
strtolower($screenType) . DIRECTORY_SEPARATOR . $screenName . '.php';
if (! file_exists($filename)) {
throw new \Gems_Exception_Coding("The screen '$screenName' of type '$screenType' does not exist at location: $filename.");
}
// \MUtil_Echo::track($filename);
include($filename);
}
$screen = new $screenName();
if (! $screen instanceof $screenClass) {
throw new \Gems_Exception_Coding("The screen '$screenName' of type '$screenType' is not an instance of '$screenClass'.");
}
if ($screen instanceof \MUtil_Registry_TargetInterface) {
$this->applySource($screen);
}
return $screen;
} | Loads and initiates an screen class and returns the class (without triggering the screen itself).
@param string $screenName The class name of the individual screen to load
@param string $screenType The type (i.e. lookup directory with an associated class) of the screen
@return \Gems_tracker_TrackerEventInterface or more specific a $screenClass type object | entailment |
protected function createModel()
{
if ($this->model instanceof \Gems_Tracker_Model_StandardTokenModel) {
$model = $this->model;
} else {
$model = $this->loader->getTracker()->getTokenModel();
}
$model->addColumn(
'CASE WHEN gto_completion_time IS NULL THEN gto_valid_from ELSE gto_completion_time END',
'calc_used_date',
'gto_valid_from');
$model->addColumn(
'CASE WHEN gto_completion_time IS NULL THEN gto_valid_from ELSE NULL END',
'calc_valid_from',
'gto_valid_from');
$model->addColumn(
'CASE WHEN gto_completion_time IS NULL AND grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) THEN gto_id_token ELSE NULL END',
'calc_id_token',
'gto_id_token');
$model->addColumn(
'CASE WHEN gto_completion_time IS NULL AND grc_success = 1 AND gto_valid_from <= CURRENT_TIMESTAMP AND gto_completion_time IS NULL AND gto_valid_until < CURRENT_TIMESTAMP THEN 1 ELSE 0 END',
'was_missed');
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function sortCalcDateCheck(\MUtil_Model_ModelAbstract $model)
{
$sort = $model->getSort();
if (isset($sort['calc_used_date'])) {
$add = true;
$resultSort = array();
foreach ($sort as $key => $asc) {
if ('calc_used_date' === $key) {
if ($add) {
$resultSort['is_completed'] = $asc;
$resultSort['gto_completion_time'] = $asc == SORT_ASC ? SORT_DESC : SORT_ASC;
$resultSort['calc_valid_from'] = $asc;
$add = false; // We can add this only once
}
} else {
$resultSort[$key] = $asc;
}
}
if (! $add) {
$model->setSort($resultSort);
}
}
} | calc_used_date has special sort, see bugs 108 and 127
@param \MUtil_Model_ModelAbstract $model | entailment |
public function getActiveTracks($orgs = '1=1')
{
if (is_array($orgs) || is_int($orgs)) {
$cacheId = __CLASS__ . '_' . __FUNCTION__ . '_o' . parent::cleanupForCacheId(implode('_', (array) $orgs));
$orgWhere = "(INSTR(gtr_organizations, '|" .
implode("|') > 0 OR INSTR(gtr_organizations, '|", (array) $orgs) .
"|') > 0)";
} else {
$orgWhere = $orgs ? $orgs : '1=1';
$cacheId = __CLASS__ . '_' . __FUNCTION__ . '_' . parent::cleanupForCacheId($orgWhere);
}
if ($results = $this->cache->load($cacheId)) {
return $results;
}
$select = "SELECT gtr_id_track, gtr_track_name
FROM gems__tracks
WHERE gtr_active=1 AND $orgWhere
ORDER BY gtr_track_name";
$results = $this->db->fetchPairs($select);
$this->cache->save($results, $cacheId, array('tracks'));
return $results;
} | Retrieve an array of key/value pairs for gsu_id_survey and gsu_survey_name
that are active
@param mixed $orgs Either an array of org ids or an organization id or an sql select where statement
@return array | entailment |
public function getAllSurveys($active=false)
{
if ($active) {
$sql = "SELECT gsu_id_survey, gsu_survey_name FROM gems__surveys WHERE gsu_active = 1 ORDER BY gsu_survey_name";
} else {
$sql = "SELECT gsu_id_survey, gsu_survey_name FROM gems__surveys ORDER BY gsu_survey_name";
}
return $this->_getSelectPairsCached(__FUNCTION__, $sql, array(), 'surveys');
} | Retrieve an array of key/value pairs for gsu_id_survey and gsu_survey_name
@param boolean $active Only show active surveys Default: False
@return array of survey Id and survey name pairs | entailment |
public function getAllSurveysAndDescriptions()
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
if ($results = $this->cache->load($cacheId)) {
return $results;
}
$select = 'SELECT gsu_id_survey,
CONCAT(
SUBSTR(CONCAT_WS(
" - ", gsu_survey_name, CASE WHEN LENGTH(TRIM(gsu_survey_description)) = 0 THEN NULL ELSE gsu_survey_description END
), 1, 50),
CASE WHEN gsu_active = 1 THEN " (' . $this->translate->_('Active') . ')" ELSE " (' . $this->translate->_('Inactive') . ')" END
)
FROM gems__surveys ORDER BY gsu_survey_name';
$results = $this->db->fetchPairs($select);
$this->cache->save($results, $cacheId, array('surveys'));
return $results;
} | Retrieve an array of key/value pairs for gsu_id_survey and gsu_survey_name plus gsu_survey_description
@return array | entailment |
public function getAllTracks()
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
if ($results = $this->cache->load($cacheId)) {
return $results;
}
$select = "SELECT gtr_id_track, gtr_track_name
FROM gems__tracks
WHERE gtr_track_class != 'SingleSurveyEngine'
ORDER BY gtr_track_name";
$results = $this->db->fetchPairs($select);
$this->cache->save($results, $cacheId, array('tracks'));
return $results;
} | Returns array (id => name) of all tracks, sorted alphabetically
@return array | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.