sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
// \MUtil_Model::$verbose = true;
//
// Initiate data retrieval for stuff needed by links
$bridge->gr2o_patient_nr;
$bridge->gr2o_id_organization;
$bridge->gr2t_id_respondent_track;
$HTML = \MUtil_Html::create();
$model->set('gto_round_description', 'tableDisplay', 'smallData');
$model->set('gr2t_track_info', 'tableDisplay', 'smallData');
$roundIcon[] = \MUtil_Lazy::iif($bridge->gto_icon_file, \MUtil_Html::create('img', array('src' => $bridge->gto_icon_file, 'class' => 'icon')),
\MUtil_Lazy::iif($bridge->gro_icon_file, \MUtil_Html::create('img', array('src' => $bridge->gro_icon_file, 'class' => 'icon'))));
$bridge->td($this->util->getTokenData()->getTokenStatusLinkForBridge($bridge, false));
if ($menuItem = $this->findMenuItem('track', 'show-track')) {
$href = $menuItem->toHRefAttribute($this->request, $bridge);
$track1 = $HTML->if($bridge->gtr_track_name, $HTML->a($href, $bridge->gtr_track_name));
} else {
$track1 = $bridge->gtr_track_name;
}
$track = array($track1, $bridge->createSortLink('gtr_track_name'));
$bridge->addMultiSort($track, 'gr2t_track_info');
$bridge->addMultiSort('gsu_survey_name', 'gto_round_description', $roundIcon);
$bridge->addSortable('ggp_name');
$bridge->addSortable('calc_used_date', null, $HTML->if($bridge->is_completed, 'disabled date', 'enabled date'));
$bridge->addSortable('gto_changed');
$bridge->addSortable('assigned_by', $this->_('Assigned by'));
$project = \GemsEscort::getInstance()->project;
// If we are allowed to see the result of the survey, show them
if ($this->currentUser->hasPrivilege('pr.respondent.result') &&
(! $this->currentUser->isFieldMaskedWhole('gto_result'))) {
$bridge->addSortable('gto_result', $this->_('Score'), 'date');
}
$bridge->useRowHref = false;
$this->addActionLinks($bridge);
$this->addTokenLinks($bridge);
} | 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 |
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
{
$filter['gto_id_respondent'] = $this->respondent->getId();
if (is_array($this->forOtherOrgs)) {
$filter['gto_id_organization'] = $this->forOtherOrgs;
} elseif (true !== $this->forOtherOrgs) {
$filter['gto_id_organization'] = $this->respondent->getOrganizationId();
}
// Filter for valid track reception codes
$filter[] = 'gr2t_reception_code IN (SELECT grc_id_reception_code FROM gems__reception_codes WHERE grc_success = 1)';
$filter['grc_success'] = 1;
// Active round
// or
// no round
// or
// token is success and completed
$filter[] = 'gro_active = 1 OR gro_active IS NULL OR (grc_success=1 AND gto_completion_time IS NOT NULL)';
$filter['gsu_active'] = 1;
// NOTE! $this->model does not need to be the token model, but $model is a token model
$tabFilter = $this->model->getMeta('tab_filter');
if ($tabFilter) {
$model->addFilter($tabFilter);
}
$model->addFilter($filter);
// \MUtil_Echo::track($model->getFilter());
$this->processSortOnly($model);
} | Overrule to implement snippet specific filtering and sorting.
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addModelSettings(array &$settings)
{
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
$settings['elementClass'] = 'Select';
$settings['multiOptions'] = $empty + $this->util->getDbLookup()->getUserConsents();
} | Add the model settings like the elementClass for this field.
elementClass is overwritten when this field is read only, unless you override it again in getDataModelSettings()
@param array $settings The settings set so far | entailment |
public function execute()
{
$model = new \Gems_Model_TemplateModel('templates', $this->project);
$templates = $model->load();
foreach ($templates as $name => $data) {
// Now load individual template
$data = $model->load(array('name'=> $name));
// And save
$model->save(reset($data));
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
protected function addHeader($filename)
{
$file = fopen($filename, 'w');
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
fwrite($file, $bom);
fclose($file);
} | Add headers to a specific file
@param string $filename The temporary filename while the file is being written | entailment |
public function addRow($row, $file)
{
$exportRow = $this->filterRow($row);
$labeledCols = $this->getLabeledColumns();
$exportRow = array_replace(array_flip($labeledCols), $exportRow);
$changed = false;
foreach ($exportRow as $name => $value) {
$type = $this->model->get($name, 'type');
// When numeric, there could be a non numeric answer, just ignore empty values
if ($type == \MUtil_Model::TYPE_NUMERIC && !empty($value) && !is_numeric($value)) {
$this->model->set($name, 'type', \MUtil_Model::TYPE_STRING);
$changed = true;
}
if ($type == \MUtil_Model::TYPE_STRING) {
$size = (int) $this->model->get($name, 'maxlength');
if (mb_strlen($value)>$size) {
$this->model->set($name, 'maxlength', mb_strlen($value));
$changed = true;
}
}
}
fputcsv($file, $exportRow, $this->delimiter, "'");
if ($changed) {
$modelData = [];
foreach ($exportRow as $name => $value) {
$modelData[$name] = [
'type' => $this->model->get($name, 'type'),
'maxlength' => $this->model->get($name, 'maxlength')
];
}
if ($this->batch) {
$models = $this->batch->getSessionVariable('modelsExtra');
$models[$this->modelId] = $modelData;
$this->batch->setSessionVariable('modelsExtra', $models);
} else {
$models = $this->_session->modelsExtra;
$models[$this->modelId] = $modelData;
$this->_session->modelsExtra = $models;
}
}
} | Add a separate row to a file
@param array $row a row in the model
@param file $file The already opened file | entailment |
protected function addSpssFile($filename)
{
$model = $this->model;
$files = $this->getFiles();
$datFileName = array_search($filename, $files);
$spsFileName = substr($datFileName, 0, -strlen($this->fileExtension)) . '.sps';
$tmpFileName = substr($filename, 0, -strlen($this->fileExtension)) . '.sps';
$this->files[$spsFileName] = $tmpFileName;
if ($this->batch) {
$this->batch->setSessionVariable('files', $this->files);
} else {
$this->_session->files = $this->files;
}
$this->addHeader($tmpFileName);
$file = fopen($tmpFileName, 'a');
//first output our script
fwrite($file,
"SET UNICODE=ON.\n" .
"SHOW LOCALE.\n" .
"PRESERVE LOCALE.\n" .
"SET LOCALE='en_UK'.\n\n" .
"GET DATA\n" .
" /TYPE=TXT\n" .
" /FILE=\"" . $datFileName . "\"\n" .
" /DELCASE=LINE\n" .
" /DELIMITERS=\"".$this->delimiter."\"\n" .
" /QUALIFIER=\"'\"\n" .
" /ARRANGEMENT=DELIMITED\n" .
" /FIRSTCASE=1\n" .
" /IMPORTCASE=ALL\n" .
" /VARIABLES=");
$labeledCols = $this->getLabeledColumns();
$labels = array();
$types = array();
$fixedNames = array();
//$questions = $survey->getQuestionList($language);
foreach ($labeledCols as $colname) {
$fixedNames[$colname] = $this->fixName($colname);
$options = array();
$type = $model->get($colname, 'type');
switch ($type) {
case \MUtil_Model::TYPE_DATE:
$type = 'SDATE10';
break;
case \MUtil_Model::TYPE_DATETIME:
$type = 'DATETIME23';
break;
case \MUtil_Model::TYPE_TIME:
$type = 'TIME8.0';
break;
case \MUtil_Model::TYPE_NUMERIC:
$defaultSize = $this->defaultNumericSize;
$type = 'F';
break;
//When no type set... assume string
case \MUtil_Model::TYPE_STRING:
default:
$defaultSize = $this->defaultAlphaSize;
$type = 'A';
break;
}
$types[$colname] = $type;
if ($type == 'A' || $type == 'F') {
$size = $model->get($colname, 'maxlength'); // This comes from db when available
if (is_null($size)) {
$size = $model->get($colname, 'size'); // This is the display width
if (is_null($size)) {
$size = $defaultSize; // We just don't know, make it the default
}
}
if ($type == 'A') {
$type = $type . $size;
} else {
$type = $type . $size . '.' . ($size - 1); //decimal
}
}
//if (isset($questions[$colname])) {
// $labels[$colname] = $questions[$colname];
//}
fwrite($file, "\n " . $fixedNames[$colname] . ' ' . $type);
}
fwrite($file, ".\nCACHE.\nEXECUTE.\n");
fwrite($file, "\n*Define variable labels.\n");
foreach ($labeledCols as $colname) {
$label = "'" . $this->formatString($model->get($colname, 'label')) . "'";
fwrite($file, "VARIABLE LABELS " . $fixedNames[$colname] . " " . $label . "." . "\n");
}
fwrite($file, "\n*Define value labels.\n");
foreach ($labeledCols as $colname) {
if ($options = $model->get($colname, 'multiOptions')) {
fwrite($file, 'VALUE LABELS ' . $fixedNames[$colname]);
foreach ($options as $option => $label) {
$label = "'" . $this->formatString($label) . "'";
if ($option !== "") {
if ($types[$colname] == 'F') {
//Numeric
fwrite($file, "\n" . $option . ' ' . $label);
} else {
//String
fwrite($file, "\n" . '"' . $option . '" ' . $label);
}
}
}
fwrite($file, ".\n\n");
}
}
fwrite($file, "RESTORE LOCALE.\n");
fclose($file);
} | Creates a correct SPSS file and adds it to the Files array | entailment |
public function fixName($input)
{
if (!preg_match("/^([a-z]|[A-Z])+.*$/", $input)) {
$input = "q_" . $input;
}
$input = str_replace(array(" ", "-", ":", ";", "!", "/", "\\", "'"), array("_", "_hyph_", "_dd_", "_dc_", "_excl_", "_fs_", "_bs_", '_qu_'), $input);
return $input;
} | Make sure the $input fieldname is correct for usage in SPSS
Should start with alphanum, and contain no spaces
@param string $input
@return string | entailment |
public function formatString($input)
{
if (is_array($input)) {
$input = join(', ', $input);
}
$output = strip_tags($input);
$output = str_replace(array("'", "\r", "\n"), array("''", ' ', ' '), $output);
//$output = "'" . $output . "'";
return $output;
} | Formatting of strings for SPSS export. Enclose in single quotes and escape single quotes
with a single quote
Example:
This isn't hard to understand
==>
'This isn''t hard to understand'
@param type $input
@return string | 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'] = 'dd-MM-yyyy 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);
}
// Load extra data
if ($this->batch) {
$models = $this->batch->getSessionVariable('modelsExtra');
} else {
$models = $this->_session->modelsExtra;
}
if (!is_array($models) || !isset($models[$this->modelId])) {
$models[$this->modelId] = [];
}
$modelData = $models[$this->modelId];
foreach($modelData as $name => $items)
{
$this->model->set($name, $items);
}
// Save extra data
if ($this->batch) {
$this->batch->setSessionVariable('modelsExtra', $models);
} else {
$this->_session->modelsExtra = $models;
}
} | Preprocess the model to add specific options | entailment |
public function isValid($value, $context = array())
{
$this->_setValue((string) $value);
$fieldSet = (boolean) isset($context[$this->_fieldName]) && $context[$this->_fieldName];
$valueSet = (boolean) $value;
if ($valueSet && (! $fieldSet)) {
return true;
}
if ((! $valueSet) && $fieldSet) {
return true;
}
$this->_error(self::NEITHER);
return false;
} | Defined by \Zend_Validate_Interface
Returns true if and only if a token has been set and the provided value
matches that token.
@param mixed $value
@return boolean | entailment |
protected function exportBatch($data)
{
$filter = $this->getSearchFilter();
if ($data) {
$batch = $this->loader->getTaskRunnerBatch('export_surveys');
$models = $this->getExportModels($data['gto_id_survey'], $filter, $data);
$batch->setVariable('model', $models);
if (!$batch->count()) {
$batch->minimalStepDurationMs = 2000;
$batch->finishUrl = $this->view->url(array('step' => 'download'));
$batch->setSessionVariable('files', array());
foreach ($data['gto_id_survey'] as $surveyId) {
$batch->addTask('Export_ExportCommand', $data['type'], 'addExport', $data, $surveyId);
}
$batch->addTask('addTask', 'Export_ExportCommand', $data['type'], 'finalizeFiles');
$export = $this->loader->getExport()->getExport($data['type']);
if ($snippet = $export->getHelpSnippet()) {
$this->addSnippet($snippet);
}
$batch->autoStart = true;
$this->accesslog->logChange($this->getRequest(), null, $data + $filter);
}
if ($batch->run($this->request)) {
exit;
} else {
$controller = $this;
if ($batch->isFinished()) {
} else {
if ($batch->count()) {
$controller->html->append($batch->getPanel($controller->view, $batch->getProgressPercentage() . '%'));
} else {
$controller->html->pInfo($controller->_('Nothing to do.'));
}
$controller->html->pInfo()->a(
\MUtil_Html_UrlArrayAttribute::rerouteUrl($this->getRequest(), array('action'=>'index', 'step' => false)),
array('class'=>'actionlink'),
$this->_('Back')
);
}
}
}
} | Performs the export step | entailment |
protected function exportDownload()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$batch = $this->loader->getTaskRunnerBatch('export_surveys');
$file = $batch->getSessionVariable('file');
foreach($file['headers'] as $header) {
header($header);
}
while (ob_get_level()) {
ob_end_clean();
}
readfile($file['file']);
// Now clean up the file
unlink($file['file']);
exit;
} | Performs the download step | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$bridge->addElement($this->createToElement());
$bridge->addElement($this->mailElements->createMethodElement());
parent::addFormElements($bridge,$model);
$bridge->addHidden('to');
} | Adds elements from the model to the bridge that creates the form.
Overrule this function to add different elements to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function getSingleTokenData()
{
$this->otherTokenData = $this->multipleTokenData;
$singleTokenData = array_shift($this->otherTokenData);
return $singleTokenData;
} | Get the default token Id, from an array of tokenids. Usually the first token. | entailment |
public function getTokenName(array $tokenData = null)
{
$data[] = $tokenData['grs_first_name'];
$data[] = $tokenData['grs_surname_prefix'];
$data[] = $tokenData['grs_last_name'];
$data = array_filter(array_map('trim', $data)); // Remove empties
return implode(' ', $data);
} | Returns the name of the user mentioned in this token
in human-readable format
@param array $tokenData
@return string | entailment |
public function afterRegistry()
{
parent::afterRegistry();
// Loaded from tracker and tracker does not always have the request as source value
if (! $this->request instanceof \Zend_Controller_Request_Abstract) {
$this->request = \Zend_Controller_Front::getInstance()->getRequest();
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function getChanges(array $context, $new)
{
$subChange = true;
if (! $new) {
$fieldName = reset($this->_dependentOn);
if (isset($context[$fieldName])) {
$sql = $this->getSql($context[$fieldName]);
$fid = $this->request->getParam(\Gems_Model::FIELD_ID);
if ($sql && $fid) {
$subChange = ! $this->db->fetchOne($sql, $fid);
}
}
}
if ($subChange) {
return array('gtf_field_type' => array(
'elementClass' => 'Select',
'onchange' => 'this.form.submit();',
));
}
} | 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 _getAppointmentSelect()
{
$select = $this->db->select();
$select->from('gems__appointments')
->joinLeft( 'gems__agenda_activities', 'gap_id_activity = gaa_id_activity')
->joinLeft('gems__agenda_procedures', 'gap_id_procedure = gapr_id_procedure')
->joinLeft('gems__locations', 'gap_id_location = glo_id_location')
->order('gap_admission_time DESC');
return $select;
} | Get the select statement for appointments in getAppointments()
Allows for overruling on project level
@return \Zend_Db_Select | entailment |
public function addActivity($name, $organizationId)
{
$model = new \MUtil_Model_TableModel('gems__agenda_activities');
\Gems_Model::setChangeFieldsByPrefix($model, 'gaa');
$values = array(
'gaa_name' => $name,
'gaa_id_organization' => $organizationId,
'gaa_match_to' => $name,
'gaa_active' => 1,
'gaa_filter' => 0,
);
$result = $model->save($values);
$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('activity', 'activities'));
return $result;
} | Add Activities to the table
Override this method for other defaults
@param string $name
@param int $organizationId
@return array | entailment |
public function createAgendaClass($className, $param1 = null, $param2 = null)
{
$params = func_get_args();
array_shift($params);
return $this->_loadClass($className, true, $params);
} | Dynamically load and create a [Gems|Project]_Agenda_ class
@param string $className
@param mixed $param1
@param mixed $param2
@return object | entailment |
public function getActiveAppointments($respondentId, $organizationId, $patientNr = null, $where = null)
{
if ($where) {
$where = "($where) AND ";
} else {
$where = "";
}
$where .= sprintf('gap_status IN (%s)', $this->getStatusKeysActiveDbQuoted());
return $this->getAppointments($respondentId, $organizationId, $patientNr, $where);
} | Get all active respondents for this user
@param int $respondentId When null $patientNr is required
@param int $organizationId
@param string $patientNr Optional for when $respondentId is null
@param string $where Optional extra where statement
@return array appointmentId => appointment description | entailment |
public function getAppointmentDisplay(array $row)
{
$date = new \MUtil_Date($row['gap_admission_time'], 'yyyy-MM-dd HH:mm:ss');
$results[] = $date->toString($this->appointmentDisplayFormat);
if ($row['gaa_name']) {
$results[] = $row['gaa_name'];
}
if ($row['gapr_name']) {
$results[] = $row['gapr_name'];
}
if ($row['glo_name']) {
$results[] = $row['glo_name'];
}
return implode($this->_('; '), $results);
} | Overrule this function to adapt the display of the agenda items for each project
@see \Gems_Agenda_Appointment->getDisplayString()
@param array $row Row containing result select
@return string | entailment |
public function getAppointment($appointmentData)
{
if (! $appointmentData) {
throw new \Gems_Exception_Coding('Provide at least the apppointment id when requesting an appointment.');
}
if (is_array($appointmentData)) {
if (!isset($appointmentData['gap_id_appointment'])) {
throw new \Gems_Exception_Coding(
'$appointmentData array should atleast have a key "gap_id_appointment" containing the requested appointment id'
);
}
$appointmentId = $appointmentData['gap_id_appointment'];
} else {
$appointmentId = $appointmentData;
}
// \MUtil_Echo::track($appointmentId, $appointmentData);
if (! isset($this->_appointments[$appointmentId])) {
$this->_appointments[$appointmentId] = $this->_loadClass('appointment', true, array($appointmentData));
} elseif (is_array($appointmentData)) {
// Make sure the new values are set in the object
$this->_appointments[$appointmentId]->refresh($appointmentData);
}
return $this->_appointments[$appointmentId];
} | Get an appointment object
@param mixed $appointmentData Appointment id or array containing appointment data
@return \Gems_Agenda_Appointment | entailment |
public function getAppointments($respondentId, $organizationId, $patientNr = null, $where = null)
{
$select = $this->_getAppointmentSelect();
if ($where) {
$select->where($where);
}
if ($respondentId) {
$select->where('gap_id_user = ?', $respondentId)
->where('gap_id_organization = ?', $organizationId);
} else {
// Join might have been created in _getAppointmentSelect
$from = $select->getPart(\Zend_Db_Select::FROM);
if (! isset($from['gems__respondent2org'])) {
$select->joinInner(
'gems__respondent2org',
'gap_id_user = gr2o_id_user AND gap_id_organization = gr2o_id_organization',
array()
);
}
$select->where('gr2o_patient_nr = ?', $patientNr)
->where('gr2o_id_organization = ?', $organizationId);
}
// \MUtil_Echo::track($select->__toString());
$rows = $this->db->fetchAll($select);
if (! $rows) {
return array();
}
$results = array();
foreach ($rows as $row) {
$results[$row['gap_id_appointment']] = $this->getAppointmentDisplay($row);
}
return $results;
} | Get all appointments for a respondent
@param int $respondentId When null $patientNr is required
@param int $organizationId
@param string $patientNr Optional for when $respondentId is null
@param string $where Optional extra where statement
@return array appointmentId => appointment description | entailment |
public function getAppointmentsForEpisode($episode)
{
$select = $this->_getAppointmentSelect();
if ($episode instanceof EpisodeOfCare) {
$episodeId = $episode->getId();
} else {
$episodeId = $episode;
}
$select->where('gap_id_episode = ?', $episodeId);
// \MUtil_Echo::track($select->__toString());
$rows = $this->db->fetchAll($select);
if (! $rows) {
return array();
}
$results = array();
foreach ($rows as $row) {
$results[$row['gap_id_appointment']] = $this->getAppointment($row);
}
return $results;
} | Get all appointments for an episode
@param int|Episode $episode Episode Id or object
@return array appointmentId => appointment object | entailment |
public function getEpisodeOfCare($episodeData)
{
if (! $episodeData) {
throw new \Gems_Exception_Coding('Provide at least the episode id when requesting an episode of care.');
}
if (is_array($episodeData)) {
if (!isset($episodeData['gec_episode_of_care_id'])) {
throw new \Gems_Exception_Coding(
'$episodeData array should atleast have a key "gec_episode_of_care_id" containing the requested episode id'
);
}
}
// \MUtil_Echo::track($appointmentId, $appointmentData);
return $this->_loadClass('episodeOfCare', true, array($episodeData));
} | Get an appointment object
@param mixed $episodeData Episode id or array containing episode data
@return \Gems\Agenda\EpisodeOfCare | entailment |
public function getEpisodeStatusCodesActive()
{
// A => active, C => Cancelled, E => Error, F => Finished, O => Onhold, P => Planned, W => Waitlist
$codes = array(
'A' => $this->_('Active'),
'F' => $this->_('Finished'),
'O' => $this->_('On hold'),
'P' => $this->_('Planned'),
'W' => $this->_('Waitlist'),
);
asort($codes);
return $codes;
} | Get the status codes for active episode of care items
see https://www.hl7.org/fhir/episodeofcare.html
@return array code => label | entailment |
public function getEpisodesAsOptions(array $episodes)
{
$options = [];
foreach ($episodes as $id => $episode) {
if ($episode instanceof EpisodeOfCare) {
$options[$id] = $episode->getDisplayString();
}
}
return $options;
} | Get the options list episodes for episodes
@param array $episodes
@return array of $episodeId => Description | entailment |
public function getEpisodesFor(\Gems_Tracker_Respondent $respondent, $where = null)
{
return $this->getEpisodesForRespId($respondent->getId(), $respondent->getOrganizationId(), $where);
} | Get the episodes for a respondent
@param \Gems_Tracker_Respondent $respondent
@param $where mixed Optional extra string or array filter
@return array of $episodeId => \Gems\Agenda\EpisodeOfCare | entailment |
public function getEpisodesForRespId($respondentId, $orgId, $where = null)
{
$select = $this->db->select();
$select->from('gems__episodes_of_care')
->where('gec_id_user = ?', $respondentId)
->where('gec_id_organization = ?', $orgId)
->order('gec_startdate DESC');
if ($where) {
if (is_array($where)) {
foreach ($where as $expr => $param) {
if (is_int($expr)) {
$select->where($param);
} else {
$select->where($expr, $param);
}
}
} else {
$select->where($where);
}
}
// \MUtil_Echo::track($select->__toString());
$episodes = $this->db->fetchAll($select);
$output = [];
foreach ($episodes as $episodeData) {
$episode = $this->getEpisodeOfCare($episodeData);
$output[$episode->getId()] = $episode;
}
return $output;
} | Get the episodes for a respondent
@param int $respondentId
@param int $orgId
@param $where mixed Optional extra string or array filter
@return array of $episodeId => \Gems\Agenda\EpisodeOfCare | entailment |
public function getFilterList()
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
$output = $this->cache->load($cacheId);
if ($output) {
return $output;
}
$output = $this->db->fetchPairs("SELECT gaf_id, COALESCE(gaf_manual_name, gaf_calc_name) "
. "FROM gems__appointment_filters WHERE gaf_active = 1 ORDER BY gaf_id_order");
$this->cache->save($output, $cacheId, array('appointment_filters'));
return $output;
} | Load the list of assignable filters
@return array filter_id => label | entailment |
protected function getFieldData()
{
return array(
'gap_id_organization' => array(
'label' => $this->_('Organization'),
'tableName' => 'gems__organizations',
'tableId' => 'gor_id_organization',
'tableLikeFilter' => "gor_active = 1 AND gor_name LIKE '%s'",
),
'gap_source' => array(
'label' => $this->_('Source of appointment'),
),
'gap_id_attended_by' => array(
'label' => $this->_('With'),
'tableName' => 'gems__agenda_staff',
'tableId' => 'gas_id_staff',
'tableLikeFilter' => "gas_active = 1 AND gas_name LIKE '%s'",
),
'gap_id_referred_by' => array(
'label' => $this->_('Referrer'),
'tableName' => 'gems__agenda_staff',
'tableId' => 'gas_id_staff',
'tableLikeFilter' => "gas_active = 1 AND gas_name LIKE '%s'",
),
'gap_id_activity' => array(
'label' => $this->_('Activity'),
'tableName' => 'gems__agenda_activities',
'tableId' => 'gaa_id_activity',
'tableLikeFilter' => "gaa_active = 1 AND gaa_name LIKE '%s'",
),
'gap_id_procedure' => array(
'label' => $this->_('Procedure'),
'tableName' => 'gems__agenda_procedures',
'tableId' => 'gapr_id_procedure',
'tableLikeFilter' => "gapr_active = 1 AND gapr_name LIKE '%s'",
),
'gap_id_location' => array(
'label' => $this->_('Location'),
'tableName' => 'gems__locations',
'tableId' => 'glo_id_location',
'tableLikeFilter' => "glo_active = 1 AND glo_name LIKE '%s'",
),
'gap_subject' => array(
'label' => $this->_('Subject'),
),
);
} | Get a structured nested array contain information on all the appointment
@return array fieldname => array(label[, tableName, tableId, tableLikeFilter)) | entailment |
public function getFilter($filterId)
{
static $filters = array();
if (isset($filters[$filterId])) {
return $filters[$filterId];
}
$found = $this->getFilters("SELECT *
FROM gems__appointment_filters LEFT JOIN gems__track_appointments ON gaf_id = gtap_filter_id
WHERE gaf_active = 1 AND gaf_id = $filterId LIMIT 1");
if ($found) {
$filters[$filterId] = reset($found);
return $filters[$filterId];
}
} | Get a filter from the database
@param $filterId Id of a single filter
@return AppointmentFilterInterface or null | entailment |
public function getFilters($sql)
{
$classes = array();
$filterRows = $this->db->fetchAll($sql);
$output = array();
// \MUtil_Echo::track($filterRows);
foreach ($filterRows as $key => $filter) {
$className = $filter['gaf_class'];
if (! isset($classes[$className])) {
$classes[$className] = $this->newFilterObject($className);
}
$filterObject = clone $classes[$className];
if ($filterObject instanceof AppointmentFilterInterface) {
$filterObject->exchangeArray($filter);
$output[$key] = $filterObject;
}
}
// \MUtil_Echo::track(count($filterRows), count($output));
return $output;
} | Get the filters from the database
@param $sql SQL statement
@return AppointmentFilterInterface[] | entailment |
public function getLocations($orgId = null)
{
// Make sure no invalid data gets through
$orgId = intval($orgId);
$cacheId = __CLASS__ . '_' . __FUNCTION__ . '_' . $orgId;
if ($results = $this->cache->load($cacheId)) {
return $results;
}
$select = $this->db->select();
$select->from('gems__locations', array('glo_id_location', 'glo_name'))
->order('glo_name');
if ($orgId) {
// Check only for active when with $orgId: those are usually used
// with editing, while the whole list is used for display.
$select->where('glo_active = 1');
$select->where("glo_organizations LIKE '%:$orgId:%'");
}
$results = $this->db->fetchPairs($select);
$this->cache->save($results, $cacheId, array('locations'));
return $results;
} | Returns an array with identical key => value pairs containing care provision locations.
@param int $orgId Optional to slect for single organization
@return array | entailment |
public function getStatusKeysActiveDbQuoted()
{
$codes = array();
foreach ($this->getStatusKeysActive() as $key) {
$codes[] = $this->db->quote($key);
}
return new \Zend_Db_Expr(implode(", ", $codes));
} | Get the status keys for active agenda items as a quoted db query string for use in "x IN (?)"
@return \Zend_Db_Expr | entailment |
public function getStatusKeysInactiveDbQuoted()
{
$codes = array();
foreach ($this->getStatusKeysInactive() as $key) {
$codes[] = $this->db->quote($key);
}
return new \Zend_Db_Expr(implode(", ", $codes));
} | Get the status keys for active agenda items as a quoted db query string for use in "x IN (?)"
@return \Zend_Db_Expr | entailment |
public function getTrackCreateOptions()
{
return [
0 => $this->_('Do nothing'),
4 => $this->_('Create new on minimum start date difference'),
3 => $this->_('Create always (unless the appointment already assigned)'),
2 => $this->_('Create new on minimum end date difference'),
5 => $this->_('Create new when all surveys have been completed'),
1 => $this->_('Create new when all surveys have been completed and on minimum end date'),
];
} | Get the element that allows to create a track from an appointment
When adding a new type, make sure to modify \Gems_Agenda_Appointment too
@see \Gems_Agenda_Appointment::getCreatorCheckMethod()
@return array Code => label | entailment |
public function getTypeCodes()
{
return array(
'A' => $this->_('Ambulatory'),
'E' => $this->_('Emergency'),
'F' => $this->_('Field'),
'H' => $this->_('Home'),
'I' => $this->_('Inpatient'),
'S' => $this->_('Short stay'),
'V' => $this->_('Virtual'),
);
} | Get the type codes for agenda items
@return array code => label | entailment |
protected function initTranslateable()
{
if ($this->translateAdapter instanceof \Zend_Translate_Adapter) {
// OK
return;
}
if ($this->translate instanceof \Zend_Translate) {
// Just one step
$this->translateAdapter = $this->translate->getAdapter();
return;
}
if ($this->translate instanceof \Zend_Translate_Adapter) {
// It does happen and if it is all we have
$this->translateAdapter = $this->translate;
return;
}
// Make sure there always is an adapter, even if it is fake.
$this->translateAdapter = new \MUtil_Translate_Adapter_Potemkin();
} | Function that checks the setup of this class/traight
This function is not needed if the variables have been defined correctly in the
source for this object and theose variables have been applied.
return @void | entailment |
protected function loadDefaultFilters()
{
if ($this->_filters) {
return $this->_filters;
}
$cacheId = __CLASS__ . '_' . __FUNCTION__;
$output = $this->cache->load($cacheId);
if ($output) {
foreach ($output as $key => $filterObject) {
// Filterobjects should not serialize anything loaded from a source
if ($filterObject instanceof \MUtil_Registry_TargetInterface) {
$this->applySource($filterObject);
}
$this->_filters[$key] = $filterObject;
}
return $this->_filters;
}
$this->_filters = $this->getFilters("SELECT *
FROM gems__appointment_filters INNER JOIN
gems__track_appointments ON gaf_id = gtap_filter_id INNER JOIN
gems__tracks ON gtap_id_track = gtr_id_track
WHERE gaf_active = 1 AND gtr_active = 1 AND gtr_date_start <= CURRENT_DATE AND
(gtr_date_until IS NULL OR gtr_date_until >= CURRENT_DATE)
ORDER BY gaf_id_order, gtap_id_order");
$this->cache->save($this->_filters, $cacheId, array('appointment_filters', 'tracks'));
return $this->_filters;
} | Load the filters from cache or elsewhere
@return AppointmentFilterInterface[] | entailment |
public function matchHealthcareStaff($name, $organizationId, $create = true)
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
$matches = $this->cache->load($cacheId);
if (! $matches) {
$matches = array();
$select = $this->db->select();
$select->from('gems__agenda_staff')
->order('gas_name');
$result = $this->db->fetchAll($select);
foreach ($result as $row) {
foreach (explode('|', $row['gas_match_to']) as $match) {
$matches[$match][$row['gas_id_organization']] = $row['gas_filter'] ? false : $row['gas_id_staff'];
}
}
$this->cache->save($matches, $cacheId, array('staff'));
}
if (isset($matches[$name])) {
if ($organizationId) {
if (isset($matches[$name][$organizationId])) {
return $matches[$name][$organizationId];
}
} else {
// Return the first location among the organizations
return reset($matches[$name]);
}
}
if (! $create) {
return null;
}
$result = $this->addHealthcareStaff($name, $organizationId);
return $result['gas_filter'] ? false : $result['gas_id_staff'];
} | Find a healt care provider for the name and organization.
@param string $name The name to match against
@param int $organizationId Organization id
@param boolean $create Create a match when it does not exist
@return int gas_id_staff staff id | entailment |
public function matchLocation($name, $organizationId, $create = true)
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
$matches = $this->cache->load($cacheId);
if (! $matches) {
$matches = array();
$select = $this->db->select();
$select->from('gems__locations')
->order('glo_name');
$result = $this->db->fetchAll($select);
foreach ($result as $row) {
foreach (explode('|', $row['glo_match_to']) as $match) {
foreach (explode(':', trim($row['glo_organizations'], ':')) as $subOrg) {
$matches[$match][$subOrg] = $row;
}
}
}
$this->cache->save($matches, $cacheId, array('locations'));
}
if (isset($matches[$name])) {
if ($organizationId) {
if (isset($matches[$name][$organizationId])) {
return $matches[$name][$organizationId];
}
// Not in this organization, if we create we update the record
} else {
// Return the first location among the organizations
return reset($matches[$name]);
}
} else {
$matches[$name] = null;
}
if (! $create) {
return null;
}
$result = $this->addLocation($name, $organizationId, $matches[$name]);
return $result;
} | Find a location for the name and organization.
@param string $name The name to match against
@param int $organizationId Organization id
@param boolean $create Create a match when it does not exist
@return array location | entailment |
public function matchProcedure($name, $organizationId, $create = true)
{
$cacheId = __CLASS__ . '_' . __FUNCTION__;
$matches = $this->cache->load($cacheId);
if (! $matches) {
$matches = array();
$select = $this->db->select();
$select->from('gems__agenda_procedures', array(
'gapr_id_procedure', 'gapr_match_to', 'gapr_id_organization', 'gapr_filter',
));
$result = $this->db->fetchAll($select);
foreach ($result as $row) {
if (null === $row['gapr_id_organization']) {
$key = 'null';
} else {
$key = $row['gapr_id_organization'];
}
foreach (explode('|', $row['gapr_match_to']) as $match) {
$matches[$match][$key] = $row['gapr_filter'] ? false : $row['gapr_id_procedure'];
}
}
$this->cache->save($matches, $cacheId, array('procedures'));
}
if (isset($matches[$name])) {
if (isset($matches[$name][$organizationId])) {
return $matches[$name][$organizationId];
}
if (isset($matches[$name]['null'])) {
return $matches[$name]['null'];
}
}
if (! $create) {
return null;
}
$result = $this->addProcedure($name, $organizationId);
return $result['gapr_filter'] ? false : $result['gapr_id_procedure'];
} | Find a procedure code for the name and organization.
@param string $name The name to match against
@param int $organizationId Organization id
@param boolean $create Create a match when it does not exist
@return int or null | entailment |
public function addContentString($wikiContent)
{
$this->wikiContent .= $wikiContent;
$parsedContent = $this->convertWords($wikiContent);
$this->generator->addContent($parsedContent);
} | Called by the inline parser, when it found a new content.
@param string $wikiContent The original content in wiki syntax | entailment |
public function addContentGenerator($wikiContent, Generator\InlineGeneratorInterface $childGenerator)
{
$this->wikiContent .= $wikiContent;
$this->generator->addContent($childGenerator);
} | Called by the inline parser, when it found a new content.
@param string $wikiContent The original content in wiki syntax
@param Generator\InlineGeneratorInterface $childGenerator The content already parsed (by an other Tag object), when this tag contains other tags. | entailment |
public function getBogusContent()
{
$generator = $this->documentGenerator->getInlineGenerator('textline');
$generator->addRawContent($this->beginTag);
foreach ($this->generator->getChildGenerators() as $child) {
$generator->addContent($child);
}
return $generator;
} | Returns the generated content of the tag.
@return string the content | entailment |
public function generate()
{
$str = '';
$keysize = strlen($this->_alphabet);
for ($i = 0; $i < $this->_length; ++$i) {
$str .= $this->_alphabet[\Sodium\randombytes_uniform($keysize)];
}
return $str;
} | Generates a new identifier.
@return string generated identifier | entailment |
protected function configure(array $config = [])
{
foreach ($config as $key => $value) {
$method = 'set' . $key;
if (method_exists($this, $method)) {
$this->$method($value);
}
}
} | Configures the generator instance.
@param array $config generator configuration | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
if ($this->sortParamAsc) {
$this->dateSelector->getModel()->setSortParamAsc($this->sortParamAsc);
}
if ($this->sortParamDesc) {
$this->dateSelector->getModel()->setSortParamDesc($this->sortParamDesc);
}
$model = $this->dateSelector->getModel();
$filter = $model->getFilter();
// Unset sorts from the filter
unset($filter[$model->getSortParamAsc()]);
unset($filter[$model->getSortParamDesc()]);
// Unset items and page (from paginator)
unset($filter['page']);
unset($filter['items']);
$model->setFilter($filter);
return $this->dateSelector->getTable($this->searchData);
} | 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 resetAction()
{
$model = $this->getModel();
$id = $this->getInstanceId();
if ($model->reset($id)) {
$this->addMessage(sprintf($this->_('Resetting values for template %s to defaults successful'), $id), 'success');
} else {
$this->addMessage(sprintf($this->_('Resetting values for template %s to defaults failed'), $id), 'warning');
}
$this->_reroute(array('action'=>'edit', 'id'=>$id), true);
} | Reset action
Deletes the template-local.ini (by means of a model function) and displays
success or fail messages and returns to the index | entailment |
public function addFormTabs($parentBridge, $name, $arrayOrKey1 = null) {
$options = func_get_args();
$options = \MUtil_Ra::pairs($options, 2);
/* $options = $this->_mergeOptions($name, $options,
self::SUBFORM_OPTIONS); */
//\MUtil_Echo::track($options);
if (isset($options['form'])) {
$form = $options['form'];
unset($options['form']);
} else {
$formClass = get_class($parentBridge->getForm());
$form = new $formClass();
}
$submodel = $parentBridge->getModel()->get($name, 'model');
if ($submodel instanceof \MUtil_Model_ModelAbstract) {
$bridge = $submodel->getBridgeFor('form', $form);
foreach ($submodel->getItemsOrdered() as $itemName) {
if (!$form->getElement($name)) {
if ($submodel->has($itemName, 'label')) {
$bridge->add($itemName);
} else {
$bridge->addHidden($itemName);
}
}
}
}
$form->activateJQuery();
$element = new \Gems_Form_Element_Tabs($form, $name, $options);
$parentBridge->getForm()->addElement($element);
return $element;
} | Adds a form multiple times in a table
You can add your own 'form' either to the model or here in the parameters.
Otherwise a form of the same class as the parent form will be created.
All elements not yet added to the form are added using a new FormBridge
instance using the default label / non-label distinction.
@param \MUtil_Model_Bridge_FormBridgeInterface $parentBridge
@param string $name Name of element
@param mixed $arrayOrKey1 \MUtil_Ra::pairs() name => value array
@return \MUtil_Form_Element_Table | entailment |
public function createBodyElement($name, $label, $required = false, $hidden = false, $mailFields = array(), $mailFieldsLabel = false) {
if ($hidden) {
return new \Zend_Form_Element_Hidden($name);
}
$options['required'] = $required;
$options['label'] = $label;
$mailBody = new \Gems_Form_Element_CKEditor($name, $options);
$mailBody->config['availablefields'] = $mailFields;
if ($mailFieldsLabel) {
$mailBody->config['availablefieldsLabel'] = $mailFieldsLabel;
} else {
$mailBody->config['availablefieldsLabel'] = $this->translate->_('Fields');
}
$mailBody->config['extraPlugins'] .= ',availablefields';
$mailBody->config['toolbar'][] = array('availablefields');
return new \Gems_Form_Element_CKEditor($name, $options);
} | Create an HTML Body element with CKEditor
@return \Gems_Form_Element_CKEditor|\Zend_Form_Element_Hidden | entailment |
public function createEmailElement($name, $label, $required = false, $multi = false) {
$options['label'] = $label;
$options['maxlength'] = 250;
$options['required'] = $required;
$options['size'] = 50;
$element = $this->_form->createElement('text', $name, $options);
if ($multi) {
$element->addValidator('SimpleEmails');
} else {
$element->addValidator('SimpleEmail');
}
return $element;
} | Default creator of an E-mail form element (set with SimpleEmails validations)
@param $name
@param $label
@param bool $required
@param bool $multi
@return \Zend_Form_Element_Text | entailment |
public function createMethodElement() {
$multiOptions = $this->util->getTranslated()->getBulkMailProcessOptions();
$options = array(
'label' => $this->translate->_('Method'),
'multiOptions' => $multiOptions,
'required' => true,
);
return $this->_form->createElement('radio', 'multi_method', $options);
} | Create a multioption select with the different mail process options
@return \Zend_Form_Element_Radio | entailment |
public function createPreviewHtmlElement($label = false) {
if ($label) {
$options['label'] = $this->translate->_($label);
} else {
$options['label'] = $this->translate->_('Preview HTML');
}
$options['nohidden'] = true;
return $this->_form->createElement('Html', 'preview_html', $options);
} | Create the container that holds the preview Email HTML text.
@param bool $noText Is there no preview text button?
@return \MUtil_Form_Element_Exhibitor | entailment |
public function createPreviewTextElement() {
$options['label'] = $this->translate->_('Preview Text');
$options['nohidden'] = true;
return $this->_form->createElement('Html', 'preview_text', $options);
} | Create the container that holds the preview Email Plain text.
@return \MUtil_Form_Element_Exhibitor | entailment |
public function createModel($detailed, $action)
{
$model = new \MUtil_Model_TableModel('gems__consents');
$model->copyKeys(); // The user can edit the keys.
$model->set('gco_description', 'label', $this->_('Description'), 'size', '10');
$model->set('gco_order', 'label', $this->_('Order'), 'size', '10',
'description', $this->_('Determines order of presentation in interface.'),
'validator', 'Digits');
$model->set('gco_code', 'label', $this->_('Consent code'),
'multiOptions', $this->util->getConsentTypes(),
'description', $this->_('Internal code, not visible to users, copied with the token information to the source.'));
if ($detailed) {
$model->set('gco_description', 'validator', $model->createUniqueValidator('gco_description'));
$model->set('gco_order', 'validator', $model->createUniqueValidator('gco_order'));
}
if ($this->project->multiLocale) {
$model->set('gco_description', 'description', 'ENGLISH please! Use translation file to translate.');
}
\Gems_Model::setChangeFieldsByPrefix($model, 'gco');
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 getAuthAdapter(\Gems_User_User $user, $password)
{
$adapter = new \Gems_Auth_Adapter_Callback(array($this->project, 'checkSuperAdminPassword'), $user->getLoginName(), array($password));
return $adapter;
} | Returns an initialized Zend\Authentication\Adapter\AdapterInterface
@param \Gems_User_User $user
@param string $password
@return Zend\Authentication\Adapter\AdapterInterface | entailment |
public function getUserData($loginName, $organization)
{
$orgs = null;
try {
$orgs = $this->db->fetchPairs("SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active = 1 ORDER BY gor_name");
natsort($orgs);
} catch (\Zend_Db_Exception $zde) {
}
if (! $orgs) {
// Table might not exist or be empty, so do something failsafe
$orgs = array($organization => 'create db first');
}
$login = $this->project->getSuperAdminName();
$twoFactor = $this->project->getSuperAdminTwoFactorKey();
return array(
'user_id' => \Gems_User_UserLoader::SYSTEM_USER_ID,
'user_login' => $login,
'user_two_factor_key' => $twoFactor,
'user_enable_2factor' => $twoFactor ? 1 : 0,
'user_name' => $login,
'user_group' => -1,
'user_role' => 'master',
'user_style' => 'gems',
'user_base_org_id' => $organization,
'user_allowed_ip_ranges' => $this->project->getSuperAdminIPRanges(),
'user_blockable' => false,
'__allowedOrgs' => $orgs
);
} | Returns the data for a user object. It may be empty if the user is unknown.
@param string $loginName
@param int $organization
@return array Of data to fill the user with. | entailment |
public function isTwoFactorRequired($ipAddress, $hasKey, Group $group = null)
{
if (! $this->project->getSuperAdminTwoFactorKey()) {
return false;
}
$tfExclude = $this->project->getSuperAdminTwoFactorIpExclude();
if (! $tfExclude) {
return true;
}
return ! $this->util->isAllowedIP($ipAddress, $tfExclude);
} | Should this user be authorized using two factor authentication?
@param string $ipAddress
@param boolean $hasKey
@param Group $group
@return boolean | entailment |
protected function loadFields()
{
$forResp = $this->_('for respondents');
$forStaff = $this->_('for staff');
$this->addField('tokens')
->setLabel($this->_('Tokens'))
->setToCount("gto_id_token");
$this->addSubField('rtokens')
->setLabel($forResp)
->setToSum("ggp_respondent_members")
->setFilter("ggp_respondent_members = 1");
$this->addSubField('stokens')
->setLabel($forStaff)
->setToSum("ggp_staff_members")
->setFilter("ggp_staff_members = 1");
$this->addField('todo')
->setLabel($this->_('Todo'))
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)");
$this->addSubField('rtodo')
->setLabel($forResp)
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)", 'ggp_respondent_members');
$this->addSubField('stodo')
->setLabel($forStaff)
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)", 'ggp_staff_members');
$this->addField('going')
->setLabel($this->_('Partially completed'))
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) AND gto_in_source = 1");
$this->addSubField('rgoing')
->setLabel($forResp)
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) AND gto_in_source = 1", 'ggp_respondent_members');
$this->addSubField('sgoing')
->setLabel($forStaff)
->setToSumWhen("gto_completion_time IS NULL AND (gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP) AND gto_in_source = 1", 'ggp_staff_members');
$this->addField('adleft')
->setLabel($this->_('Time left in days - average'))
->setToAverage("CASE WHEN gto_valid_until IS NOT NULL AND gto_valid_until >= CURRENT_TIMESTAMP THEN DATEDIFF(gto_valid_until, CURRENT_TIMESTAMP) ELSE NULL END", 2);
$this->addSubField('midleft')
->setLabel($this->_('least time left'))
->setToMinimum("CASE WHEN gto_valid_until IS NOT NULL AND gto_valid_until >= CURRENT_TIMESTAMP THEN DATEDIFF(gto_valid_until, CURRENT_TIMESTAMP) ELSE NULL END", 2);
$this->addSubField('madleft')
->setLabel($this->_('most time left'))
->setToMaximum("CASE WHEN gto_valid_until IS NOT NULL AND gto_valid_until >= CURRENT_TIMESTAMP THEN DATEDIFF(gto_valid_until, CURRENT_TIMESTAMP) ELSE NULL END", 2);
$this->addField('missed')
->setLabel($this->_('Missed'))
->setToSumWhen("gto_completion_time IS NULL AND gto_valid_until < CURRENT_TIMESTAMP");
$this->addSubField('rmissed')
->setLabel($forResp)
->setToSumWhen("gto_completion_time IS NULL AND gto_valid_until < CURRENT_TIMESTAMP", 'ggp_respondent_members');
$this->addSubField('smissed')
->setLabel($forStaff)
->setToSumWhen("gto_completion_time IS NULL AND gto_valid_until < CURRENT_TIMESTAMP", 'ggp_staff_members');
$this->addField('done')
->setLabel($this->_('Answered'))
->setToSumWhen("gto_completion_time IS NOT NULL");
$this->addSubField('rdone')
->setLabel($forResp)
->setToSumWhen("gto_completion_time IS NOT NULL", 'ggp_respondent_members');
$this->addSubField('sdone')
->setLabel($forStaff)
->setToSumWhen("gto_completion_time IS NOT NULL", 'ggp_staff_members');
$this->addField('adur')
->setLabel($this->_('Answer time in days - average'))
->setToAverage("gto_completion_time - gto_valid_from", 2);
$this->addSubField('midur')
->setLabel($this->_('fastest answer'))
->setToMinimum("gto_completion_time - gto_valid_from", 2);
$this->addSubField('madur')
->setLabel($this->_('slowest answer'))
->setToMaximum("gto_completion_time - gto_valid_from", 2);
} | Tells the models which fields to expect. | entailment |
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$footer = $bridge->tfrow();
$footer[] = $this->getQuestion();
$footer[] = ' ';
$footer->actionLink(array($this->confirmParameter => 1), $this->_('Yes'));
$footer[] = ' ';
$footer->actionLink($this->findMenuItem($this->request->getControllerName(), $this->abortAction)->toHRefAttribute($this->request), $this->_('No'));
} | Use findmenuitem for the abort action so we get the right id appended
@param \MUtil_Model_Bridge_VerticalTableBridge $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function createModel()
{
if (! $this->model instanceof FieldMaintenanceModel) {
$this->model = $this->trackEngine->getFieldsMaintenanceModel(false, 'index');
}
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = [];
$elements['include_respondent_data'] = $this->_createCheckboxElement('include_respondent_data', $this->_('Include respondent data'));
$elements['include_views'] = $this->_createCheckboxElement('include_views', $this->_('Include views'));
return $elements;
} | Returns a text element for autosearch. Can be overruled.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of (possible nested) \Zend_Form_Element's or static text to add to the html or null for group breaks. | entailment |
public function getFieldsTranslations()
{
$this->_targetModel->setAlias('gas_name_attended_by', 'gap_id_attended_by');
$this->_targetModel->setAlias('gas_name_referred_by', 'gap_id_referred_by');
$this->_targetModel->setAlias('gaa_name', 'gap_id_activity');
$this->_targetModel->setAlias('gapr_name', 'gap_id_procedure');
$this->_targetModel->setAlias('glo_name', 'gap_id_location');
return array(
'gap_patient_nr' => 'gr2o_patient_nr',
'gap_organization_id' => 'gap_id_organization',
'gap_id_in_source' => 'gap_id_in_source',
'gap_admission_time' => 'gap_admission_time',
'gap_discharge_time' => 'gap_discharge_time',
'gap_admission_code' => 'gap_code',
'gap_status_code' => 'gap_status',
'gap_attended_by' => 'gas_name_attended_by',
'gap_referred_by' => 'gas_name_referred_by',
'gap_activity' => 'gaa_name',
'gap_procedure' => 'gapr_name',
'gap_location' => 'glo_name',
'gap_subject' => 'gap_subject',
'gap_comment' => 'gap_comment',
// Autofill fields - without a source field but possibly set in this translator
'gap_id_user',
);
} | 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;
}
// Set fixed values for import
$row['gap_source'] = 'import';
$row['gap_manual_edit'] = 0;
if (! isset($row['gap_id_user'])) {
if (isset($row['gr2o_patient_nr'], $row[$this->orgIdField])) {
$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[$this->orgIdField]));
if ($id) {
$row['gap_id_user'] = $id;
}
}
if (! isset($row['gap_id_user'])) {
// No user no import if still not set
return false;
}
}
if (isset($row['gap_admission_time'], $row['gap_discharge_time']) &&
($row['gap_admission_time'] instanceof \MUtil_Date) &&
($row['gap_discharge_time'] instanceof \MUtil_Date)) {
if ($row['gap_discharge_time']->diffDays($row['gap_admission_time']) > 366) {
if ($row['gap_discharge_time']->diffDays() > 366) {
// $row['gap_discharge_time'] = null;
}
}
}
$skip = false;
if (isset($row['gas_name_attended_by'])) {
$row['gap_id_attended_by'] = $this->_agenda->matchHealthcareStaff(
$row['gas_name_attended_by'],
$row[$this->orgIdField]
);
$skip = $skip || (false === $row['gap_id_attended_by']);
}
if (!$skip && isset($row['gas_name_referred_by'])) {
$row['gap_id_referred_by'] = $this->_agenda->matchHealthcareStaff(
$row['gas_name_referred_by'],
$row[$this->orgIdField]
);
$skip = $skip || (false === $row['gap_id_referred_by']);
}
if (!$skip && isset($row['gaa_name'])) {
$row['gap_id_activity'] = $this->_agenda->matchActivity(
$row['gaa_name'],
$row[$this->orgIdField]
);
$skip = $skip || (false === $row['gap_id_activity']);
}
if (!$skip && isset($row['gapr_name'])) {
$row['gap_id_procedure'] = $this->_agenda->matchProcedure(
$row['gapr_name'],
$row[$this->orgIdField]
);
$skip = $skip || (false === $row['gap_id_procedure']);
}
if (!$skip && isset($row['glo_name'])) {
$location = $this->_agenda->matchLocation(
$row['glo_name'],
$row[$this->orgIdField]
);
$row['gap_id_location'] = is_null($location) ? null : $location['glo_id_location'];
$skip = $skip || is_null($location) || $location['glo_filter'];
}
if ($skip) {
return null;
}
// \MUtil_Echo::track($row);
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 startImport()
{
if ($this->_targetModel instanceof \MUtil_Model_ModelAbstract) {
// No multiOptions as a new items can be created during import
$fields = array(
'gap_id_attended_by', 'gap_id_referred_by', 'gap_id_activity', 'gap_id_procedure', 'gap_id_location',
);
foreach ($fields as $name) {
$this->_targetModel->del($name, 'multiOptions');
}
}
return parent::startImport();
} | Prepare for the import.
@return \MUtil_Model_ModelTranslatorAbstract (continuation pattern) | entailment |
public function execute($versionData = null)
{
$batch = $this->getBatch();
switch (count((array) $versionData)) {
case 0:
// Can be enabled in 1.7.3, for now leave it for testing
// $batch->addToCounter('import_errors');
// $batch->addMessage($this->_('No "version" data found in import file.'));
// break;
case 1;
break;
default:
$batch->addToCounter('import_errors');
$batch->addMessage(sprintf(
$this->_('%d sets of "version" data found in import file.'),
count($versionData)
));
foreach ($tracksData as $lineNr => $versionData) {
$batch->addMessage(sprintf(
$this->_('"version" data found on line %d.'),
$lineNr
));
}
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task
@param array $versionData Nested array of trackdata | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->addColumn(new \Zend_Db_Expr(sprintf(
"CASE WHEN gla_by IS NULL THEN '%s'
ELSE CONCAT(
COALESCE(gsf_last_name, '-'),
', ',
COALESCE(CONCAT(gsf_first_name, ' '), ''),
COALESCE(gsf_surname_prefix, '')
)
END",
$this->_('(no user)')
)), 'staff_name');
$this->addColumn(new \Zend_Db_Expr(sprintf(
"CASE WHEN grs_id_user IS NULL THEN '%s'
ELSE CONCAT(
COALESCE(grs_last_name, '-'),
', ',
COALESCE(CONCAT(grs_first_name, ' '), ''),
COALESCE(grs_surname_prefix, '')
)
END",
$this->_('(no respondent)')
)), 'respondent_name');
} | Called after the check that all required registry values
have been set correctly has run.
This function is no needed if the classes are setup correctly
@return void | entailment |
public function applyBrowseSettings($detailed = false)
{
$this->resetOrder();
//Not only active, we want to be able to read the log for inactive organizations too
$orgs = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations');
$this->set('gla_created', 'label', $this->_('Date'));
$this->set('gls_name', 'label', $this->_('Action'));
$this->set('gla_organization', 'label', $this->_('Organization'), 'multiOptions', $orgs);
$this->set('staff_name', 'label', $this->_('Staff'));
$this->set('gla_role', 'label', $this->_('Role'));
$this->set('respondent_name', 'label', $this->_('Respondent'));
$jdType = new JsonData();
$this->set('gla_message', 'label', $this->_('Message'));
$jdType->apply($this, 'gla_message', $detailed);
if ($detailed) {
$mjdType = new MaskedJsonData($this->currentUser);
$this->set('gla_data', 'label', $this->_('Data'));
$mjdType->apply($this, 'gla_data', $detailed);
$this->set('gla_method', 'label', $this->_('Method'));
$this->set('gla_remote_ip', 'label', $this->_('IP address'));
}
$this->refreshGroupSettings();
} | Set those settings needed for the browse display
@return \Gems\Model\LogModel | entailment |
public function refreshGroupSettings()
{
$group = $this->currentUser->getGroup();
if ($group instanceof Group) {
$group->applyGroupToModel($this, false);
}
} | Function to re-apply all the masks and settings for the current group
@return void | entailment |
public function afterImport(\MUtil_Task_TaskBatch $batch, \MUtil_Form_Element_Html $element)
{
$text = parent::afterImport($batch, $element);
$data = $this->formData;
// Remove unuseful data
unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId]);
// Add useful data
$data['localfile'] = basename($this->_session->localfile);
$data['extension'] = $this->_session->extension;
$data['failureDirectory'] = '...' . substr($this->importer->getFailureDirectory(), -30);
$data['longtermFilename'] = basename($this->importer->getLongtermFilename());
$data['successDirectory'] = '...' . substr($this->importer->getSuccessDirectory(), -30);
$data['tempDirectory'] = '...' . substr($this->tempDirectory, -30);
$data['importTranslator'] = get_class($this->importer->getImportTranslator());
$data['sourceModelClass'] = get_class($this->sourceModel);
$data['targetModelClass'] = get_class($this->targetModel);
ksort($data);
$this->accesslog->logChange($this->request, null, array_filter($data));
} | Hook for after save
@param \MUtil_Task_TaskBatch $batch that was just executed
@param \MUtil_Form_Element_Html $element Tetx element for display of messages
@return string a message about what has changed (and used in the form) | entailment |
public function isAvailable()
{
try {
/** @var Response $result */
$result = $this->get('/', $this->getGuzzleOptions());
if ($result->getStatusCode() == 200) {
return true;
}
} catch (RequestException $ex) {
$msg = sprintf("Tika unavailable - %s", $ex->getMessage());
Injector::inst()->get(LoggerInterface::class)->info($msg);
return false;
}
} | Detect if the service is available
@return bool | entailment |
public function getVersion()
{
/** @var Response $response */
$response = $this->get('version', $this->getGuzzleOptions());
$version = 0.0;
// Parse output
if ($response->getStatusCode() == 200
&& preg_match('/Apache Tika (?<version>[\.\d]+)/', $response->getBody(), $matches)
) {
$version = (float)$matches['version'];
}
return $version;
} | Get version code
@return float | entailment |
public function getSupportedMimes()
{
if ($this->mimes) {
return $this->mimes;
}
$response = $this->get(
'mime-types',
$this->getGuzzleOptions([
'headers' => [
'Accept' => 'application/json',
],
])
);
return $this->mimes = Convert::json2array($response->getBody());
} | Gets supported mime data. May include aliased mime types.
@return array | entailment |
public function tika($file)
{
$text = null;
try {
/** @var Response $response */
$response = $this->put(
'tika',
$this->getGuzzleOptions([
'headers' => [
'Accept' => 'text/plain',
],
'body' => file_get_contents($file),
])
);
$text = $response->getBody();
} catch (RequestException $e) {
$msg = sprintf(
'TikaRestClient was not able to process %s. Response: %s %s.',
$file,
$e->getResponse()->getStatusCode(),
$e->getResponse()->getReasonPhrase()
);
// Only available if tika-server was started with --includeStack
$body = $e->getResponse()->getBody();
if ($body) {
$msg .= ' Body: ' . $body;
}
Injector::inst()->get(LoggerInterface::class)->info($msg);
}
return (string) $text;
} | Extract text content from a given file.
Logs a notice-level error if the document can't be parsed.
@param string $file Full filesystem path to a file to post
@return string Content of the file extracted as plain text | entailment |
protected function getGuzzleOptions($options = [])
{
if (!empty($this->options['username']) && !empty($this->options['password'])) {
$options['auth'] = [
$this->options['username'],
$this->options['password']
];
}
return $options;
} | Assembles an array of request options to pass to Guzzle
@param array $options Authentication (etc) will be merged into this array and returned
@return array | entailment |
public function execute($lineNr = null, $conditionData = null)
{
$batch = $this->getBatch();
$conditions = $this->loader->getConditions();
$import = $batch->getVariable('import');
if (isset($conditionData['gcon_id']) && $conditionData['gcon_id']) {
$import['importConditions'][$conditionData['gcon_id']] = false;
} else {
$batch->addToCounter('import_errors');
$batch->addMessage(sprintf(
$this->_('No gcon_id specified for condition at line %d.'),
$lineNr
));
}
if (isset($conditionData['gcon_class']) && $conditionData['gcon_class']) {
try {
$conditions->loadRoundCondition($conditionData['gcon_class']);
} catch (\Gems_Exception_Coding $ex) {
$batch->addToCounter('import_errors');
$batch->addMessage(sprintf(
$this->_('Unknown or invalid round condition "%s" specified on line %d.'),
$conditionData['gcon_class'],
$lineNr
));
}
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
public function authenticate()
{
$this->_authenticateSetup();
if ($this->_radius->AccessRequest($this->_identity,$this->_credential)) {
$this->_authenticateResultInfo['code'] = Result::SUCCESS;
$this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
} else {
$this->_authenticateResultInfo['code'] = Result::FAILURE;
$this->_authenticateResultInfo['messages'][] = 'Authentication failed.';
}
$authResult = $this->_authenticateCreateAuthResult();
return $authResult;
} | authenticate() - defined by Zend\Authentication\Adapter\AdapterInterface. This method is called to
attempt an authenication. Previous to this call, this adapter would have already
been configured with all necessary information to successfully connect to a Radius
server and attempt to find a record matching the provided identity.
@throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed
@return Zend\Authentication\Result | entailment |
protected function _authenticateSetup()
{
$exception = null;
if ($this->_ip === null) {
$exception = 'An ip address must be specified for use with the \Gems_User_Adapter_Radius authentication adapter.';
} elseif ($this->_sharedSecret === null) {
$exception = 'A shared secret must be specified for use with the \Gems_User_Adapter_Radius authentication adapter.';
} elseif ($this->_identity == '') {
$exception = 'A value for the identity was not provided prior to authentication with \Gems_User_Adapter_Radius.';
} elseif ($this->_credential === null) {
$exception = 'A credential value was not provided prior to authentication with \Gems_User_Adapter_Radius.';
}
if (null !== $exception) {
/**
* @see \Gems_Exception_Coding
*/
throw new \Gems_Exception_Coding($exception);
}
$this->_authenticateResultInfo = array(
'code' => Result::FAILURE,
'identity' => $this->_identity,
'messages' => array()
);
$this->_radius = new Radius($this->_ip, $this->_sharedSecret,$this->_suffix,$this->_timeout,$this->_authenticationPort,$this->_accountingPort);
return true;
} | _authenticateSetup() - This method abstracts the steps involved with making sure
that this adapter was indeed setup properly with all required peices of information.
@throws \Gems_Exception_Coding - in the event that setup was not done properly
@return true | entailment |
public function addExistingRoundsToModel(\ArrayObject $import, \MUtil_Model_ModelAbstract $model)
{
$currentRounds = $this->trackEngine->getRounds();
if (! $currentRounds) {
return;
}
$importRounds = array();
$newImportRounds = array();
$tracker = $this->loader->getTracker();
foreach ($import['rounds'] as $lineNr => $roundData) {
if (isset($roundData['survey_export_code'], $import['surveyCodes'][$roundData['survey_export_code']])) {
$roundData['gro_id_survey'] = $import['surveyCodes'][$roundData['survey_export_code']];
$round = $tracker->createTrackClass('Round', $roundData);
$importRounds[$round->getRoundOrder()] = $round->getFullDescription();
$newImportRounds[$round->getRoundOrder()] = sprintf(
$this->_('Set round to round %s'),
$round->getFullDescription()
);
$import['roundOrderToLine'][$round->getRoundOrder()] = $lineNr;
}
}
// Filter for rounds not in current track
foreach ($currentRounds as $roundId => $round) {
if ($round instanceof Round) {
$order = $round->getRoundOrder();
if (isset($newImportRounds[$order])) {
unset($newImportRounds[$order]);
}
}
}
$except = array(self::ROUND_LEAVE, self::ROUND_DEACTIVATE);
$notEqualTo = array(); // Make sure no round is imported twice
foreach ($currentRounds as $roundId => $round) {
if ($round instanceof Round) {
$name = "round_$roundId";
$order = $round->getRoundOrder();
$model->set($name,
'existingRound', true,
'required', true,
'roundId', $roundId
);
if (isset($importRounds[$order])) {
if ($round->getFullDescription() == $importRounds[$order]) {
$options = array(
self::ROUND_LEAVE => $this->_('Leave current round'),
$order => $this->_('Replace with import round'),
);
} else {
$options = array(
self::ROUND_LEAVE => $this->_('Leave current round'),
$order => sprintf(
$this->_('Replace with import round %s'),
$importRounds[$order]
),
);
}
$model->set($name,
'label', sprintf(
$this->_('Matching round %s'),
$round->getFullDescription()
),
'elementClass', 'Radio',
'multiOptions', $options
);
$value = $order;
} else {
$model->set($name,
'label', sprintf(
$this->_('Round not in import: %s'),
$round->getFullDescription()
),
'elementClass', 'Select',
'multiOptions', array(
self::ROUND_LEAVE => sprintf($this->_('Leave current round %d unchanged'), $order),
self::ROUND_DEACTIVATE => sprintf($this->_('Deactivate current round %d'), $order),
) + $newImportRounds,
'size', 3 + count($newImportRounds)
);
$value = null;
if ($notEqualTo) {
$notEqualVal = new NotEqualExcept($notEqualTo, $except);
$model->set($name, 'validators[notequal]', $notEqualVal);
}
$notEqualTo[] = $name;
}
if (! array_key_exists($name, $this->formData)) {
$this->formData[$name] = $value;
}
}
}
} | Add the settings from the transformed import data to the formData and the model
@param \ArrayObject $import
@param \MUtil_Model_ModelAbstract $model | entailment |
public function addImportToModelData(\ArrayObject $import)
{
// formDefaults are set in the Gems\Task\Tracker\Import tasks
if (isset($import['formDefaults']) && $import['formDefaults']) {
foreach ($import['formDefaults'] as $name => $default) {
if (! (isset($this->formData[$name]) && $this->formData[$name])) {
$this->formData[$name] = $default;
}
}
}
// \MUtil_Echo::track($this->formData);
// modelSettings are set in the Gems\Task\Tracker\Import tasks
if (isset($import['modelSettings']) && $import['modelSettings']) {
$model = $this->getModel();
foreach ($import['modelSettings'] as $name => $settings) {
// \MUtil_Echo::track($name, $settings);
$model->set($name, $settings);
}
}
} | Add the settings from the transformed import data to the formData and the model
@param \ArrayObject $import | entailment |
protected function addStepChangeTrack(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$this->displayHeader($bridge, $this->_('Change track information.'), 'h3');
// Load the import data form settings
$this->loadImportData();
// Always add organization select, even when they were not exported
$this->addItems($bridge, $model->getColNames('respondentData'));
// \MUtil_Echo::track($this->formData);
$all = $this->loader->getUtil()->getTrackData()->getAllSurveys();
$available = array('' => $this->_('(skip rounds)')) + $all;
// \MUtil_Echo::track($all);
$form = $bridge->getForm();
$surveyHeader = $form->createElement('Html', 'sheader1');
$surveyHeader->h3($this->_('Survey export code links'));
$form->addElement($surveyHeader);
$surveySubHeader = $form->createElement('Html', 'sheader2');
$surveySubHeader->strong($this->_('Linked survey name'));
$surveySubHeader->setLabel($this->_('Import survey name'))
->setDescription(sprintf($this->_('[%s]'), $this->_('export code')))
->setRequired(true);
$form->addElement($surveySubHeader);
$this->addItems($bridge, $model->getColNames('isSurvey'));
// \MUtil_Echo::track($this->_session->uploadFileName, $import->getArrayCopy());
} | Add the elements from the model to the bridge for file check step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepCreateTrack(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
// Things go really wrong (at the session level) if we run this code
// while the finish button was pressed
if ($this->isFinishedClicked()) {
return;
}
$this->nextDisabled = true;
$this->displayHeader($bridge, $this->_('Creating the track.'), 'h3');
$batch = $this->getImportCreateBatch();
$form = $bridge->getForm();
$batch->setFormId($form->getId());
$batch->autoStart = true;
// \MUtil_Registry_Source::$verbose = true;
if ($batch->run($this->request)) {
exit;
}
$element = $form->createElement('html', $batch->getId());
if ($batch->isFinished()) {
$this->nextDisabled = $batch->getCounter('create_errors');
$batch->autoStart = false;
// Keep the filename after $batch->getMessages(true) cleared the previous
$this->addMessage($batch->getMessages(true));
if ($this->nextDisabled) {
$element->pInfo($this->_('Errors occurred during import!'));
} else {
$element->h3($this->_('Track created successfully!'));
$element->pInfo($this->_('Click the "Finish" button to see the track.'));
}
$data = $this->formData;
// Remove unuseful data
unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId], $data['auto_form_focus_tracker']);
// Add useful data
ksort($data);
$this->accesslog->logChange($this->request, null, array_filter($data));
} else {
$element->setValue($batch->getPanel($this->view, $batch->getProgressPercentage() . '%'));
}
$form->activateJQuery();
$form->addElement($element);
// \MUtil_Echo::track($this->loadImportData()->getArrayCopy());
} | Add the elements from the model to the bridge for file check step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepElementsFor(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model, $step)
{
$this->displayHeader($bridge, $this->getFormTitle($step), 'h2');
switch ($step) {
case 2:
$this->addStepFileCheck($bridge, $model);
break;
case 3:
$this->addStepChangeTrack($bridge, $model);
break;
case 4:
if ($this->trackEngine) {
$this->addStepRoundMatch($bridge, $model);
} else {
$this->addStepCreateTrack($bridge, $model);
}
break;
case 5:
if ($this->trackEngine) {
$this->addStepMergeTrack($bridge, $model);
break;
}
// Intentional faal through
default:
$this->addStepFileImport($bridge, $model);
break;
}
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model
@param int $step The current step | entailment |
protected function addStepFileCheck(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($this->onStartStep() && $this->isNextClicked()) {
return;
}
$this->nextDisabled = true;
$this->displayHeader($bridge, $this->_('Checking the content of the file.'), 'h3');
$batch = $this->getImportCheckBatch();
$form = $bridge->getForm();
$batch->setFormId($form->getId());
$batch->autoStart = true;
// \MUtil_Registry_Source::$verbose = true;
if ($batch->run($this->request)) {
exit;
}
$element = $form->createElement('html', $batch->getId());
if ($batch->isFinished()) {
$this->nextDisabled = $batch->getCounter('import_errors');
$batch->autoStart = false;
// Keep the filename after $batch->getMessages(true) cleared the previous
$this->addMessage($batch->getMessages(true));
if ($this->nextDisabled) {
$element->pInfo($this->_('Import errors occurred!'));
} else {
$element->h3($this->_('Import checks OK!'));
$element->pInfo($this->_('Click the "Next" button to continue.'));
}
} else {
$element->setValue($batch->getPanel($this->view, $batch->getProgressPercentage() . '%'));
}
$form->activateJQuery();
$form->addElement($element);
} | Add the elements from the model to the bridge for file check step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepFileImport(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
// Reset the data
$this->_session->importData = null;
$this->displayHeader($bridge, $this->_('Upload a track definition file.'), 'h3');
$this->addItems($bridge, 'trackFile', 'gtr_id_track');
$element = $bridge->getForm()->getElement('trackFile');
if ($element instanceof \Zend_Form_Element_File) {
if (file_exists($this->_session->localfile)) {
unlink($this->_session->localfile);
}
// Now add the rename filter, the localfile is known only once after loadFormData() has run
$element->addFilter(new \Zend_Filter_File_Rename(array(
'target' => $this->_session->localfile,
'overwrite' => true
)));
$uploadFileName = $element->getFileName();
// Download the data oon post with filename
if ($this->request->isPost() && $uploadFileName && $element->isValid(null)) {
// \MUtil_Echo::track($element->getFileName(), $element->getFileSize());
if (!$element->receive()) {
throw new \MUtil_Model_ModelException(sprintf(
$this->_("Error retrieving file '%s'."),
$element->getFileName()
));
}
$this->_session->importData = null;
$this->_session->uploadFileName = basename($uploadFileName);
// \MUtil_Echo::track($this->_session->uploadFileName);
}
}
} | Add the elements from the model to the bridge for file upload step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepRoundMatch(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$this->displayHeader($bridge, $this->_('Match the current track rounds to import rounds.'), 'h3');
// Load the import data form settings
$import = $this->loadImportData();
$this->addExistingRoundsToModel($import, $model);
$rounds = $model->getColNames('existingRound');
if ($rounds) {
$this->addItems($bridge, $rounds);
} else {
$bridge->addHtml('existingRound')->pInfo($this->_('No rounds in current track.'));
}
} | Add the elements from the model to the bridge for file check step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function afterFormValidationFor($step)
{
parent::afterFormValidationFor($step);
if (3 == $step) {
$import = $this->loadImportData();
$model = $this->getModel();
$saves = array();
foreach ($model->getCol('exportCode') as $name => $exportCode) {
if (isset($this->formData[$name]) && $this->formData[$name]) {
$saves[] = array('gsu_id_survey' => $this->formData[$name], 'gsu_export_code' => $exportCode);
$import['surveyCodes'][$exportCode] = $this->formData[$name];
}
}
if ($saves) {
$sModel = new \MUtil_Model_TableModel('gems__surveys');
\Gems_Model::setChangeFieldsByPrefix($sModel, 'gus', $this->currentUser->getUserId());
$sModel->saveAll($saves);
$count = $sModel->getChanged();
if ($count == 0) {
$this->addMessage($this->_('No export code changed'));
} else {
$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('surveys'));
$this->addMessage(sprintf(
$this->plural('%d export code changed', '%d export codes changed', $count),
$count
));
}
}
}
if ($this->trackEngine && 4 == $step) {
$import = $this->loadImportData();
$model = $this->getModel();
$saves = array();
$import['deactivateRounds'] = array();
foreach ($model->getCol('roundId') as $name => $roundId) {
$round = $this->trackEngine->getRound($roundId);
if (isset($this->formData[$name]) && $this->formData[$name] && $round instanceof Round) {
switch ($this->formData[$name]) {
case self::ROUND_DEACTIVATE:
$import['deactivateRounds'][$roundId] = $round->getFullDescription();
break;
case self::ROUND_LEAVE:
if (isset($import['roundOrderToLine'][$round->getRoundOrder()])) {
$lineNr = $import['roundOrderToLine'][$round->getRoundOrder()];
unset($import['rounds'][$lineNr]);
}
$import['roundOrders'][$round->getRoundOrder()] = $roundId;
break;
default:
if (isset($import['roundOrderToLine'][$this->formData[$name]])) {
$lineNr = $import['roundOrderToLine'][$this->formData[$name]];
$import['rounds'][$lineNr]['gro_id_round'] = $roundId;
}
$import['roundOrders'][$this->formData[$name]] = $roundId;
break;
}
}
}
}
} | Overrule this function for any activities you want to take place
after the form has successfully been validated, but before any
buttons are processed.
@param int $step The current step | entailment |
protected function afterSave($changed)
{
if ($this->trackEngine) {
$this->addMessage($this->_('Track merge finished'));
} else {
$this->addMessage($this->_('Track import finished'));
}
$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('tracks'));
} | Hook that allows actions when data was saved
When not rerouted, the form will be populated afterwards
@param int $changed The number of changed rows (0 or 1 usually, but can be more) | entailment |
protected function createModel()
{
if (! $this->importModel instanceof \MUtil_Model_ModelAbstract) {
$model = new \MUtil_Model_SessionModel('import_for_' . $this->request->getControllerName());
$model->set('trackFile', 'label', $this->_('A .track.txt file'),
'count', 1,
'elementClass', 'File',
'extension', 'txt',
'description', $this->_('Import an exported track using a file with the extension ".track.txt".'),
'required', true
);
$model->set('importId');
$options = array('' => $this->_('<<create a new track>>')) + $this->util->getTrackData()->getAllTracks();
$model->set('gtr_id_track', 'label', $this->_('Merge with'),
'description', $this->_('Create a new track or choose a track to merge the import into.'),
'default', '',
'multiOptions', $options,
'size', min(12, count($options) + 1)
);
$trackModel = $this->loader->getTracker()->getTrackModel();
$trackModel->applyFormatting(true, true);
$model->set('gtr_track_name', $trackModel->get('gtr_track_name') + array('respondentData' => true));
$model->set('gtr_organizations', $trackModel->get('gtr_organizations') + array('respondentData' => true));
$this->importModel = $model;
}
return $this->importModel;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function displayHeader(\MUtil_Model_Bridge_FormBridgeInterface $bridge, $header, $tagName = 'h2')
{
static $count = 0;
$count += 1;
$element = $bridge->getForm()->createElement('html', 'step_header_' . $count);
$element->$tagName($header);
$bridge->addElement($element);
} | Display a header
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param mixed $header Header content
@param string $tagName | entailment |
protected function getFormFor($step)
{
$baseform = $this->createForm();
if ($this->trackEngine &&
($step == 4) &&
(\MUtil_Bootstrap::enabled() !== true) &&
($baseform instanceof \MUtil_Form)) {
$model = $this->getModel();
$table = new \MUtil_Html_DivFormElement();
$table->setAsFormLayout($baseform);
$baseform->setAttrib('class', $this->class);
$bridge = $model->getBridgeFor('form', $baseform);
$this->_items = null;
$this->initItems();
$this->addFormElementsFor($bridge, $model, $step);
return $baseform;
} else {
return parent::getFormFor($step);
}
} | Creates from the model a \Zend_Form using createForm and adds elements
using addFormElements().
@param int $step The current step
@return \Zend_Form | entailment |
protected function getFormTitle($step)
{
if ($this->trackEngine) {
return sprintf(
$this->_('Merge import into "%s" track. Step %d of %d.'),
$this->trackEngine->getTrackName(),
$step,
$this->getStepCount()
);
}
return sprintf(
$this->_('New track import. Step %d of %d.'),
$step,
$this->getStepCount()
);
} | Get the title at the top of the form
@param int $step The current step
@return string | entailment |
protected function loadFormData()
{
$model = $this->getModel();
if ($this->request->isPost()) {
$this->formData = $model->loadPostData($this->request->getPost() + $this->formData, true);
} else {
// Assume that if formData is set it is the correct formData
if (! $this->formData) {
$this->formData = $model->loadNew();
}
}
if (isset($this->formData['gtr_id_track']) && $this->formData['gtr_id_track']) {
$this->trackEngine = $this->loader->getTracker()->getTrackEngine($this->formData['gtr_id_track']);
}
if (! (isset($this->formData['importId']) && $this->formData['importId'])) {
$this->formData['importId'] = mt_rand(10000,99999) . time();
}
$this->_session = new \Zend_Session_Namespace(__CLASS__ . '-' . $this->formData['importId']);
if (! (isset($this->_session->localfile) && $this->_session->localfile)) {
$importLoader = $this->loader->getImportLoader();
$this->_session->localfile = \MUtil_File::createTemporaryIn(
$importLoader->getTempDirectory(),
$this->request->getControllerName() . '_'
);
}
// \MUtil_Echo::track($this->formData);
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function loadImportData()
{
if (isset($this->_session->importData) && ($this->_session->importData instanceof \ArrayObject)) {
// No need to run this after initial load, but we need to
// run this every time afterwards.
$this->addImportToModelData($this->_session->importData);
return $this->_session->importData;
}
$sections = $this->getImportSections();
// Array object to have automatic passing by reference
$this->_session->importData = new \ArrayObject(array_fill_keys(
array_keys($sections) + array('errors'),
array()
));
$file = $this->_session->localfile;
if (! file_exists($file)) {
$this->_session->importData['errors'][] = sprintf(
$this->_('The import file "%s" seems to be missing.'),
$this->_session->uploadFileName
);
return $this->_session->importData;
}
$content = file_get_contents($file);
if (! $content) {
$this->_session->importData['errors'][] = sprintf(
$this->_('The import file "%s" is empty.'),
$this->_session->uploadFileName
);
return $this->_session->importData;
}
$fieldsCount = 0;
$fieldsNames = false;
$fieldsReset = false;
$key = false;
$lineNr = 0;
foreach (explode("\r\n", $content) as $line) {
$lineNr++;
if ($line) {
if (strpos($line, "\t") === false) {
$key = strtolower(trim($line));
$fieldsNames = false;
$fieldsReset = false;
if (isset($sections[$key])) {
$fieldsReset = $sections[$key];
} else {
$this->_session->importData['errors'][] = sprintf(
$this->_('Unknown data type identifier "%s" found at line %s.'),
trim($line),
$lineNr
);
$key = false;
}
} else {
$raw = explode("\t", $line);
if ($fieldsNames) {
if (count($raw) === $fieldsCount) {
$data = array_combine($fieldsNames, $raw);
$this->_session->importData[$key][$lineNr] = $data;
} else {
$this->_session->importData['errors'][] = sprintf(
$this->_('Incorrect number of fields at line %d. Found %d while %d expected.'),
$lineNr,
count($raw),
$fieldsCount
);
}
if ($fieldsReset) {
$fieldsNames = false;
}
} else {
$fieldsNames = $raw;
$fieldsCount = count($fieldsNames);
}
}
}
}
return $this->_session->importData;
} | Load the import data in an array fo the type:
\ArrayObject(array(
'track' => array(linenr => array),
'organizations' => array(linenr => array),
'fields' => array(linenr => array),
'surveys' => array(linenr => array),
'rounds' => array(linenr => array),
'errors' => array(linenr => string),
))
Stored in session
@return \ArrayObject | entailment |
protected function setAfterSaveRoute()
{
if ($this->_session->localfile && file_exists($this->_session->localfile)) {
// Now is a good moment to remove the temporary file
@unlink($this->_session->localfile);
}
$import = $this->loadImportData();
if (isset($import['trackId']) && $import['trackId']) {
$trackId = $import['trackId'];
$this->routeAction = 'show';
} else {
$trackId = null;
}
// Default is just go to the index
if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
$this->afterSaveRouteUrl = array(
$this->request->getControllerKey() => $this->request->getControllerName(),
$this->request->getActionKey() => $this->routeAction,
\MUtil_Model::REQUEST_ID => $trackId,
);
}
return $this;
} | Set what to do when the form is 'finished'.
@return \Gems\Tracker\Snippets\ImportMergeSnippetAbstract | entailment |
protected function validateForm()
{
if (2 == $this->currentStep) {
return true;
}
// Note we use an MUtil_Form
return $this->_form->isValid($this->formData, $this->disableValidatorTranslation);
} | Performs the validation.
@return boolean True if validation was OK and data should be saved. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.