sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function _toCleanArray(array $data)
{
switch (count($data)) {
case 0:
return null;
case 1:
if (isset($data[0])) {
// Return array content when only one item
// with the key 0.
if (is_array($data[0])) {
return $this->_toCleanArray($data[0]);
} else {
return $data[0];
}
}
break;
case 2:
if (isset($data[0], $data[1]) && is_string($data[1])) {
if (('info' === $data[1]) || ('warning' === $data[1]) || ('error' === $data[1])) {
if (is_array($data[0])) {
return $this->_toCleanArray($data[0]);
} else {
return $data[0];
}
}
}
}
$output = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
$output[$key] = $this->_toCleanArray($value);
} else {
if (is_string($value)) {
// Filter passwords from the log
if (\MUtil_String::contains($key, 'password', true) || \MUtil_String::contains($key, 'pwd', true)) {
$value = '****';
}
} elseif ($value instanceof Zend_Date) {
// Output iso representation for date objects
$value = $value->getIso();
}
$output[$key] = $value;
}
}
return $output;
} | Remove password and pwd contents and clean up message status data and single item arrays
@param array $data
@return mixed | entailment |
private function _toJson($data)
{
if ($data) {
if (is_array($data)) {
return json_encode($this->_toCleanArray($data));
}
return json_encode($data);
}
} | Converts data types for storage
@param mixed $data
@return string | entailment |
protected function getMessages()
{
if (! $this->_messenger instanceof \MUtil_Controller_Action_Helper_FlashMessenger) {
$this->_messenger = new \MUtil_Controller_Action_Helper_FlashMessenger();
}
return $this->_messenger->getMessagesOnly();
} | The curent flash messenger messages
@return array | entailment |
public function log($action, \Zend_Controller_Request_Abstract $request = null, $message = null, $respondentId = null, $force = false)
{
if (null === $request) {
$request = \Zend_Controller_Front::getInstance()->getRequest();
}
$this->_logEntry($request, $action, $force, null, $message, $respondentId);
return $this;
} | Logs the action for the current user with optional message and respondent id
@param string $action
@param \Zend_Controller_Request_Abstract $request
@param string $message An optional message to log with the action
@param <type> $respondentId
@param boolean $force Should we force the logentry to be inserted or should we try to skip duplicates? Default = false
@return \Gems_AccessLog
@deprecated Since version 1.7.1: use logChange or logRequest | entailment |
public function logChange(\Zend_Controller_Request_Abstract $request, $message = null, $data = null, $respondentId = null)
{
$action = $request->getControllerName() . '.' . $request->getActionName();
return $this->logEntry($request, $action, true, $message, $data, $respondentId);
} | Logs the action for the current user with optional message and respondent id
@param \Zend_Controller_Request_Abstract $request
@param mixed $message
@param mixed $data
@param int $respondentId
@return boolean True when a log entry was stored | entailment |
public function logRequest(\Zend_Controller_Request_Abstract $request, $message = null, $data = null, $respondentId = null)
{
$action = $request->getControllerName() . '.' . $request->getActionName();
if ($respondentId instanceof \Gems_Tracker_Respondent) {
if ($respondentId->exists) {
$data = (array) $data;
$data['gr2o_id_organization'] = $respondentId->getOrganizationId();
$respondentId = $respondentId->getId();
} else {
$respondentId = null;
}
}
return $this->logEntry($request, $action, false, $message, $data, $respondentId);
} | Logs the action for the current user with optional message and respondent id
@param \Zend_Controller_Request_Abstract $request
@param mixed $message
@param mixed $data
@param int|\Gems_Tracker_Respondent $respondentId
@return boolean True when a log entry was stored | entailment |
protected function saveData()
{
$this->addMessage($this->_('You have been subscribed succesfully.'));
$sql = "SELECT gr2o_id_user FROM gems__respondent2org
WHERE gr2o_email = ? AND gr2o_id_organization = ?";
$userId = $this->db->fetchOne($sql, [$this->formData['email'], $this->currentOrganization->getId()]);
$model = $this->loader->getModels()->createRespondentModel();
$values['grs_iso_lang'] = $this->locale->getLanguage();
$values['gr2o_id_organization'] = $this->currentOrganization->getId();
$values['gr2o_email'] = $this->formData['email'];
$values['gr2o_mailable'] = 1;
$values['gr2o_comments'] = $this->_('Created by subscription');
$values['gr2o_opened_by'] = $this->currentUser->getUserId();
if ($userId) {
$values['grs_id_user'] = $userId;
$values['gr2o_id_user'] = $userId;
} else {
$func = $this->patientNrGenerator;
$values['gr2o_patient_nr'] = $func();
}
// \MUtil_Echo::track($values);
$model->save($values);
return $model->getChanged();
} | Hook containing the actual save code.
@return int The number of "row level" items changed | entailment |
public function getChanges(array $context, $new)
{
// Only change anything when there are filters
$filters = $this->loader->getAgenda()->getFilterList();
if (! $filters) {
return array();
}
// Load utility
$translated = $this->util->getTranslated();
$output['gtf_id_order'] =array(
'description' => $this->_('The display and processing order of the fields.') . "\n" .
$this->_('When using automatic filters the fields are ALWAYS filled with appointments in ascending order.'),
);
$output['htmlCalc'] = array(
'label' => ' ',
'elementClass' => 'Exhibitor',
);
$output['gtf_filter_id'] = array(
'label' => $this->_('Automatic link'),
'description' => $this->_('Automatically link an appointment when it passes this filter.'),
'elementClass' => 'Select',
'multiOptions' => $translated->getEmptyDropdownArray() + $filters,
'onchange' => 'this.form.submit();',
);
if ($context['gtf_filter_id']) {
$periodUnits = $this->util->getTranslated()->getPeriodUnits();
$output['gtf_min_diff_length'] = array(
'label' => $this->_('Minimal time difference'),
'description' => $this->_('Difference with the previous appointment or track start date, can be negative but not zero'),
'elementClass' => 'Text',
'required' => true,
// 'size' => 5, // Causes trouble during save
'filters[int]' => 'Int',
'validators[isnot]' => new \MUtil_Validate_IsNot(0, $this->_('This value may not be zero!')),
);
$output['gtf_min_diff_unit'] = array(
'label' => $this->_('Minimal difference unit'),
'elementClass' => 'Select',
'multiOptions' => $periodUnits,
);
$output['gtf_max_diff_exists'] = array(
'label' => $this->_('Set a maximum time difference'),
'elementClass' => 'Checkbox',
'onclick' => 'this.form.submit();',
);
if ($context['gtf_max_diff_exists']) {
$output['gtf_max_diff_length'] = array(
'label' => $this->_('Maximum time difference'),
'elementClass' => 'Text',
'required' => false,
// 'size' => 5, // Causes trouble during save
'filters[int]' => 'Int',
);
if ($context['gtf_min_diff_length'] < 0) {
$output['gtf_max_diff_length']['description'] = $this->_(
'Must be negative, just like the minimal difference.'
);
$output['gtf_max_diff_length']['validators[lt]'] = new \Zend_Validate_LessThan(0);
} else {
$output['gtf_max_diff_length']['description'] = $this->_(
'Must be positive, just like the minimal difference.'
);
$output['gtf_max_diff_length']['validators[gt]'] = new \Zend_Validate_GreaterThan(0);
}
$output['gtf_max_diff_unit'] = array(
'label' => $this->_('Maximum difference unit'),
'elementClass' => 'Select',
'multiOptions' => $periodUnits,
);
}
// $output['gtf_after_next'] = array(
// 'label' => $this->_('Link ascending'),
// 'description' => $this->_('Automatically linked appointments are added in ascending (or otherwise descending) order; starting with the track start date.'),
// 'elementClass' => 'Checkbox',
// 'multiOptions' => $translated->getYesNo(),
// );
$output['gtf_uniqueness'] = array(
'label' => $this->_('Link unique'),
'description' => $this->_('Can one appointment be used in multiple fields?'),
'elementClass' => 'Radio',
'multiOptions' => array(
0 => $this->_('No: repeatedly linked appointments are allowed.'),
1 => $this->_('Track instances may link only once to an appointment.'),
2 => $this->_('Tracks of this type may link only once to an appointment.'),
// 3 => $this->_('Appointment may not be used in any other track.'),
),
);
$output['gtf_create_track'] = $this->loader->getAgenda()->getTrackCreateElement();
}
$label = false;
$description = false;
if ($context['gtf_create_track']) {
switch ($context['gtf_create_track']) {
case 1:
$label = $this->_('End date difference');
$description = $this->_('Any previous track must be closed and have an end date at least this many days in the past.');
break;
case 2:
$label = $this->_('End date difference');
$description = $this->_('Any previous track must have an end date at least this many days in the past.');
break;
case 4:
$label = $this->_('Start date difference');
$description = $this->_('Any previous track must have an start date at least this many days in the past.');
break;
case 5:
break;
}
}
if ($label && $description) {
$output['gtf_create_wait_days'] = array(
'label' => $label,
'description' => $description,
'elementClass' => 'Text',
);
} else {
unset($output['gtf_create_wait_days']);
}
return $output;
} | 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 |
protected function _isTokenInFilter(\Gems_Tracker_Token $token)
{
$result = false;
// Only if token has a success code
if ($token->getReceptionCode()->isSuccess()) {
$result = true;
}
if ($result) {
$tokenInfo = array(
'code' => $token->getSurvey()->getCode(),
'surveyid' => $token->getSurveyId(),
'tokenid' => $token->getTokenId()
);
// Now check if the tokenfilter is true
if (empty($this->tokenFilter)) {
$result = true;
} else {
$result = false;
// Now read the filter and split by track code or track id
foreach ($this->tokenFilter as $filter)
{
$remaining = array_diff_assoc($filter, $tokenInfo);
if (empty($remaining)) {
$result = true;
break;
}
}
}
}
return $result;
} | Determines if this particular token should be included
in the report
@param \Gems_Tracker_Token $token
@return boolean This dummy implementation always returns true | entailment |
protected function _isTrackInFilter(\Gems_Tracker_RespondentTrack $track)
{
$result = false;
$trackInfo = array(
'code' => $track->getCode(),
'trackid' => $track->getTrackId(),
'resptrackid' => $track->getRespondentTrackId(),
'respid' => $track->getRespondentId(),
);
if (empty($this->trackFilter)) {
$result = true;
} else {
// Now read the filter and split by track code or track id
foreach($this->trackFilter as $filter) {
$remaining = array_diff_assoc($filter, $trackInfo);
if (empty($remaining)) {
$result = true;
break;
}
}
}
// Only if track has a success code
if ($result && $track->getReceptionCode()->isSuccess()) {
return true;
}
return false;
} | Determines if this particular track should be included
in the report
@param \Gems_Tracker_RespondentTrack $track
@return boolean This dummy implementation always returns true | entailment |
protected function _exportTrackTokens(\Gems_Tracker_RespondentTrack $track)
{
$groupSurveys = $this->_group;
$token = $track->getFirstToken();
$engine = $track->getTrackEngine();
$surveys = array();
$table = $this->html->table(array('class' => 'browser table'));
$table->th($this->_('Survey'))
->th($this->_('Round'))
->th($this->_('Token'))
->th($this->_('Status'));
$this->html->br();
while ($token) {
//Should this token be in the list?
if (!$this->_isTokenInFilter($token)) {
$token = $token->getNextToken();
continue;
}
$table->tr()->td($token->getSurveyName())
->td(($engine->getTrackType() == 'T' ? $token->getRoundDescription() : $this->_('Single Survey')))
->td(strtoupper($token->getTokenId()))
->td($token->getStatus());
//Should we display the answers?
if (!$this->_displayToken($token)) {
$token = $token->getNextToken();
continue;
}
$showToken = false;
if (! $groupSurveys) {
// For single survey tracks or when $groupSurvey === false we show all tokens
$showToken = true;
} else {
// For multi survey tracks and $groupSurveys === true, we show only the first token
// as the snippet takes care of showing the other tokens
if (!isset($surveys[$token->getSurveyId()])) {
$showToken = true;
$surveys[$token->getSurveyId()] = 1;
}
}
if ($showToken) {
$params = array(
'token' => $token,
'tokenId' => $token->getTokenId(),
'showHeaders' => false,
'showButtons' => false,
'showSelected' => false,
'showTakeButton' => false,
'grouped' => $groupSurveys);
$snippets = $token->getAnswerSnippetNames();
if (!is_array($snippets)) {
$snippets = array($snippets);
}
list($snippets, $snippetParams) = \MUtil_Ra::keySplit($snippets);
$params = $params + $snippetParams;
$this->html->snippet('Export_SurveyHeaderSnippet', 'token', $token);
foreach($snippets as $snippet) {
$this->html->snippet($snippet, $params);
}
$this->html->br();
}
$token = $token->getNextToken();
}
} | Exports all the tokens of a single track, grouped by round
@param \Gems_Tracker_RespondentTrack $track | entailment |
protected function _exportTrack(\Gems_Tracker_RespondentTrack $respTrack)
{
if (!$this->_isTrackInFilter($respTrack)) {
return;
}
$trackModel = $this->loader->getTracker()->getRespondentTrackModel();
$trackModel->applyDetailSettings($respTrack->getTrackEngine(), false);
$trackModel->resetOrder();
$trackModel->set('gtr_track_name', 'label', $this->_('Track'));
$trackModel->set('gr2t_track_info', 'label', $this->_('Description'),
'description', $this->_('Enter the particulars concerning the assignment to this respondent.'));
$trackModel->set('assigned_by', 'label', $this->_('Assigned by'));
$trackModel->set('gr2t_start_date', 'label', $this->_('Start'),
'formatFunction', $this->util->getTranslated()->formatDate,
'default', \MUtil_Date::format(new \Zend_Date(), 'dd-MM-yyyy'));
$trackModel->set('gr2t_reception_code');
$trackModel->set('gr2t_comment', 'label', $this->_('Comment'));
$trackModel->setFilter(array('gr2t_id_respondent_track' => $respTrack->getRespondentTrackId()));
$trackData = $trackModel->loadFirst();
$this->html->h4($this->_('Track') . ' ' . $trackData['gtr_track_name']);
$bridge = $trackModel->getBridgeFor('itemTable', array('class' => 'browser table'));
$bridge->setRepeater(\MUtil_Lazy::repeat(array($trackData)));
$bridge->th($this->_('Track information'), array('colspan' => 2));
$bridge->setColumnCount(1);
foreach($trackModel->getItemsOrdered() as $name) {
if ($label = $trackModel->get($name, 'label')) {
$bridge->addItem($name, $label);
}
}
$tableContainer = \MUtil_Html::create()->div(array('class' => 'table-container'));
$tableContainer[] = $bridge->getTable();
$this->html[] = $tableContainer;
$this->html->br();
$this->_exportTrackTokens($respTrack);
$this->html->hr();
} | Exports a single track
@param \Gems_Tracker_RespondentTrack $respTrack | entailment |
protected function _exportRespondent($respondentId)
{
$respondentModel = $this->loader->getModels()->getRespondentModel(false);
//Insert orgId when set
if (is_array($respondentId) && isset($respondentId['gr2o_id_organization'])) {
$filter['gr2o_id_organization'] = $respondentId['gr2o_id_organization'];
$respondentId = $respondentId['gr2o_patient_nr'];
} else {
// Or accept to find in current organization
// $filter['gr2o_id_organization'] = $this->currentUser->getCurrentOrganizationId();
// Or use any allowed organization?
$filter['gr2o_id_organization'] = array_keys($this->currentUser->getAllowedOrganizations());
}
$filter['gr2o_patient_nr'] = $respondentId;
$respondentModel->setFilter($filter);
$respondentData = $respondentModel->loadFirst();
$this->html->snippet($this->_respondentSnippet,
'model', $respondentModel,
'data', $respondentData,
'respondentId', $respondentId);
$tracker = $this->loader->getTracker();
$tracks = $tracker->getRespondentTracks($respondentData['gr2o_id_user'], $respondentData['gr2o_id_organization']);
foreach ($tracks as $trackId => $track) {
$this->_exportTrack($track);
}
} | Exports a single respondent
@param string $respondentId | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->_pdf = $this->loader->getPdf();
$this->escort = \GemsEscort::getInstance();
$this->html = new \MUtil_Html_Sequence();
$this->request = \Zend_Controller_Front::getInstance()->getRequest();
// Do not know why, but for some reason menu is not loaded automatically.
$this->menu = $this->loader->getMenu();
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function getForm($hideGroup = false)
{
$form = new \Gems_Form();
$form->setAttrib('target', '_blank');
if ($hideGroup) {
$element = new \Zend_Form_Element_Hidden('group');
} else {
$element = new \Zend_Form_Element_Checkbox('group');
$element->setLabel($this->_('Group surveys'));
}
$element->setValue(1);
$form->addElement($element);
$element = new \Zend_Form_Element_Select('format');
$element->setLabel($this->_('Output format'));
$outputFormats = array('html' => 'HTML');
if ($this->_pdf->hasPdfExport()) {
$outputFormats['pdf'] = 'PDF';
$element->setValue('pdf');
}
$element->setMultiOptions($outputFormats);
$form->addElement($element);
$element = new \Zend_Form_Element_Submit('export');
$element->setLabel($this->_('Export'))
->setAttrib('class', 'button');
$form->addElement($element);
$links = $this->menu->getMenuList();
$links->addParameterSources($this->request, $this->menu->getParameterSource());
$links->addCurrentParent($this->_('Cancel'));
if (count($links)) {
$element = new \MUtil_Form_Element_Html('menuLinks');
$element->setValue($links);
// $element->setOrder(999);
$form->addElement($element);
}
return $form;
} | Constructs the form
@param boolean $hideGroup When true group checkbox is hidden
@return \Gems_Form_TableForm | entailment |
public function render($respondents, $group = true, $format = 'html')
{
$this->_group = $group;
$this->html->snippet($this->_reportHeader);
$respondentCount = count($respondents);
$respondentIdx = 0;
foreach ($respondents as $respondentId) {
$respondentIdx++;
$this->_exportRespondent($respondentId);
if ($respondentIdx < $respondentCount) {
// Add some whitespace between patients
$this->html->div('', array('style' => 'height: 100px'));
}
}
$this->html->snippet($this->_reportFooter, 'respondents', $respondents);
$this->menu->setVisible(false);
if ($this->escort instanceof \Gems_Project_Layout_MultiLayoutInterface) {
$this->escort->layoutSwitch();
}
$this->escort->postDispatch($this->request);
\Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->disableLayout();
\Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender(true);
$this->view->layout()->content = $this->html->render($this->view);
$content = $this->view->layout->render();
if ($format == 'pdf') {
if (is_array($respondentId) && isset($respondentId['gr2o_id_organization'])) {
$respondentId = $respondentId['gr2o_patient_nr'];
}
$filename = 'respondent-export-' . strtolower($respondentId) . '.pdf';
$content = $this->_pdf->convertFromHtml($content);
$this->_pdf->echoPdfContent($content, $filename, true);
} else {
echo $content;
}
$this->menu->setVisible(true);
} | Renders the entire report (including layout)
@param array|string[] $respondentId
@param boolean $group Group same surveys or not
@param string $format html|pdf, the output format to use | entailment |
public function getFieldsTranslations()
{
$fieldList = parent::getFieldsTranslations();
// Add the key values (so organization id is present)
$keys = array_combine(array_values($this->_targetModel->getKeys()), array_values($this->_targetModel->getKeys()));
$fieldList = $fieldList + $keys;
$fieldList['grs_email'] = 'gr2o_email';
return $fieldList;
} | Get information on the field translations
@return array of fields sourceName => targetName
@throws \MUtil_Model_ModelException | entailment |
public function translateRowValues($row, $key)
{
$row = parent::translateRowValues($row, $key);
if (! $row) {
return false;
}
if ((! isset($row['grs_id_user'])) && isset($row['gr2o_patient_nr'], $row['gr2o_id_organization'])) {
$sql = 'SELECT gr2o_id_user
FROM gems__respondent2org
WHERE gr2o_patient_nr = ? AND gr2o_id_organization = ?';
$id = $this->db->fetchOne($sql, array($row['gr2o_patient_nr'], $row['gr2o_id_organization']));
if ($id) {
$row['grs_id_user'] = $id;
$row['gr2o_id_user'] = $id;
}
}
if (empty($row['gr2o_email'])) {
$row['calc_email'] = 1;
}
return $row;
} | Perform any translations necessary for the code to work
@param mixed $row array or \Traversable row
@param scalar $key
@return mixed Row array or false when errors occurred | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$seq = $this->getHtmlSequence();
$seq->h2($this->_('Checks'));
$ul = $seq->ul();
$ul->li($this->_('Updates existing token description and order to the current round description and order.'));
$ul->li($this->_('Updates the survey of unanswered tokens when the round survey was changed.'));
$ul->li($this->_('Removes unanswered tokens when the round is no longer active.'));
$ul->li($this->_('Creates new tokens for new rounds.'));
$ul->li($this->_(
'Checks the validity dates and times of unanswered tokens, using the current round settings.'
));
$seq->pInfo($this->_(
'Run this code when a track has changed or when the code has changed and the track must be adjusted.'
));
$seq->pInfo($this->_(
'If you do not run this code after changing a track, then the old tracks remain as they were and only newly created tracks will reflect the changes.'
));
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 getChanges(array $context, $new)
{
$conditions = $this->loader->getConditions();
$options = $this->util->getTranslated()->getEmptyDropdownArray();
if (isset($context['gcon_type'])) {
$options = $conditions->listConditionsForType($context['gcon_type']);
reset($options);
$default = key($options);
}
return ['gcon_class' => ['multiOptions' => $options, 'default' => 'default']];
} | 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 |
protected function _checkDir($directory)
{
$eDir = @dir($directory);
if (false == $eDir) {
// Dir does probably not exist
if (!is_dir($directory)) {
if (false === @mkdir($directory, 0777, true)) {
\MUtil_Echo::pre(sprintf($this->translate->_('Directory %s not found and unable to create'), $directory), 'OpenRosa ERROR');
} else {
$eDir = @dir($directory);
}
}
}
return $eDir;
} | Open the dir, suppressing possible errors and try to
create when it does not exist
@param type $directory
@return Directory | entailment |
protected function _getSourceSurveysForSynchronisation()
{
// First scan for new definitions
$this->_scanForms();
// Surveys in OpenRosa
$db = $this->getSourceDatabase();
$select = $db->select();
$select->from('gems__openrosaforms', ['gof_id']);
return $db->fetchCol($select);
} | Returns all surveys for synchronization
@return array of sourceId values or false | entailment |
public function checkSourceActive($userId)
{
$active = true;
$values['gso_active'] = $active ? 1 : 0;
$values['gso_status'] = $active ? 'Active' : 'Inactive';
$this->_updateSource($values, $userId);
return $active;
} | Checks wether this particular source is active or not and should handle updating the gems-db
with the right information about this source
@param int $userId Id of the user who takes the action (for logging)
@return boolean | entailment |
public function getAnswerDateTime($fieldName, \Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
{
$answers = $token->getRawAnswers();
if (isset($answers[$fieldName]) && $answers[$fieldName]) {
if (\Zend_Date::isDate($answers[$fieldName], \Zend_Date::ISO_8601)) {
return new \MUtil_Date($answers[$fieldName], \Zend_Date::ISO_8601);
}
if (\Gems_Tracker::$verbose) {
\MUtil_Echo::r($answers[$fieldName], 'Missed answer date value:');
}
}
} | Returns a field from the raw answers as a date object.
A seperate function as only the source knows what format the date/time value has.
@param string $fieldName Name of answer field
@param \Gems_Tracker_Token $token Gems token object
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return \MUtil_Date date time or null | entailment |
public function getCompletionTime(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
if ($name = $model->getMeta('start')) {
return $this->getAnswerDateTime($name, $token, $surveyId);
}
return null;
} | Gets the time the survey was completed according to the source
A source always return null when it does not know this time (or does not know
it well enough). In the case \Gems_Tracker_Token will do it's best to keep
track by itself.
@param \Gems_Tracker_Token $token Gems token object
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return \MUtil_Date date time or null | entailment |
public function getDatesList($language, $surveyId, $sourceSurveyId = null)
{
$result = [];
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$dateItems = $model->getItemsFor('type', Mutil_model::TYPE_DATETIME) + $model->getItemsFor('type', Mutil_model::TYPE_DATE);
foreach ($dateItems as $name)
{
if ($label = $model->get($name, 'label')) {
$result[$name] = $label;
}
}
return $result;
} | Returns an array containing fieldname => label for each date field in the survey.
Used in dropdown list etc..
@param string $language (ISO) language string
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array fieldname => label | entailment |
public function getFullQuestionList($language, $surveyId, $sourceSurveyId = null)
{
return $this->getQuestionList($language, $surveyId, $sourceSurveyId);
} | Returns an array of arrays with the structure:
question => string,
class => question|question_sub
group => is for grouping
type => (optional) source specific type
answers => string for single types,
array for selection of,
nothing for no answer
@param string $language (ISO) language string
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array Nested array
@deprecated since version 1.8.4 remove in 1.8.5 | entailment |
public function getQuestionInformation($language, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$result = [];
foreach($model->getItemsOrdered() as $name) {
if ($label = $model->get($name, 'label')) {
$result[$name]['question'] = $label;
if ($answers = $model->get($name, 'multiOptions')) {
$result[$name]['answers'] = $answers;
}
}
}
if ($model->getMeta('nested', false)) {
// We have a nested model, add the nested questions
$nestedNames = $model->getMeta('nestedNames');
foreach($nestedNames as $nestedName) {
if ($nestedName instanceof \Gems_Model_JoinModel) {
$nestedModel = $nestedName;
} else {
$nestedModel = $model->get($nestedName, 'model');
}
foreach($nestedModel->getItemsOrdered() as $name) {
if ($label = $nestedModel->get($name, 'label')) {
$result[$name]['question'] = $label;
if ($answers = $nestedModel->get($name, 'multiOptions')) {
$result[$name]['answers'] = $answers;
}
}
}
}
}
return $result;
} | Returns an array of arrays with the structure:
question => string,
class => question|question_sub
group => is for grouping
type => (optional) source specific type
answers => string for single types,
array for selection of,
nothing for no answer
@param string $language (ISO) language string
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array Nested array | entailment |
public function getQuestionList($language, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$result = [];
foreach($model->getItemsOrdered() as $name) {
if ($label = $model->get($name, 'label')) {
$result[$name] = $label;
}
}
if ($model->getMeta('nested', false)) {
foreach ($model->getMeta('nestedNames') as $name) {
// We have a nested model, add the nested questions
$nestedModel = $model->get($name, 'model');
foreach($nestedModel->getItemsOrdered() as $name) {
if ($label = $nestedModel->get($name, 'label')) {
$result[$name] = $label;
}
}
}
}
return $result;
} | Returns an array containing fieldname => label for dropdown list etc..
@param string $language (ISO) language string
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array fieldname => label | entailment |
public function getRawTokenAnswerRow($tokenId, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$result = $model->loadFirst(['token' => $tokenId]);
return $result;
} | Returns the answers in simple raw array format, without value processing etc.
Function may return more fields than just the answers.
@param string $tokenId Gems Token Id
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array Field => Value array | entailment |
public function getRawTokenAnswerRows(array $filter, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$answers = $model->load($filter);
$data = [];
foreach($answers as $key=>$answer) {
$data[$answer['token']] = $answer;
}
if ($data) {
return $data;
}
return [];
} | Returns the answers of multiple tokens in simple raw nested array format,
without value processing etc.
Function may return more fields than just the answers.
The $filter param is an array of filters to apply to the selection, it has
some special formatting rules. The key is the db-field to filter on and the
value could be a value or an array of values to filter on.
Special keys that should be mapped to the right field by the source are:
respondentid
organizationid
consentcode
token
So a filter of [token]=>[abc-def][def-abc] will return the results for these two tokens
while a filter of [organizationid] => 70 will return all results for this organization.
@param array $filter filter array
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return array Of nested Field => Value arrays indexed by tokenId | entailment |
public function getRawTokenAnswerRowsSelect(array $filter, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
$select = $model->getSelect();
$this->filterLimitOffset($filter, $select);
return $select;
} | Get the select object to use for RawTokenAnswerRows
@param array $filter
@param type $surveyId
@param type $sourceSurveyId
@return \Zend_Db_Select | entailment |
public function getSurveyInfo($sourceSurveyId)
{
$db = $this->getSourceDatabase();
$select = $db->select();
$select->from('gems__openrosaforms')
->where('gof_id = ?', $sourceSurveyId);
return $db->fetchRow($select);
} | Return info about the survey (row from gems__openrosaforms)
@param int $sourceSurveyId
@return array | entailment |
public function getSurveyAnswerModel(\Gems_Tracker_Survey $survey, $language = null, $sourceSurveyId = null)
{
if (null === $sourceSurveyId) {
$sourceSurveyId = $this->_getSid($survey->getSurveyId());
}
$model = $this->createModel($survey);
$model->set('gto_id_token', 'label', $this->_('Token'), 'elementClass', 'Exhibitor');
$surveyForm = $this->getSurvey($survey->getSurveyId(), $sourceSurveyId);
$surveyModel = $this->getSurvey($survey->getSurveyId(), $sourceSurveyId)->getModel();
$model->setMeta('openroseTableName', $surveyForm->getTableName());
$model->setMeta('internalAttributes', true);
/*$questionsList = $this->getQuestionList($language, $survey->getSurveyId(), $sourceSurveyId);
foreach($questionsList as $item => $question) {
$allOptions = $surveyModel->get($item);
$allowed = array_fill_keys(array('storageFormat', 'dateFormat', 'label', 'multiOptions', 'maxlength', 'type', 'itemDisplay', 'formatFunction'),1);
$options = array_intersect_key($allOptions, $allowed);
$options['label'] = strip_tags($question);
$options['survey_question'] = true;
//Should also do something to get the better titles...
$model->set($item, $options);
}
return $model;
*/
foreach($surveyModel->getItemsOrdered() as $name) {
$label = $surveyModel->get($name, 'label');
if ($label) {
$options = $surveyModel->get($name);
unset($options['table']);
$options['label'] = strip_tags($label);
$options['label_raw'] = $label;
$options['survey_question'] = true;
//Should also do something to get the better titles...
$model->set($name, $options);
}
}
if ($tableIdField = $model->getTableIdField()) {
if ($surveyModel->has($tableIdField) && !$surveyModel->get($tableIdField, 'label')) {
$options = $surveyModel->get($name);
unset($options['table']);
$model->set($tableIdField, $options);
}
}
if ($surveyModel->getMeta('nested', false)) {
$model->setMeta('nested', true);
// We have a nested model, add the nested questions
$nestedNames = $surveyModel->getMeta('nestedNames');
$model->setMeta('nestedNames', $nestedNames);
foreach($nestedNames as $nestedName) {
$nestedModel = $surveyModel->get($nestedName, 'model');
if ($nestedModel instanceof \MUtil_Model_ModelAbstract) {
$model->addListModel($nestedModel, array('orf_id' => 'orfr_response_id'));
$model->set($nestedName, 'label', $surveyModel->get($nestedName, 'label'),
'elementClass', 'FormTable'
);
$model->setMeta('nestedNames', $nestedNames);
}
}
}
$model->del('token');
return $model;
} | Returns a model for the survey answers
@param \Gems_Tracker_Survey $survey
@param string $language Optional (ISO) language string
@param string $sourceSurveyId Optional Survey Id used by source
@return \MUtil_Model_ModelAbstract | entailment |
public function getToken($tokenId)
{
$tracker = $this->loader->getTracker();
$token = $tracker->getToken($tokenId);
return $token;
} | Returns a Gems Tracker token from a token ID
@param string $tokenId Gems Token Id
@return \Gems_Tracker_Token
@deprecated | entailment |
public function getTokenUrl(\Gems_Tracker_Token $token, $language, $surveyId, $sourceSurveyId)
{
// There is no url, so return null
$basePath = \GemsEscort::getInstance()->basePath->__toString();
return $basePath . '/open-rosa-form/edit/id/' . $token->getTokenId();
} | Returns the url that (should) start the survey for this token
@param \Gems_Tracker_Token $token Gems token object
@param string $language
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return string The url to start the survey | entailment |
public function isCompleted(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
{
$result = $this->getRawTokenAnswerRow($token->getTokenId(), $surveyId);
$completed = !empty($result);
return $completed;
} | Returns true if the survey was completed according to the source
@param \Gems_Tracker_Token $token Gems token object
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return boolean True if the token has completed | entailment |
public function checkSurvey($sourceSurveyId, $surveyId, $userId)
{
$changed = 0;
$created = false;
$deleted = false;
$deletedFile = false;
$survey = $this->tracker->getSurvey($surveyId);
// Get OpenRosa data
if ($sourceSurveyId) {
// Surveys in OpenRose
$db = $this->getSourceDatabase();
$select = $db->select();
$select->from('gems__openrosaforms')
->where('gof_id = ?', $sourceSurveyId);
$openRosaSurvey = $db->fetchRow($select);
} else {
$openRosaSurvey = false;
}
if ($openRosaSurvey) {
// Exists
$values['gsu_survey_name'] = sprintf(
'%s [%s]',
$openRosaSurvey['gof_form_title'],
$openRosaSurvey['gof_form_version']
);
$values['gsu_status'] = 'OK';
$values['gsu_surveyor_active'] = $openRosaSurvey['gof_form_active'];
if (!$surveyId) {
// New
$values['gsu_active'] = 0;
$values['gsu_id_source'] = $this->getId();
$values['gsu_surveyor_id'] = $sourceSurveyId;
$created = true;
}
if (!$this->sourceFileExists($openRosaSurvey['gof_form_xml'])) {
// No longer exists
$values['gsu_surveyor_active'] = 0;
$values['gsu_status'] = 'Survey form XML was removed from directory.';
$deletedFile = true;
}
} else {
// No longer exists
$values['gsu_surveyor_active'] = 0;
$values['gsu_status'] = 'Survey was removed from source.';
$deleted = true;
}
$changed = $survey->saveSurvey($values, $userId);
if (! $changed) {
return;
}
if ($deleted) {
$message = $this->_('The \'%s\' survey is no longer active. The survey was removed from OpenRosa!');
} elseif ($deletedFile) {
$message = $this->_('The \'%s\' survey is no longer active. The survey XML file was removed from its directory!');
} elseif ($created) {
$message = $this->_('Imported the \'%s\' survey.');
} else {
$message = $this->_('Updated the \'%s\' survey.');
}
return sprintf($message, $survey->getName());;
} | Survey source synchronization check function
@param string $sourceSurveyId
@param int $surveyId
@param int $userId
@return mixed message string or array of messages | entailment |
public function setRawTokenAnswers(\Gems_Tracker_Token $token, array $answers, $surveyId, $sourceSurveyId = null)
{
$survey = $this->getSurvey($surveyId, $sourceSurveyId);
$model = $survey->getModel();
// new \Zend_Db_Table(array('db' => $this->getSourceDatabase(), 'name' => 'odk__etc'))
$answers['token'] = $answers['gto_id_token'];
$model->save($answers);
return $model->getChanged();
} | Sets the answers passed on.
@param \Gems_Tracker_Token $token Gems token object
@param $answers array Field => Value array
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source | entailment |
protected function sourceFileExists($filename)
{
$fullFilename = $this->formDir . $filename;
if (file_exists($fullFilename)) {
return true;
}
return false;
} | Check if the xml file still exists in the directory
@param $filename
@return bool | entailment |
private function _checkForMailSent($isNew, array $context)
{
// Never change on new tokens
if ($isNew) {
return false;
}
// Only act on existing valid from date
if (! (isset($context['gto_valid_from']) && $context['gto_valid_from'])) {
return false;
}
// There must be data to reset
$hasSentDate = isset($context['gto_mail_sent_date']) && $context['gto_mail_sent_date'];
if (! ($hasSentDate || (isset($context['gto_mail_sent_num']) && $context['gto_mail_sent_num']))) {
return false;
}
// When only the sent_num is set, then clear the existing data
if (! $hasSentDate) {
return true;
}
if ($context['gto_valid_from'] instanceof \Zend_Date) {
$start = $context['gto_valid_from'];
} else {
$start = new \MUtil_Date($context['gto_valid_from'], $this->get('gto_valid_from', 'dateFormat'));
}
if ($context['gto_mail_sent_date'] instanceof \Zend_Date) {
$sent = $context['gto_mail_sent_date'];
} else {
$sent = new \MUtil_Date($context['gto_mail_sent_date'], $this->get('gto_mail_sent_date', 'dateFormat'));
}
return $start->isLater($sent);
} | Function to check whether the mail_sent should be reset
@param boolean $isNew True when a new item is being saved
@param array $context The values being saved
@return boolean True when the change should be triggered | entailment |
public function addEditTracking()
{
// Old code
// $changer = new \MUtil_Model_Type_ChangeTracker($this, 1, 0);
//
// $changer->apply('gto_valid_from_manual', 'gto_valid_from');
// $changer->apply('gto_valid_until_manual', 'gto_valid_until');
$this->addDependency(new OffOnElementsDependency('gto_valid_from_manual', 'gto_valid_from', 'readonly', $this));
$this->addDependency(new OffOnElementsDependency('gto_valid_until_manual', 'gto_valid_until', 'readonly', $this));
$this->set('gto_valid_until', 'validators[dateAfter]',
new \MUtil_Validate_Date_DateAfter('gto_valid_from')
);
return $this;
} | Add tracking off manual date changes by the user
@param mixed $value The value to store when the tracked field has changed
@return \Gems_Tracker_Model_StandardTokenModel | entailment |
public function afterRegistry()
{
parent::afterRegistry();
//If we are allowed to see who filled out a survey, modify the model accordingly
if ($this->currentUser->hasPrivilege('pr.respondent.who')) {
$this->addLeftTable('gems__staff', array('gto_by' => 'gems__staff_2.gsf_id_user'));
$this->addColumn(new \Zend_Db_Expr('CASE
WHEN gems__staff_2.gsf_id_user IS NULL THEN COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)
ELSE CONCAT_WS(
" ",
CONCAT(COALESCE(gems__staff_2.gsf_last_name, "-"), ","),
gems__staff_2.gsf_first_name,
gems__staff_2.gsf_surname_prefix
)
END'), 'ggp_name');
} else {
$this->set('ggp_name', 'column_expression', new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)'));
}
if ($this->currentUser->hasPrivilege('pr.respondent.result')) {
$this->addColumn('gto_result', 'calc_result', 'gto_result');
} else {
$this->addColumn(new \Zend_Db_Expr('NULL'), 'calc_result', 'gto_result');
}
$this->addColumn($this->util->getTokenData()->getStatusExpression(), 'token_status');
$this->set('forgroup', 'column_expression', new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, ggp_name)'));
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function applyFormatting()
{
$this->resetOrder();
$dbLookup = $this->util->getDbLookup();
$translated = $this->util->getTranslated();
// Token id & respondent
$this->set('gto_id_token', 'label', $this->_('Token'),
'elementClass', 'Exhibitor',
'formatFunction', 'strtoupper'
);
$this->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'),
'elementClass', 'Exhibitor'
);
$this->set('respondent_name', 'label', $this->_('Respondent name'),
'elementClass', 'Exhibitor'
);
$this->set('gto_id_organization', 'label', $this->_('Organization'),
'elementClass', 'Exhibitor',
'multiOptions', $dbLookup->getOrganizationsWithRespondents()
);
// Track, round & survey
$this->set('gtr_track_name', 'label', $this->_('Track'),
'elementClass', 'Exhibitor'
);
$this->set('gr2t_track_info', 'label', $this->_('Description'),
'elementClass', 'Exhibitor'
);
$this->set('gto_round_description', 'label', $this->_('Round'),
'elementClass', 'Exhibitor'
);
$this->set('gsu_survey_name', 'label', $this->_('Survey'),
'elementClass', 'Exhibitor'
);
$this->set('ggp_name', 'label', $this->_('Assigned to'),
'elementClass', 'Exhibitor'
);
// Token, editable part
$manual = $translated->getDateCalculationOptions();
$this->set('gto_valid_from_manual', 'label', $this->_('Set valid from'),
'description', $this->_('Manually set dates are fixed an will never be (re)calculated.'),
'elementClass', 'Radio',
'multiOptions', $manual,
'separator', ' '
);
$this->set('gto_valid_from', 'label', $this->_('Valid from'),
'elementClass', 'Date',
'formatFunction', $translated->formatDateNever,
'tdClass', 'date');
$this->set('gto_valid_until_manual', 'label', $this->_('Set valid until'),
'description', $this->_('Manually set dates are fixed an will never be (re)calculated.'),
'elementClass', 'Radio',
'multiOptions', $manual,
'separator', ' '
);
$this->set('gto_valid_until', 'label', $this->_('Valid until'),
'elementClass', 'Date',
'formatFunction', $translated->formatDateForever,
'tdClass', 'date');
$this->set('gto_comment', 'label', $this->_('Comments'),
'cols', 50,
'elementClass', 'Textarea',
'rows', 3,
'tdClass', 'pre'
);
// Token, display part
$this->set('gto_mail_sent_date', 'label', $this->_('Last contact'),
'elementClass', 'Exhibitor',
'formatFunction', $translated->formatDateNever,
'tdClass', 'date');
$this->set('gto_mail_sent_num', 'label', $this->_('Number of contact moments'),
'elementClass', 'Exhibitor'
);
$this->set('gto_completion_time', 'label', $this->_('Completed'),
'elementClass', 'Exhibitor',
'formatFunction', $translated->formatDateNa,
'tdClass', 'date');
$this->set('gto_duration_in_sec', 'label', $this->_('Duration in seconds'),
'elementClass', 'Exhibitor'
);
$this->set('gto_result', 'label', $this->_('Score'),
'elementClass', 'Exhibitor'
);
$this->set('grc_description', 'label', $this->_('Reception code'),
'formatFunction', array($this->translate, '_'),
'elementClass', 'Exhibitor'
);
$this->set('gto_changed', 'label', $this->_('Changed on'),
'elementClass', 'Exhibitor',
'formatFunction', $translated->formatDateUnknown
);
$this->set('assigned_by', 'label', $this->_('Assigned by'),
'elementClass', 'Exhibitor'
);
$this->refreshGroupSettings();
return $this;
} | Sets the labels, format functions, etc...
@return \Gems_Tracker_Model_StandardTokenModel | entailment |
public function saveCheckedMailDate($value, $isNew = false, $name = null, array $context = array())
{
if ($this->_checkForMailSent($isNew, $context)) {
return null;
}
return $this->formatSaveDate($value, $isNew, $name, $context);
} | A ModelAbstract->setOnSave() function that can transform the saved item.
@see setSaveWhen()
@param mixed $value The value being saved
@param boolean $isNew True when a new item is being saved
@param string $name The name of the current field
@param array $context Optional, the other values being saved
@return boolean | entailment |
public function saveCheckedMailNum($value, $isNew = false, $name = null, array $context = array())
{
if ($this->_checkForMailSent($isNew, $context)) {
return 0;
}
return $value;
} | A ModelAbstract->setOnSave() function that can transform the saved item.
@see setSaveWhen()
@param mixed $value The value being saved
@param boolean $isNew True when a new item is being saved
@param string $name The name of the current field
@param array $context Optional, the other values being saved
@return boolean | entailment |
public function createModel($detailed, $action)
{
$model = new \MUtil_Model_TableModel('gems__mail_servers');
\Gems_Model::setChangeFieldsByPrefix($model, 'gms');
// Key can be changed by users
$model->copyKeys();
$model->set('gms_from',
'label', $this->_('From address [part]'),
'size', 30,
'description', $this->_("E.g.: '%', '%.org' or '%@gemstracker.org' or '[email protected]'."));
$model->set('gms_server', 'label', $this->_('Server'), 'size', 30);
$model->set('gms_ssl',
'label', $this->_('Encryption'),
'required', false,
'multiOptions', array(
\Gems_Mail::MAIL_NO_ENCRYPT => $this->_('None'),
\Gems_Mail::MAIL_SSL => $this->_('SSL'),
\Gems_Mail::MAIL_TLS => $this->_('TLS')));
$model->set('gms_port',
'label', $this->_('Port'),
'required', true,
'description', $this->_('Normal values: 25 for TLS and no encryption, 465 for SSL'),
'validator', 'Digits');
$model->set('gms_user', 'label', $this->_('User ID'), 'size', 20);
if ($detailed) {
$model->set('gms_password',
'label', $this->_('Password'),
'elementClass', 'Password',
'repeatLabel', $this->_('Repeat password'),
'description', $this->_('Enter only when changing'));
$type = new \Gems_Model_Type_EncryptedField($this->project, true);
$type->apply($model, 'gms_password');
}
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);
$appId = $this->request->getParam(\Gems_Model::APPOINTMENT_ID);
if ($appId) {
$appKeyPrefix = $this->db->quote(FieldsDefinition::makeKey(FieldMaintenanceModel::APPOINTMENTS_NAME, ''));
$appSource = $this->db->quote(\Gems_Tracker_Engine_StepEngineAbstract::APPOINTMENT_TABLE);
$or[] = $this->db->quoteInto(
"gro_valid_after_source = $appSource AND
(gto_id_respondent_track, gro_valid_after_field) IN
(SELECT gr2t2a_id_respondent_track, CONCAT($appKeyPrefix, gr2t2a_id_app_field)
FROM gems__respondent2track2appointment
WHERE gr2t2a_id_appointment = ?)",
$appId
);
$or[] = $this->db->quoteInto(
"gro_valid_for_source = $appSource AND
(gto_id_respondent_track, gro_valid_for_field) IN
(SELECT gr2t2a_id_respondent_track, CONCAT($appKeyPrefix, gr2t2a_id_app_field)
FROM gems__respondent2track2appointment
WHERE gr2t2a_id_appointment = ?)",
$appId
);
}
$model->addFilter(array('(' . implode(') OR (', $or) . ')'));
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function _toNavigationArray(\Gems_Menu_ParameterCollector $source)
{
$result = parent::_toNavigationArray($source);
$store = self::_getSessionStore($this->get('label'));
if (isset($store->controller)) {
foreach ($result['pages'] as $page) {
if ($page['controller'] === $store->controller) {
if (isset($store->action) && $page['action'] === $store->action) {
$result['action'] = $store->action;
$this->set('action', $store->action);
}
$result['controller'] = $store->controller;
$this->set('controller', $store->controller);
}
}
}
// Get any missing MVC keys from children, even when invisible
if ($requiredIndices = $this->notSet('controller', 'action')) {
if (isset($result['pages'])) {
$firstChild = null;
$order = 0;
foreach ($result['pages'] as $page) {
if ($page['allowed']) {
if ($page['order'] < $order || $order == 0) {
$firstChild = $page;
$order = $page['order'];
}
}
}
if (null === $firstChild) {
// No children are visible and required mvc properties
// are missing: ergo this page is not visible.
$result['visible'] = false;
// Use first (invisible) child as firstChild
$firstChild = reset($result['pages']);
}
} else {
// Use '/' slash as default to ensure any not visible
// menu items points to another existing item that is
// active.
$firstChild = array_fill_keys($requiredIndices, '/');
}
foreach ($requiredIndices as $key) {
$result[$key] = $firstChild[$key];
}
}
return $result;
} | Returns a \Zend_Navigation creation array for this menu item, with
sub menu items in 'pages'
@param \Gems_Menu_ParameterCollector $source
@return array | entailment |
protected function applyAcl(\MUtil_Acl $acl, $userRole)
{
parent::applyAcl($acl, $userRole);
if ($this->isVisible()) {
$this->set('allowed', false);
$this->set('visible', false);
if ($this->_subItems) {
foreach ($this->_subItems as $item) {
if ($item->get('visible', true)) {
$this->set('allowed', true);
$this->set('visible', true);
return $this;
}
}
}
}
return $this;
} | Set the visibility of the menu item and any sub items in accordance
with the specified user role.
@param \Zend_Acl $acl
@param string $userRole
@return \Gems_Menu_MenuAbstract (continuation pattern) | entailment |
protected function setBranchVisible(array $activeBranch)
{
parent::setBranchVisible($activeBranch);
$child = end($activeBranch);
$store = self::_getSessionStore($this->get('label'));
$contr = $child->get('controller');
$action = $child->get('action');
$store->controller = $contr;
$store->action = $action;
$this->set('controller', $contr);
$this->set('action', $action);
return $this;
} | Make sure only the active branch is visible
@param array $activeBranch Of \Gems_Menu_Menu Abstract items
@return \Gems_Menu_MenuAbstract (continuation pattern) | entailment |
public function createModel($detailed, $action)
{
$model = new \Gems\Model\ExportDbaModel($this->db, $this->escort->getDatabasePaths());
if ($this->project->databaseFileEncoding) {
$model->setFileEncoding($this->project->databaseFileEncoding);
}
$model->set('name', 'label', $this->_('Name'));
//$model->set('exportTable','label', $this->_('Table'), 'formatFunction', [$this, 'visualBoolean']);
$model->set('respondentData', 'label', $this->_('Respondent data'), 'formatFunction', [$this, 'visualBoolean']);
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 backupAction()
{
$filter = $this->getSearchFilter();
$model = $this->getModel();
$tables = $model->load();
$allTables = [];
$noDataTables = [];
foreach($tables as $table) {
if ($table['type'] == 'view' && (!array_key_exists('include_views', $filter) || $filter['include_views'] != '1')) {
continue;
}
$allTables[] = $table['name'];
if ($table['respondentData'] === true && (!array_key_exists('include_respondent_data', $filter) || $filter['include_respondent_data'] != '1')) {
$noDataTables[] = $table['name'];
}
}
$filename = $this->getBackupFilename($filter);
$dbConfig = $this->getDatabaseConfig();
$dumpSettings = [
'include-tables' => $allTables,
'no-data' => $noDataTables,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => false,
'add-drop-table' => true,
];
ini_set('max_execution_time', 300);
try {
$dump = new \Ifsnop\Mysqldump\Mysqldump($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'], $dumpSettings);
$dump->start($filename);
echo sprintf($this->_('Database backup completed. File can be found in %s'), $filename);
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
} | Action for the actual backup of the database | entailment |
protected function getDatabaseConfig()
{
$config = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$resources = $config->getOption('resources');
$dbConfig = [
'driver' => $resources['db']['adapter'],
'hostname' => $resources['db']['params']['host'],
'database' => $resources['db']['params']['dbname'],
'username' => $resources['db']['params']['username'],
'password' => $resources['db']['params']['password'],
'charset' => $resources['db']['params']['charset'],
'dsn' => sprintf('mysql:host=%s;dbname=%s', $resources['db']['params']['host'], $resources['db']['params']['dbname']),
];
return $dbConfig;
} | Get the current database config, including a DSN
@return array | entailment |
protected function getBackupFilename($filter)
{
$directory = GEMS_ROOT_DIR . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'backup';
\MUtil_File::ensureDir($directory);
$directory .= DIRECTORY_SEPARATOR;
$backupName = 'gems_backup_';
if (!array_key_exists('include_respondent_data', $filter) || $filter['include_respondent_data'] == '1') {
$backupName .= 'no_respondent_data_';
}
$now = new \DateTime();
$backupName .= $now->format('Ymd');
$backupName .= '.sql';
return $directory . $backupName;
} | Get the string name of the backup file.
With current settings this file will be written in /var/backup/gems_backup_YYYYMMDD.sql or
/var/backup/gems_backup_no_respondent_data_YYYYMMDD.sql if respondent data is not included
@param $filter
@return string
@throws Zend_Exception | entailment |
public function getSearchFilter($useRequest = true)
{
$filter = parent::getSearchFilter($useRequest);
if (!array_key_exists('include_views', $filter) || $filter['include_views'] != '1') {
$filter['type'] = 'table';
}
return $filter;
} | Get the filter to use with the model for searching including model sorts, etc..
@param boolean $useRequest Use the request as source (when false, the session is used)
@return array or false | entailment |
public function visualBoolean($value)
{
if ($value === true) {
//return '<i>O</i>';
return \MUtil_Html::create()->i(['class' => 'fa fa-check', 'style' => 'color: green;']);
}
return \MUtil_Html::create()->i(['class' => 'fa fa-times', 'style' => 'color: red;']);
} | Show a check or cross for true or false values
@param bool $value
@return mixed | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($model->has('row_class')) {
$bridge->getTable()->tbody()->getFirst(true)->appendAttrib('class', $bridge->row_class);
}
if ($this->showMenu) {
$showMenuItems = $this->getShowMenuItems();
foreach ($showMenuItems as $menuItem) {
$bridge->addItemLink($menuItem->toActionLinkLower($this->request, $bridge));
}
}
// Newline placeholder
$br = \MUtil_Html::create('br');
$by = \MUtil_Html::raw($this->_(' / '));
$sp = \MUtil_Html::raw(' ');
// make sure search results are highlighted
$this->applyTextMarker();
if ($this->currentUser->areAllFieldsMaskedWhole('respondent_name', 'grs_surname_prefix', 'grco_address')) {
$bridge->addMultiSort('grco_created', $br, 'gr2o_patient_nr', $br, 'gtr_track_name');
} else {
$bridge->addMultiSort('grco_created', $br, 'gr2o_patient_nr', $sp, 'respondent_name', $br, 'grco_address', $br, 'gtr_track_name');
}
$bridge->addMultiSort('grco_id_token', $br, 'assigned_by', $br, 'grco_sender', $br, 'gsu_survey_name');
$bridge->addMultiSort('status', $by, 'filler', $br, 'grco_topic');
if ($this->showMenu) {
$items = $this->findMenuItems('track', 'show');
$links = array();
$params = array('gto_id_token' => $bridge->gto_id_token, \Gems_Model::ID_TYPE => 'token');
$title = \MUtil_Html::create('strong', $this->_('+'));
foreach ($items as $item) {
if ($item instanceof \Gems_Menu_SubMenuItem) {
$bridge->addItemLink($item->toActionLinkLower($this->request, $params, $title));
}
}
}
$bridge->getTable()->appendAttrib('class', 'compliance');
$tbody = $bridge->tbody();
$td = $tbody[0][0];
$td->appendAttrib(
'class',
\MUtil_Lazy::method($this->util->getTokenData(), 'getStatusClass', $bridge->getLazy('status'))
);
} | Adds columns from the model to the bridge that creates the browse table.
Overrule this function to add different columns to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
public function createModel($detailed, $action)
{
$model = new \MUtil_Model_FolderModel(
$this->getPath($detailed, $action),
$this->getMask($detailed, $action),
$this->recursive
);
if ($this->recursive) {
$model->set('relpath', 'label', $this->_('File (local)'),
'maxlength', 255,
'size', 40,
'validators', array('File_Path', 'File_IsRelativePath')
);
$model->set('filename', 'elementClass', 'Exhibitor');
}
if ($detailed || (! $this->recursive)) {
$model->set('filename', 'label', $this->_('Filename'), 'size', 30, 'maxlength', 255);
}
if ($detailed) {
$model->set('path', 'label', $this->_('Path'), 'elementClass', 'Exhibitor');
$model->set('fullpath', 'label', $this->_('Full name'), 'elementClass', 'Exhibitor');
$model->set('extension', 'label', $this->_('Type'), 'elementClass', 'Exhibitor');
$model->set('content', 'label', $this->_('Content'),
'formatFunction', array(\MUtil_Html::create(), 'pre'),
'elementClass', 'TextArea');
}
$model->set('size', 'label', $this->_('Size'),
'formatFunction', array('MUtil_File', 'getByteSized'),
'elementClass', 'Exhibitor');
$model->set('changed', 'label', $this->_('Changed on'),
'dateFormat', $this->util->getTranslated()->dateTimeFormatString,
'elementClass', 'Exhibitor');
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 deleteAction()
{
$request = $this->getRequest();
$model = $this->getModel();
$model->applyRequest($request);
if ($model->getFilter()) {
$model->delete();
} else {
$this->addMessage($this->_('Empty delete request not allowed'));
}
$this->_reroute(array($request->getActionKey() => 'index', MUTil_Model::REQUEST_ID => null));
} | Confirm has been moved to javascript | entailment |
public function getOnEmptyText()
{
static $warned;
$dir = $this->getPath(false, 'index');
if (! is_dir($dir)) {
try {
\MUtil_File::ensureDir($dir);
} catch (\Zend_Exception $e) {
$text = $e->getMessage();
if (! $warned) {
$warned = true;
$this->addMessage($text);
}
return $text;
}
}
return parent::getOnEmptyText();
} | Returns the on empty texts for the autofilter snippets
@static boolean $warned Listen very closely. I shall tell this only once!
@return string | entailment |
public function importAction()
{
$id = $this->_getIdParam();
$model = $this->getModel();
$data = $model->loadFirst(array('urlpath' => $id));
if (! ($data && isset($data['fullpath']))) {
$this->addMessage(sprintf($this->_('File "%s" not found on the server.'), $id));
return;
}
$importLoader = $this->loader->getImportLoader();
$importer = $importLoader->getFileImporter($data['fullpath']);
if (! $importer) {
$this->addMessage(sprintf($this->_('Automatic import not possible for file "%s".'), $data['relpath']));
return;
}
$batch = $importer->getCheckAndImportBatch();
$title = $this->_('Import the file.');
$this->_helper->batchRunner($batch, $title, $this->accesslog);
$this->html->pInfo($this->_('Checks this file for validity and then performs an import.'));
// \MUtil_Echo::track($data);
} | Import the file | entailment |
public function processTokenData(\Gems_Tracker_Token $token)
{
if (! $token->getReceptionCode()->isSuccess()) {
return;
}
$answers = $token->getRawAnswers();
if (isset($answers['informedconsent'])) {
$consent = $this->util->getConsent($answers['informedconsent']);
if ($consent->exists) {
// Is existing consent description as answer
$consentCode = $consent->getDescription();
} else {
if ($answers['informedconsent']) {
// Uses start of consent description as answer (LS has only 5 chars for an answer option)
$consentCode = $this->db->fetchOne(
"SELECT gco_description FROM gems__consents WHERE gco_description LIKE ? ORDER BY gco_order",
$answers['informedconsent'] . '%'
);
} else {
$consentCode = false;
}
if (! $consentCode) {
if ($answers['informedconsent']) {
// Code not found, use first positive consent
$consentCode = $this->db->fetchOne(
"SELECT gco_description FROM gems__consents WHERE gco_code != ? ORDER BY gco_order",
$this->util->getConsentRejected()
);
} else {
// Code not found, use first negative consent
$consentCode = $this->db->fetchOne(
"SELECT gco_description FROM gems__consents WHERE gco_code = ? ORDER BY gco_order",
$this->util->getConsentRejected()
);
}
}
}
$respondent = $token->getRespondent();
$values = array(
'gr2o_patient_nr' => $respondent->getPatientNumber(),
'gr2o_id_organization' => $respondent->getOrganizationId(),
'gr2o_consent' => $consentCode,
);
$model = $respondent->getRespondentModel();
$model->save($values);
if ($model->getChanged()) {
// Refresh the token so it has the new consent code
$token->refresh();
// Make sure the NEW consent is applied to this survey itself
$survey = $token->getSurvey();
$survey->copyTokenToSource($token, '');
}
}
return false;
} | Process the data and return the answers that should be changed.
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 |
public function filter($value)
{
// perform some transformation upon $value to arrive on $valueFiltered
$valueFiltered = strtoupper(trim($value));
if (strlen($valueFiltered) == 6) {
if (preg_match('/\d{4,4}[A-Z]{2,2}/', $valueFiltered)) {
$valueFiltered = substr_replace($valueFiltered, ' ', 4, 0);
}
}
return $valueFiltered;
} | Returns the result of filtering $value
@param mixed $value
@throws \Zend_Filter_Exception If filtering $value is impossible
@return mixed | entailment |
public function getFormElements(&$form, &$data)
{
$element = $form->createElement('multiCheckbox', 'format');
$element->setLabel($this->_('Excel options'))
->setMultiOptions(array(
'formatVariable'=> $this->_('Export labels instead of field names'),
'formatAnswer' => $this->_('Format answers'),
'formatDate' => $this->_('Format dates as Excel numbers easily convertable to date')
))
->setBelongsTo($this->getName())
->setSeparator('');
$elements['format'] = $element;
return $elements;
} | form elements for extra options for this particular export option
@param \MUtil_Form $form Current form to add the form elements
@param array $data current options set in the form
@return array Form elements | entailment |
protected function addheader($filename)
{
$tempFilename = str_replace($this->fileExtension, '', $filename);
$headerFilename = $tempFilename . '_header' . $this->fileExtension;
$exportName = $this->getName();
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($headerFilename);
$header = $this->getColumnHeaders();
if (isset($this->data[$exportName]) &&
isset($this->data[$exportName]['format']) &&
in_array('formatVariable', (array) $this->data[$exportName]['format'])) {
$writer->addRow($header);
} else {
$writer->addRow(array_keys($header));
}
$writer->close();
} | Add headers to a specific file
@param string $filename The temporary filename while the file is being written | entailment |
public function addRows($data, $modelId, $tempFilename, $filter)
{
$this->data = $data;
$this->modelId = $modelId;
$this->model = $this->getModel();
if ($this->model) {
$this->model->setFilter($filter + $this->model->getFilter());
if ($this->batch) {
$rowNumber = $this->batch->getSessionVariable('rowNumber');
$iteration = $this->batch->getSessionVariable('iteration');
} else {
$this->_session = new \Zend_Session_Namespace(__CLASS__);
$rowNumber = $this->_session->rowNumber;
$iteration = $this->_session->iteration;
}
// Reset internal rownumber when we move to a new file
if ($filter = $this->model->getFilter()) {
if (array_key_exists('limit', $filter)) {
if ($filter['limit'][1] == 0) {
$rowNumber = 2;
}
}
}
if (empty($rowNumber)) {
$rowNumber = 2;
}
if (empty($iteration)) {
$iteration = 0;
}
$filename = $tempFilename . '_' . $iteration . $this->fileExtension;
$rows = $this->model->load();
$exportName = $this->getName();
if (isset($this->data[$exportName]) &&
isset($this->data[$exportName]['format']) &&
in_array('formatAnswer', (array) $this->data[$exportName]['format'])) {
// We want answer labels instead of codes
} else {
// Skip formatting
$this->modelFilterAttributes = array('formatFunction', 'dateFormat', 'storageFormat', 'itemDisplay');
}
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($filename);
foreach($rows as $row) {
$this->addRowWithCount($row, $writer, $rowNumber);
$rowNumber++;
}
$writer->close();
}
if ($this->batch) {
$this->batch->setSessionVariable('rowNumber', $rowNumber);
$this->batch->setSessionVariable('iteration', $iteration+1);
} else {
$this->_session->rowNumber = $rowNumber;
$this->_session->iteration = $iteration++;
}
} | Add model rows to file. Can be batched
@param array $data Data submitted by export form
@param array $modelId Model Id when multiple models are passed
@param string $tempFilename The temporary filename while the file is being written
@param array $filter Filter (limit) to use | entailment |
public function addRowWithCount($row, $writer, $rowNumber)
{
$exportRow = $this->filterRow($row);
$labeledCols = $this->getLabeledColumns();
$exportRow = array_replace(array_flip($labeledCols), $exportRow);
$writer->addRow($exportRow);
} | Add a separate row to a file
@param array $row a row in the model
@param file $file The already opened file | entailment |
public function addFooter($filename, $modelId = null)
{
parent::addFooter($filename, $modelId);
$this->model = $this->getModel();
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($filename);
$tempFilename = str_replace($this->fileExtension, '', $filename);
$headerFilename = $tempFilename . '_header' . $this->fileExtension;
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($headerFilename);
$rowStyle = (new StyleBuilder())
->setFontBold()
->build();
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $row) {
$writer->addRowWithStyle($row, $rowStyle);
}
}
$reader->close();
unlink($headerFilename);
if ($this->batch) {
$iteration = $this->batch->getSessionVariable('iteration');
} else {
$this->_session = new \Zend_Session_Namespace(__CLASS__);
$iteration = $this->_session->iteration;
}
for($i=0;$i<$iteration;$i++) {
$partFilename = $tempFilename . '_' . $i . $this->fileExtension;
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($partFilename);
$reader->setShouldFormatDates(true);
foreach($reader->getSheetIterator() as $sheetIndex=>$sheet) {
if ($sheetIndex !== 1) {
$writer->addNewSheetAndMakeItCurrent();
}
foreach($sheet->getRowIterator() as $row) {
$writer->addRow($row);
}
}
$reader->close();
unlink($partFilename);
}
$writer->close();
// reset row number and iteration
if ($this->batch) {
$this->batch->setSessionVariable('rowNumber', 0);
$this->batch->setSessionVariable('iteration', 0);
} else {
$this->_session->rowNumber = 0;
$this->_session->iteration = 0;
}
} | Add a footer to a specific file
@param string $filename The temporary filename while the file is being written | entailment |
public function createExcelDate(\DateTime $date)
{
$day = clone $date;
$endDate = $day->setTime(0, 0, 0);
$startDate = new \DateTime('1970-01-01 00:00:00');
$diff = $endDate->diff($startDate)->format('%a');
if ($endDate < $startDate) {
$daysBetween = 25569 - $diff;
} else {
$daysBetween = 25569 + $diff;
}
$seconds = $date->getTimestamp() - $endDate->getTimestamp();
return (float)$daysBetween + ($seconds / 86400);
} | Create Excel date stamp from DateTime
@param \DateTime $date
@return float number of days since 1900-01-00 | entailment |
protected function preprocessModel()
{
parent::preprocessModel();
$labeledCols = $this->getLabeledColumns();
foreach($labeledCols as $columnName) {
$options = array();
$type = $this->model->get($columnName, 'type');
switch ($type) {
case \MUtil_Model::TYPE_DATE:
$options['dateFormat'] = 'yyyy-MM-dd';
break;
case \MUtil_Model::TYPE_DATETIME:
$options['dateFormat'] = 'yyyy-MM-dd HH:mm:ss';
break;
case \MUtil_Model::TYPE_TIME:
$options['dateFormat'] = 'HH:mm:ss';
break;
case \MUtil_Model::TYPE_NUMERIC:
break;
//When no type set... assume string
/*case \MUtil_Model::TYPE_STRING:
default:
$type = \MUtil_Model::TYPE_STRING;
$options['formatFunction'] = 'formatString';
break;*/
}
$options['type'] = $type;
$this->model->set($columnName, $options);
}
} | Preprocess the model to add specific options | entailment |
public function getSqlAppointmentsWhere()
{
if ($this->_locations && ($this->_locations !== true)) {
$where = 'gap_id_location IN (' . implode(', ', $this->_locations) . ')';
} 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->_locations) {
if (isset($this->_locations[$appointment->getLocationId()])) {
return true;
}
}
return false;
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
{
if ($this->request) {
$this->processSortOnly($model);
$model->setFilter(array('gto_id_token' => $this->token->getTokenId()));
}
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
public function createModel($detailed, $action)
{
$filter = $this->getSearchFilter($action !== 'export');
// Return empty model when no track sel;ected
if (! (isset($filter['gtf_id_track']) && $filter['gtf_id_track'])) {
$model = new \Gems_Model_JoinModel('trackfields' , 'gems__track_fields');
$model->set('gtf_field_name', 'label', $this->_('Name'));
$model->setFilter(array('1=0'));
$this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
return $model;
}
$this->trackId = $filter['gtf_id_track'];
$tracker = $this->loader->getTracker();
$this->engine = $tracker->getTrackEngine($this->trackId);
$orgs = $this->currentUser->getRespondentOrgFilter();
if (isset($filter['gr2t_id_organization'])) {
$orgs = array_intersect($orgs, (array) $filter['gr2t_id_organization']);
}
$this->orgWhere = " AND gr2t_id_organization IN (" . implode(", ", $orgs) . ")";
$sql = "SELECT COUNT(*)
FROM gems__respondent2track INNER JOIN gems__reception_codes ON gr2t_reception_code = grc_id_reception_code
WHERE gr2t_id_track = ? AND grc_success = 1" . $this->orgWhere;
// Add the period filter - if any
if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
$sql .= ' AND ' . $where;
}
$this->dateWhere = $where;
$this->trackCount = $this->db->fetchOne($sql, $this->trackId);
$model = $this->engine->getFieldsMaintenanceModel();
//$model->setFilter($filter);
// $model->addColumn(new \Zend_Db_Expr($trackCount), 'trackcount');
// $model->addColumn(new \Zend_Db_Expr("(SELECT COUNT())"), 'fillcount');
$model->set('trackcount', 'label', $this->_('Tracks'));
$model->setOnLoad('trackcount', $this->trackCount);
$model->set('fillcount', 'label', $this->_('Filled'));
$model->setOnLoad('fillcount', array($this, 'fillCount'));
$model->set('emptycount', 'label', $this->_('Empty'));
$model->setOnLoad('emptycount', array($this, 'emptyCount'));
$model->set('valuecount', 'label', $this->_('Unique values'));
$model->setOnLoad('valuecount', array($this, 'valueCount'));
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 emptyCount($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
$value = $this->trackCount - $this->trackFilled;
return sprintf(
$this->_('%d (%d%%)'),
$value,
$this->trackCount ? round($value / $this->trackCount * 100, 0) : 0
);
} | A ModelAbstract->setOnLoad() function that takes care of transforming a
dateformat read from the database to a \Zend_Date format
If empty or \Zend_Db_Expression (after save) it will return just the value
currently there are no checks for a valid date format.
@see \MUtil_Model_ModelAbstract
@param mixed $value The value being saved
@param boolean $isNew True when a new item is being saved
@param string $name The name of the current field
@param array $context Optional, the other values being saved
@param boolean $isPost True when passing on post data
@return \MUtil_Date|\Zend_Db_Expr|string | entailment |
public function fillCount($value, $isNew = false, $name = null, array $context = array(), $isPost = false)
{
$model = $this->engine->getFieldsDataStorageModel();
if (! $model instanceof FieldDataModel) {
return null;
}
$subName = $model->getModelNameForRow($context);
$sql = sprintf("SELECT COUNT(*)
FROM %s INNER JOIN gems__respondent2track ON %s = gr2t_id_respondent_track
INNER JOIN gems__reception_codes ON gr2t_reception_code = grc_id_reception_code
WHERE %s = %s AND %s IS NOT NULL AND gr2t_id_track = %d AND grc_success = 1" . $this->orgWhere,
$model->getTableName($subName),
$model->getFieldName('gr2t2f_id_respondent_track', $subName),
$model->getFieldName('gr2t2f_id_field', $subName),
$context['gtf_id_field'],
$model->getFieldName('gr2t2f_value', $subName),
$this->trackId
);
// Add the period filter - if any
if ($this->dateWhere) {
$sql .= ' AND ' . $this->dateWhere;
}
// \MUtil_Echo::track($sql);
$this->trackFilled = $this->db->fetchOne($sql);
$value = $this->trackFilled;
return sprintf(
$this->_('%d (%d%%)'),
$value,
$this->trackCount ? round($value / $this->trackCount * 100, 0) : 0
);
} | A ModelAbstract->setOnLoad() function that takes care of transforming a
dateformat read from the database to a \Zend_Date format
If empty or \Zend_Db_Expression (after save) it will return just the value
currently there are no checks for a valid date format.
@see \MUtil_Model_ModelAbstract
@param mixed $value The value being saved
@param boolean $isNew True when a new item is being saved
@param string $name The name of the current field
@param array $context Optional, the other values being saved
@param boolean $isPost True when passing on post data
@return \MUtil_Date|\Zend_Db_Expr|string | entailment |
public function getSearchDefaults()
{
if (! isset($this->defaultSearchData['gr2t_id_organization'])) {
$orgs = $this->currentUser->getRespondentOrganizations();
$this->defaultSearchData['gr2t_id_organization'] = array_keys($orgs);
}
if (!isset($this->defaultSearchData['gtf_id_track'])) {
$orgs = $this->currentUser->getRespondentOrganizations();
$tracks = $this->util->getTrackData()->getTracksForOrgs($orgs);
if (count($tracks) == 1) {
$this->defaultSearchData['gtf_id_track'] = key($tracks);
}
}
return parent::getSearchDefaults();
} | Function to allow the creation of search defaults in code
@see getSearchFilter()
@return array | entailment |
public function copyAction()
{
$trackId = $this->_getIdParam();
$engine = $this->getTrackEngine();
$newTrackId = $engine->copyTrack($trackId);
$this->_reroute(array('action' => 'edit', \MUtil_Model::REQUEST_ID => $newTrackId));
} | Action for making a copy of a track | entailment |
public function checkAllAction()
{
$batch = $this->loader->getTracker()->checkTrackRounds('trackCheckRoundsAll', $this->currentUser->getUserId());
$this->_helper->BatchRunner($batch, $this->_('Checking round assignments for all tracks.'), $this->accesslog);
$this->addSnippet('Track\\CheckRoundsInformation');
} | Action for checking all assigned rounds using a batch | entailment |
public function checkTrackAction()
{
$id = $this->_getIdParam();
$track = $this->getTrackEngine();
$where = $this->db->quoteInto('gr2t_id_track = ?', $id);
$batch = $this->loader->getTracker()->checkTrackRounds(
'trackCheckRounds' . $id,
$this->currentUser->getUserId(),
$where
);
$title = sprintf($this->_("Checking round assignments for track %d '%s'."), $id, $track->getTrackName());
$this->_helper->BatchRunner($batch, $title, $this->accesslog);
$this->addSnippet('Track\\CheckRoundsInformation');
} | Action for checking all assigned rounds for a single track using a batch | entailment |
public function createModel($detailed, $action)
{
$tracker = $this->loader->getTracker();
$model = $tracker->getTrackModel();
$model->applyFormatting($detailed);
$model->addFilter(array("gtr_track_class != 'SingleSurveyEngine'"));
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 \Gems_Model_TrackModel | entailment |
public function exportAction()
{
if ($this->exportSnippets) {
$params = $this->_processParameters($this->exportParameters);
$this->addSnippets($this->exportSnippets, $params);
}
} | Generic model based export action | entailment |
public function getSearchFilter($useRequest = true)
{
$filter = parent::getSearchFilter($useRequest);
if (isset($filter['org']) && strlen($filter['org'])) {
$filter[] = 'gtr_organizations LIKE "%|' . $filter['org'] . '|%"';
unset($filter['org']);
}
return $filter;
} | Get the filter to use with the model for searching including model sorts, etc..
@param boolean $useRequest Use the request as source (when false, the session is used)
@return array or false | entailment |
public function recalcAllFieldsAction()
{
$batch = $this->loader->getTracker()->recalcTrackFields(
'trackRecalcAllFields'
);
$this->_helper->BatchRunner($batch, $this->_('Recalculating fields for all tracks.'), $this->accesslog);
$this->addSnippet('Track\\RecalcFieldsInformation');
} | Action for checking all assigned rounds using a batch | entailment |
public function recalcFieldsAction()
{
$id = $this->_getIdParam();
$track = $this->getTrackEngine();
$where = $this->db->quoteInto('gr2t_id_track = ?', $id);
$batch = $this->loader->getTracker()->recalcTrackFields(
'trackRecalcFields' . $id,
$where
);
$title = sprintf($this->_("Recalculating fields for track %d '%s'."), $id, $track->getTrackName(), $this->accesslog);
$this->_helper->BatchRunner($batch, $title, $this->accesslog);
$this->addSnippet('Track\\RecalcFieldsInformation');
} | Action for checking all assigned rounds for a single track using a batch | entailment |
public function showAction()
{
$showSnippets = $this->showSnippets;
$first = array_shift($showSnippets);
$next = $showSnippets;
$this->showSnippets = $first;
parent::showAction();
$this->showParameters['tagName'] = 'h3';
$this->showSnippets = $next;
parent::showAction();
$this->showSnippets = array_unshift($next, $first);
} | Pass the h3 tag to all snippets except the first one | entailment |
public function getCronBatch($id = 'cron')
{
$batch = $this->loader->getTaskRunnerBatch($id);
$batch->setMessageLogFile($this->project->getCronLogfile());
$batch->minimalStepDurationMs = 3000; // 3 seconds max before sending feedback
if (! $batch->isLoaded()) {
$this->loadCronBatch($batch);
}
return $batch;
} | Perform automatic job mail | entailment |
public function getMailer($target = null, $id = false, $orgId = false)
{
if(isset($this->mailTargets[$target])) {
$target = ucfirst($target);
return $this->_loadClass($target.'Mailer', true, array($id, $orgId));
} else {
return false;
}
} | Get the correct mailer class from the given target
@param [type] $target mailtarget (lowercase)
@param array $identifiers the identifiers needed for the specific mailtargets
@return \Gems_Mail_MailerAbstract class | entailment |
protected function loadCronBatch(\Gems_Task_TaskRunnerBatch $batch)
{
$batch->addMessage(sprintf($this->_("Starting %s mail jobs"), $this->project->getName()));
$batch->addTask('Mail\\AddAllMailJobsTask');
// Check for unprocessed tokens,
$tracker = $this->loader->getTracker();
$tracker->loadCompletedTokensBatch($batch, null, $this->currentUser->getUserId());
} | Perform the actions and load the tasks needed to start the cron batch
@param \Gems_Task_TaskRunnerBatch $batch | entailment |
protected function _load(array $filter, array $sort)
{
$result = array();
foreach ($this->getItemsOrdered() as $item) {
$result[0][$item] = $item;
}
return $result;
} | Returns a nested array containing the items requested.
@param array $filter Filter array, num keys contain fixed expresions, text keys are equal or one of filters
@param array $sort Sort array field name => sort type
@return array Nested array or false | entailment |
protected function inlineIssueLink($excerpt)
{
if (preg_match('/([\p{L}\p{N}_-]*)\/?([\p{L}\p{N}_-]*)#(\d+)/ui', $excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) {
if (!empty($matches[1][0])) {
$project = $matches[1][0] . '/' . $matches[2][0];
} else {
$project = $this->projectName;
}
$url = sprintf('%s/%s/issues/%s', $this->GitHub, $project, $matches[3][0]);
$inline = array(
'extent' => strlen($matches[0][0]),
'position' => $matches[0][1],
'element' => array(
'name' => 'a',
'text' => '#' . $matches[3][0],
'attributes' => array(
'href' => $url,
),
),
);
return $inline;
}
} | Find links to issue on github
organization/repository#<issue> or #<issue>
@param array $excerpt
@return array | entailment |
public function isValid($value, $context = array())
{
$user = $this->_userSource->getUser();
if ($user instanceof \Gems_User_User) {
$result = $user->authenticate($value);
} else {
$result = new Result(Result::FAILURE_UNCATEGORIZED, null);
}
return $this->setAuthResult($result);
} | 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 findRespondentTrackFor(array $row)
{
if (! (isset($row[$this->patientNrField], $row[$this->orgIdField]) &&
$row[$this->patientNrField] &&
$row[$this->orgIdField])) {
return null;
}
$trackId = $this->getTrackId();
if (! $trackId) {
return null;
}
$select = $this->db->select();
$select->from('gems__respondent2track', array('gr2t_id_respondent_track'))
->joinInner(
'gems__respondent2org',
'gr2t_id_user = gr2o_id_user AND gr2t_id_organization = gr2o_id_organization',
array()
)
->where('gr2o_patient_nr = ?', $row[$this->patientNrField])
->where('gr2o_id_organization = ?', $row[$this->orgIdField])
->where('gr2t_id_track = ?');
$select->order(new \Zend_Db_Expr("CASE
WHEN gr2t_start_date IS NOT NULL AND gr2t_end_date IS NULL THEN 1
WHEN gr2t_start_date IS NOT NULL AND gr2t_end_date IS NOT NULL THEN 2
ELSE 3 END ASC"))
->order('gr2t_start_date DESC')
->order('gr2t_end_date DESC')
->order('gr2t_created');
$respTrack = $this->db->fetchOne($select);
if ($respTrack) {
return $respTrack;
}
return null;
} | If the token can be created find the respondent track for the token
@param array $row
@return int|null | entailment |
protected function findTokenFor(array $row)
{
if (! (isset($row[$this->patientNrField], $row[$this->orgIdField]) &&
$row[$this->patientNrField] &&
$row[$this->orgIdField] &&
$this->getSurveyId())) {
return null;
}
$select = $this->db->select();
$select->from('gems__tokens', array('gto_id_token'))
->joinInner(
'gems__respondent2org',
'gto_id_respondent = gr2o_id_user AND gto_id_organization = gr2o_id_organization',
array()
)
->where('gr2o_patient_nr = ?', $row[$this->patientNrField])
->where('gr2o_id_organization = ?', $row[$this->orgIdField])
->where('gto_id_survey = ?', $this->getSurveyId());
$trackId = $this->getTrackId();
if ($trackId) {
$select->where('gto_id_track = ?', $trackId);
}
$select->order(new \Zend_Db_Expr("CASE
WHEN gto_completion_time IS NULL AND gto_valid_from IS NOT NULL THEN 1
WHEN gto_completion_time IS NULL AND gto_valid_from IS NULL THEN 2
ELSE 3 END ASC"))
->order('gto_completion_time DESC')
->order('gto_valid_from ASC')
->order('gto_round_order');
$token = $this->db->fetchOne($select);
if ($token) {
return $token;
}
return null;
} | Find the token id using the passed row data and
the other translator parameters.
@param array $row
@return string|null | entailment |
public function getRespondentAnswerTranslations()
{
$this->_targetModel->set($this->patientNrField, 'label', $this->_('Patient ID'),
'order', 5,
'required', true,
'type', \MUtil_Model::TYPE_STRING
);
$this->_targetModel->set($this->orgIdField, 'label', $this->_('Organization ID'),
'multiOptions', $this->util->getDbLookup()->getOrganizationsWithRespondents(),
'order', 6,
'required', true,
'type', \MUtil_Model::TYPE_STRING
);
return array(
$this->patientNrField => $this->patientNrField,
$this->orgIdField => $this->orgIdField,
);
} | Get information on the field translations
@return array of fields sourceName => targetName
@throws \MUtil_Model_ModelException | entailment |
public function getFieldsTranslations()
{
if (! $this->_targetModel instanceof \MUtil_Model_ModelAbstract) {
throw new \MUtil_Model_ModelTranslateException(sprintf('Called %s without a set target model.', __FUNCTION__));
}
// \MUtil_Echo::track($this->_targetModel->getItemNames());
return $this->getRespondentAnswerTranslations() + parent::getFieldsTranslations();
} | Get information on the field translations
@return array of fields sourceName => targetName
@throws \MUtil_Model_ModelException | entailment |
public function getNoTokenError(array $row, $key)
{
$messages = array();
if (! (isset($row[$this->patientNrField]) && $row[$this->patientNrField])) {
$messages[] = sprintf($this->_('Missing respondent number in %s field.'), $this->patientNrField);
}
if (! (isset($row[$this->orgIdField]) && $row[$this->orgIdField])) {
$messages[] = sprintf($this->_('Missing organization number in %s field.'), $this->orgIdField);
}
if (! $this->getSurveyId()) {
$messages[] = $this->_('Missing survey definition.');
}
if ($messages) {
return implode(' ', $messages);
}
if (! $this->_skipUnknownPatients) {
$respondent = $this->loader->getRespondent($row[$this->patientNrField], $row[$this->orgIdField]);
$organization = $respondent->getOrganization();
if (! $organization->exists()) {
return sprintf(
$this->_('Organization %s (specified for respondent %s) does not exist.'),
$respondent->getOrganizationId(),
$respondent->getPatientNumber()
);
}
if (! $respondent->exists) {
return sprintf(
$this->_('Respondent %s does not exist in organization %s.'),
$respondent->getPatientNumber(),
$organization->getName()
);
}
$tracker = $this->loader->getTracker();
$trackId = $this->getTrackId();
if ($trackId) {
$trackEngine = $tracker->getTrackEngine($trackId);
if (! $trackEngine->getTrackName()) {
return sprintf($this->_('Track id %d does not exist'), $trackId);
}
$select = $this->db->select();
$select->from('gems__respondent2track')
->joinInner(
'gems__reception_codes',
'gr2t_reception_code = grc_id_reception_code',
array()
)
->where('gr2t_id_user = ?', $respondent->getId())
->where('gr2t_id_organization = ?', $respondent->getOrganizationId())
->where('grc_success = 1');
if (! $this->db->fetchOne($select)) {
return sprintf(
$this->_('Respondent %s does not have a valid %s track.'),
$respondent->getPatientNumber(),
$trackEngine->getTrackName()
);
}
}
$survey = $tracker->getSurvey($this->getSurveyId());
$tokenSelect = $tracker->getTokenSelect();
$tokenSelect->andReceptionCodes()
->forRespondent($respondent->getId(), $respondent->getOrganizationId())
->forSurveyId($this->getSurveyId());
if ($tokenSelect->fetchOne()) {
$tokenSelect->onlySucces();
if (! $tokenSelect->fetchOne()) {
return sprintf(
$this->_('Respondent %s has only deleted %s surveys.'),
$respondent->getPatientNumber(),
$survey->getName()
);
}
} else {
return sprintf(
$this->_('Respondent %s has no %s surveys.'),
$respondent->getPatientNumber(),
$survey->getName()
);
}
}
return parent::getNoTokenError($row, $key);
} | Get the error message for when no token exists
@return string | entailment |
public function processTokenInsertion(\Gems_Tracker_Token $token)
{
$this->token = $token;
if ($token->getReceptionCode()->isSuccess() && (!$token->isCompleted())) {
// Read questioncodes
$questions = $token->getSurvey()->getQuestionList(null);
$fields = [];
$results = [];
// Check if they match a prefix schema
foreach ($questions as $code => $text) {
$upperField = strtoupper($code);
$prefix = substr($upperField, 0, $this->prefixLength);
if (array_key_exists($prefix, $this->prefixes)) {
$fields[$prefix][$code] = substr($upperField, $this->prefixLength);
}
}
if (count($fields) > 0) {
foreach ($fields as $prefix => $requests) {
// Find which method to call
$method = $this->prefixes[$prefix];
$results = $results + $this->$method($requests);
}
}
return $results;
}
} | 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 |
public function getCopyFields($requests)
{
$prefix = 'CP';
$token = $this->token;
$surveyCode = $token->getSurvey()->getCode();
$surveyId = $token->getSurveyId();
$flipRequests = array_flip($requests);
// Check from the last token back, we need to find the last answered token.
// To be improved with a custom token loader that selects tokens answered before this one to prevent looping the complete track.
$prev = $token->getRespondentTrack()->getLastToken();
do {
if ($prev->getReceptionCode()->isSuccess() && $prev->isCompleted()) {
// Check first on survey id and when that does not work by code (if not empty).
if ($prev->getSurveyId() === $surveyId || (!empty($surveyCode) && $prev->getSurvey()->getCode() === $surveyCode)) {
// @@TODO: Make case insensitive from here on, also change $check array to $requests
$answers = $prev->getRawAnswers();
$answersUc = array_change_key_case($answers, CASE_UPPER);
$values = array_intersect_key($answersUc, $flipRequests);
// Values now has the CP prefix requested answers that have a no-prefix match
// If this is not the complete set, we look for CP prefix matches to allow copy from start
if (count($values) !== count($requests)) {
$missing = array_diff_key($flipRequests, $values);
foreach ($missing as $key => $value) {
$prefixKey = $prefix . $key;
if (array_key_exists($prefixKey, $answersUc)) {
$values[$key] = $answersUc[$prefixKey];
}
}
}
$results = [];
foreach ($values as $key => $value) {
$newKey = $flipRequests[$key];
$results[$newKey] = $value;
}
return $results;
}
}
} while ($prev = $prev->getPreviousToken());
return [];
} | Tries to fulfill request to copy fields
Copy fields will be fulfilled by searching the track in reverse
- first to see if there is a field without the CP prefix
- then if there are fields with the CP prefix
And only return the match when (in the end) ALL fields are found. If not
it will start again for the next answered token to the same survey, or
survey with the same code as the requesting token.
@param array $requests
@return array | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.