sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getSearchFilter($useRequest = true) { $filter = parent::getSearchFilter($useRequest); unset($filter['AUTO_SEARCH_TEXT_BUTTON']); $where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db, null, 'yyyy-MM-dd HH:mm:ss'); if ($where) { $filter[] = $where; } if (! isset($filter['gto_id_organization'])) { $filter['gto_id_organization'] = $this->currentUser->getRespondentOrgFilter(); } $filter['gsu_active'] = 1; // When we dit not select a specific status we skip the deleted status if (!isset($filter['token_status'])) { $filter['grc_success'] = 1; } if (isset($filter['main_filter'])) { switch ($filter['main_filter']) { case 'hasnomail': $filter[] = sprintf( "((gr2o_email IS NULL OR gr2o_email = '' OR gr2o_email NOT RLIKE '%1\$s') AND ggp_respondent_members = 1 AND gto_id_relationfield IS NULL) OR ((grr_email IS NULL OR grr_email = '' OR grr_email NOT RLIKE '%1\$s') AND ggp_respondent_members = 1 AND gto_id_relationfield IS NOT NULL)", str_replace('\'', '\\\'', trim(\MUtil_Validate_SimpleEmail::EMAIL_REGEX, '/')) ); $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'; $filter['gto_completion_time'] = null; // Exclude not mailable, we don't want to ask them for email if we are not allowed to used it anyway $filter['gr2o_mailable'] = 1; $filter['gr2t_mailable'] = 1; break; case 'notmailable': $filter[] = '(gr2o_mailable = 0 OR gr2t_mailable = 0) AND ggp_respondent_members = 1'; $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'; $filter['gto_completion_time'] = null; break; case 'notmailed': $filter['gto_mail_sent_date'] = null; $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'; $filter['gto_completion_time'] = null; break; case 'tomail': $filter[] = sprintf( "(gr2o_email IS NOT NULL AND gr2o_email != '' AND gr2o_email RLIKE '%1\$s' AND ggp_respondent_members = 1 AND gto_id_relationfield IS NULL) OR (grr_email IS NOT NULL AND grr_email != '' AND grr_email RLIKE '%1\$s' AND ggp_respondent_members = 1 AND gto_id_relationfield IS NOT NULL)", str_replace('\'', '\\\'', trim(\MUtil_Validate_SimpleEmail::EMAIL_REGEX, '/')) ); $filter['gto_mail_sent_date'] = null; $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'; $filter['gto_completion_time'] = null; // Exclude not mailable $filter['gr2o_mailable'] = 1; $filter['gr2t_mailable'] = 1; break; case 'toremind': // $filter['can_email'] = 1; $filter[] = 'gto_mail_sent_date < CURRENT_TIMESTAMP'; $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)'; $filter['gto_completion_time'] = null; break; default: break; } unset($filter['main_filter']); } return $filter; }
Get the filter to use with the model for searching @param boolean $useRequest Use the request as source (when false, the session is used) @return array or false
entailment
public function indexAction() { if ($this->checkForAnswersOnLoad) { $this->loader->getTracker()->processCompletedTokens( null, $this->currentUser->getUserId(), $this->currentUser->getCurrentOrganizationId(), true ); } parent::indexAction(); }
Default overview action
entailment
public function extractFileAsText($disableCache = false) { /** @var File $file */ $file = $this->owner; if (!$disableCache) { $text = $this->getTextCache()->load($file); if ($text) { return $text; } } // Determine which extractor can process this file. $extractor = FileTextExtractor::for_file($file); if (!$extractor) { return null; } $text = $extractor->getContent($file); if (!$text) { return null; } if (!$disableCache) { $this->getTextCache()->save($file, $text); } return $text; }
Tries to parse the file contents if a FileTextExtractor class exists to handle the file type, and returns the text. The value is also cached into the File record itself. @param boolean $disableCache If false, the file content is only parsed on demand. If true, the content parsing is forced, bypassing the cached version @return string|null
entailment
protected function addTableCells(\MUtil_Model_Bridge_VerticalTableBridge $bridge) { $bridge->setColumnCount(1); $HTML = \MUtil_Html::create(); $bridge->tdh($this->getCaption(), array('colspan' => 2)); // Caption for tracks $trackLabel = $this->_('Assigned tracks'); if ($menuItem = $this->findMenuItem('track', 'index')) { $href = $menuItem->toHRefAttribute($this->request, $bridge); $bridge->tdh(array('class' => 'linked'))->a($href, $trackLabel); } else { $bridge->tdh($trackLabel, array('class' => 'linked')); } $bridge->tr(); // ROW 1 $bridge->addItem($bridge->gr2o_patient_nr, $this->_('Respondent nr: ')); $rowspan = 10; // Column for tracks $tracksModel = $this->model->getRespondentTracksModel(); $tracksData = \MUtil_Lazy::repeat( $tracksModel->load( array('gr2o_patient_nr' => $this->repeater->gr2o_patient_nr, 'gr2o_id_organization' => $this->repeater->gr2o_id_organization), array('gr2t_created' => SORT_DESC))); $tracksList = $HTML->div($tracksData, array('class' => 'tracksList')); $tracksList->setOnEmpty($this->_('No tracks')); if ($menuItem = $this->findMenuItem('track', 'show-track')) { $href = $menuItem->toHRefAttribute($tracksData, array('gr2o_patient_nr' => $this->repeater->gr2o_patient_nr)); $tracksTarget = $tracksList->p()->a($href); } else { $tracksTarget = $tracksList->p(); } $tracksTarget->strong($tracksData->gtr_track_name); $tracksTarget[] = ' '; $tracksTarget->em($tracksData->gr2t_track_info, array('renderWithoutContent' => false)); $tracksTarget[] = ' '; $tracksTarget[] = \MUtil_Lazy::call($this->util->getTranslated()->formatDate, $tracksData->gr2t_created); $bridge->td($tracksList, array('rowspan' => $rowspan, 'class' => 'linked tracksList')); // OTHER ROWS $bridge->addItem( $HTML->spaced($bridge->itemIf('grs_last_name', array($bridge->grs_last_name, ',')), $bridge->grs_first_name, $bridge->grs_surname_prefix), $this->_('Respondent')); $bridge->addItem('grs_gender'); $bridge->addItem('grs_birthday'); $bridge->addItem('gr2o_email'); $bridge->addItem('gr2o_created'); $bridge->addItem('gr2o_created_by'); if ($this->onclick) { // TODO: can we not use $repeater? $href = array('location.href=\'', $this->onclick, '\';'); foreach ($bridge->tbody() as $tr) { foreach ($tr as $td) { if (strpos($td->class, 'linked') === false) { $td->onclick = $href; } else { $td->onclick = 'event.cancelBubble=true;'; } } } $bridge->tbody()->onclick = '// Dummy for CSS'; } }
Place to set the data to display @param \MUtil_Model_Bridge_VerticalTableBridge $bridge @return void
entailment
public function calcultateName($value, $isNew = false, $name = null, array $context = array()) { if (isset($context['gaf_filter_text1']) && $context['gaf_filter_text1']) { return sprintf($this->_('Episode subject contains %s'), $context['gaf_filter_text1']); } else { return $this->_('Missing episode subject filter'); } }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return string
entailment
public function addElement(\Zend_Form_Element $element) { $decorators = $element->getDecorators(); $decorator = array_shift($decorators); $element->setDecorators(array($decorator, array('Description', array('class'=>'description')), 'Errors', array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')), array('Label'), array(array('labelCell' => 'HtmlTag'), array('tag' => 'td', 'class'=>'label')), array(array('row' => 'HtmlTag'), array('tag' => 'tr', 'class' => $this->_alternate)) )); return parent::addElement($element); }
Add element to stack @param \Zend_Form_Element $element @return \Zend_Form_DisplayGroup
entailment
public function loadDefaultDecorators() { if ($this->loadDefaultDecoratorsIsDisabled()) { return $this; } $decorators = $this->getDecorators(); if (empty($decorators)) { $this->addDecorator('FormElements') ->addDecorator(array('table' => 'HtmlTag'), array('tag' => 'table', 'class'=>'formTable')) ->addDecorator(array('tab' => 'HtmlTag'), array('tag' => 'div', 'class' => 'displayGroup')) ->addDecorator('TabPane', array('jQueryParams' => array('containerId' => 'mainForm', 'title' => $this->getAttrib('title')))); } return $this; }
Load default decorators @return void
entailment
protected function _addJoinTables() { $this->addTable('gems__respondents', array('gap_id_user' => 'grs_id_user')); if ($this->has('gap_id_organization')) { $this->addTable( 'gems__organizations', array('gap_id_organization' => 'gor_id_organization'), 'gor', false ); } if ($this->has('gap_id_attended_by')) { $this->addLeftTable( 'gems__agenda_staff', array('gap_id_attended_by' => 'gas_id_staff'), 'gas', false ); } /* if ($this->has('gap_id_referred_by')) { $this->addLeftTable( array('ref_staff' => 'gems__agenda_staff'), array('gap_id_referred_by' => 'ref_staff.gas_id_staff') ); } // */ if ($this->has('gap_id_activity')) { $this->addLeftTable( 'gems__agenda_activities', array('gap_id_activity' => 'gaa_id_activity'), 'gap', false ); } if ($this->has('gap_id_procedure')) { $this->addLeftTable( 'gems__agenda_procedures', array('gap_id_procedure' => 'gapr_id_procedure'), 'gapr', false ); } if ($this->has('gap_id_location')) { $this->addLeftTable( 'gems__locations', array('gap_id_location' => 'glo_id_location'), 'glo', false ); } }
Add the join tables instead of lookup tables.
entailment
public function afterRegistry() { $agenda = $this->loader->getAgenda(); if ($agenda) { $this->addColumn( "CASE WHEN gap_status IN ('" . implode("', '", $agenda->getStatusKeysInactive()) . "') THEN 'deleted' ELSE '' END", 'row_class' ); $codes = $agenda->getStatusCodesInactive(); if (isset($codes['CA'])) { $cancelCode = 'CA'; } elseif ($codes) { reset($codes); $cancelCode = key($codes); } else { $cancelCode = null; } if ($cancelCode) { $this->setDeleteValues('gap_status', $cancelCode); } } }
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() { $this->_addJoinTables(); $this->resetOrder(); $agenda = $this->loader->getAgenda(); $this->setIfExists('gap_admission_time', 'label', $this->_('Appointment'), // 'formatFunction', array($this->util->getTranslated(), 'formatDateTime'), 'dateFormat', 'dd-MM-yyyy HH:mm', 'description', $this->_('dd-mm-yyyy hh:mm')); $this->setIfExists('gap_status', 'label', $this->_('Type'), 'multiOptions', $agenda->getStatusCodes()); if ($this->currentUser->hasPrivilege('pr.episodes')) { $this->setIfExists('gap_id_episode', 'label', $this->_('Episode'), 'formatFunction', [$this, 'showEpisode']); } $this->setIfExists('gas_name', 'label', $this->_('With')); // $this->setIfExists('ref_staff.gas_name', 'label', $this->_('By')); $this->setIfExists('gaa_name', 'label', $this->_('Activities')); $this->setIfExists('gapr_name', 'label', $this->_('Procedures')); $this->setIfExists('glo_name', 'label', $this->_('Location')); $this->setIfExists('gor_name', 'label', $this->_('Organization')); $this->setIfExists('gap_subject', 'label', $this->_('Subject')); $dels = $this->loader->getAgenda()->getStatusKeysInactiveDbQuoted(); if ($dels) { $this->addColumn( new \Zend_Db_Expr("CASE WHEN gap_status IN ($dels) THEN 'deleted' ELSE '' END "), 'row_class' ); } $this->refreshGroupSettings(); return $this; }
Set those settings needed for the browse display @return \Gems_Model_AppointmentModel
entailment
public function applyDetailSettings($setMulti = true) { $this->resetOrder(); $agenda = $this->loader->getAgenda(); $dbLookup = $this->util->getDbLookup(); $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $this->setIfExists('gap_admission_time', 'label', $this->_('Appointment'), 'dateFormat', 'dd-MM-yyyy HH:mm', 'description', $this->_('dd-mm-yyyy hh:mm')); $this->setIfExists('gap_discharge_time', 'label', $this->_('Discharge'), 'dateFormat', 'dd-MM-yyyy HH:mm', 'description', $this->_('dd-mm-yyyy hh:mm')); $this->setIfExists('gap_code', 'label', $this->_('Type'), 'multiOptions', $agenda->getTypeCodes()); $this->setIfExists('gap_status', 'label', $this->_('Status'), 'multiOptions', $agenda->getStatusCodes()); if ($this->currentUser->hasPrivilege('pr.episodes')) { $this->setIfExists('gap_id_episode', 'label', $this->_('Episode'), 'formatFunction', [$this, 'showEpisode'], 'required', false); } $this->setIfExists('gap_id_attended_by', 'label', $this->_('With'), 'multiOptions', $empty + $agenda->getHealthcareStaff()); $this->setIfExists('gap_id_referred_by', 'label', $this->_('Referrer'), 'multiOptions', $empty + $agenda->getHealthcareStaff()); $this->setIfExists('gap_id_activity', 'label', $this->_('Activities')); $this->setIfExists('gap_id_procedure', 'label', $this->_('Procedures')); $this->setIfExists('gap_id_location', 'label', $this->_('Location')); $this->setIfExists('gap_id_organization', 'label', $this->_('Organization'), 'elementClass', 'Exhibitor', 'multiOptions', $empty + $dbLookup->getOrganizations()); $this->setIfExists('gap_subject', 'label', $this->_('Subject')); $this->setIfExists('gap_comment', 'label', $this->_('Comment')); if ($setMulti) { $this->setIfExists('gap_id_activity', 'multiOptions', $empty + $agenda->getActivities()); $this->setIfExists('gap_id_procedure', 'multiOptions', $empty + $agenda->getProcedures()); $this->setIfExists('gap_id_location', 'multiOptions', $empty + $agenda->getLocations()); } $this->refreshGroupSettings(); return $this; }
Set those settings needed for the detailed display @param boolean $setMulti When false organization dependent multi options are nor filled. @return \Gems_Model_AppointmentModel
entailment
public function applyEditSettings($orgId = null) { $this->applyDetailSettings(false); $agenda = $this->loader->getAgenda(); $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $this->setIfExists('gap_id_organization', 'default', $orgId ?: $this->currentOrganization->getId()); $this->setIfExists('gap_admission_time', 'elementClass', 'Date'); $this->setIfExists('gap_discharge_time', 'elementClass', 'Date'); $this->setIfExists('gap_status', 'required', true); $this->setIfExists('gap_comment', 'elementClass', 'Textarea', 'rows', 5); $this->setIfExists('gap_id_activity', 'multiOptions', $empty + $agenda->getActivities($orgId)); $this->setIfExists('gap_id_procedure', 'multiOptions', $empty + $agenda->getProcedures($orgId)); $this->setIfExists('gap_id_location', 'multiOptions', $empty + $agenda->getLocations($orgId)); if ($this->currentUser->hasPrivilege('pr.episodes')) { $this->setIfExists('gap_id_episode', 'multiOptions', $empty); $this->addDependency('AppointmentCareEpisodeDependency'); } return $this; }
Set those values needed for editing @param int $orgId The id of the current organization @return \Gems_Model_AppointmentModel
entailment
public function save(array $newValues, array $filter = null) { // When appointment id is not set, then check for existing instances of // this appointment using the source information if ((!isset($newValues['gap_id_appointment'])) && isset($newValues['gap_id_in_source'], $newValues['gap_id_organization'], $newValues['gap_source'])) { $sql = "SELECT gap_id_appointment FROM gems__appointments WHERE gap_id_in_source = ? AND gap_id_organization = ? AND gap_source = ?"; $id = $this->db->fetchOne( $sql, array($newValues['gap_id_in_source'], $newValues['gap_id_organization'], $newValues['gap_source']) ); if ($id) { $newValues['gap_id_appointment'] = $id; } } $oldChanged = $this->getChanged(); $returnValues = parent::save($newValues, $filter); if ($this->getChanged() && ($this->getChanged() !== $oldChanged)) { if ($this->isAutoTrackUpdate()) { $appointment = $this->loader->getAgenda()->getAppointment($returnValues); $this->_changedTokenCount += $appointment->updateTracks(); } } // \MUtil_Echo::track($this->_changedTokenCount); return $returnValues; }
Save a single model item. @param array $newValues The values to store for a single model item. @param array $filter If the filter contains old key values these are used to decide on update versus insert. @return array The values as they are after saving (they may change).
entailment
public function showEpisode($episodeId) { if (! $episodeId) { return null; } $episode = $this->loader->getAgenda()->getEpisodeOfCare($episodeId); if (! $episode->exists) { return $episodeId; } $episodeItem = $this->menu->findAllowedController('care-episode', 'show'); if ($episodeItem) { $href = $episodeItem->toHRefAttribute(['gec_episode_of_care_id' => $episodeId]); } else { $href = false; } if (! $href) { return $episode->getDisplayString(); } $onclick = new \MUtil_Html_OnClickArrayAttribute(); $onclick->addCancelBubble(true); return \MUtil_Html::create('a', $href, $episode->getDisplayString(), $onclick); }
Display the episode @param int $episodeId @return string
entailment
public function matchEpisode(EpisodeOfCare $episode) { if (! $this->_data['gaf_filter_text1']) { return ! $episode->getSubject(); } $regex = '/' . str_replace(array('%', '_'), array('.*', '.{1,1}'),$this->_data['gaf_filter_text1']) . '/i'; return (boolean) preg_match($regex, $episode->getSubject()); }
Check a filter for a match @param \Gems\Agenda\EpisodeOfCare $episode @return boolean
entailment
public function execute($lineNr = null, $fieldData = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (isset($fieldData['gtf_id_order']) && $fieldData['gtf_id_order']) { $import['fieldOrder'][$fieldData['gtf_id_order']] = false; if ($batch->hasVariable('trackEngine') && isset($fieldData['gtf_field_type']) && $fieldData['gtf_field_type']) { $trackEngine = $batch->getVariable('trackEngine'); if ($trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) { $fieldDef = $trackEngine->getFieldsDefinition(); $field = $fieldDef->getFieldByOrder($fieldData['gtf_id_order']); if ($field instanceof FieldInterface) { if ($field->getFieldType() != $fieldData['gtf_field_type']) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Conflicting field types "%s" and "%s" for field orders %d specified on line %d.'), $field->getFieldType(), $fieldData['gtf_field_type'], $fieldData['gtf_id_order'], $lineNr )); } } } } } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No gtf_id_order specified for field at line %d.'), $lineNr )); } if (isset($fieldData['gtf_field_type']) && $fieldData['gtf_field_type']) { $model = $this->loader->getTracker()->createTrackClass('Model\\FieldMaintenanceModel'); $fields = $model->getFieldTypes(); if (! isset($fields[$fieldData['gtf_field_type']])) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown field type "%s" specified on line %d.'), $fieldData['gtf_field_type'], $lineNr )); } } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No field type specified 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 $trackData Nested array of trackdata
entailment
public function calculateFieldInfo($currentValue, array $fieldData) { if (! $currentValue) { return $currentValue; } // Display nice $sql = $this->_sql . "WHERE grr_id = ?"; $row = $this->db->fetchRow($sql, $currentValue); if ($row && isset($row['name'])) { return $row['name']; } return $currentValue; }
Calculation the field info display for this type @param array $currentValue The current value @param array $fieldData The other values loaded so far @return mixed the new value
entailment
public function getDataModelDependyChanges(array $context, $new) { if ($this->isReadOnly()) { return null; } $sql = $this->_sql ."WHERE grr_id_respondent = ? ORDER BY grr_type"; $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $output['multiOptions'] = $empty + $this->db->fetchPairs($sql, $context['gr2t_id_user']); return $output; }
Returns the changes to the model for this field that must be made in an array consisting of <code> array(setting1 => $value1, setting2 => $value2, ...), </code> By using [] array notation in the setting array key 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 (setting => value)
entailment
public function showRelation($value) { // Display nicer $display = $this->calculateFieldInfo($value, array()); if ($value == $display) { $display = $this->_('-'); } return $display; }
Display a relation as text @param value $value @return string
entailment
public function autofilterAction($resetMvc = true) { $htmlOrig = $this->html; $div = $this->html->div(array('id' => 'autofilter_target', 'class' => 'table-container')); // Already done when this value is false if ($resetMvc) { $this->autofilterParameters = $this->autofilterParameters + $this->_autofilterExtraParameters; } $this->html = $div; parent::autofilterAction($resetMvc); $this->html = $htmlOrig; }
The automatically filtered result @param $resetMvc When true only the filtered resulsts
entailment
public function excelAction() { // Make sure we have all the parameters used by the model $this->autofilterParameters = $this->autofilterParameters + $this->_autofilterExtraParameters; $model = $this->getExportModel(); // Set any defaults. if (isset($this->autofilterParameters['sortParamAsc'])) { $model->setSortParamAsc($this->autofilterParameters['sortParamAsc']); } if (isset($this->autofilterParameters['sortParamDesc'])) { $model->setSortParamDesc($this->autofilterParameters['sortParamDesc']); } $model->applyParameters($this->getSearchFilter(false), true); // Add any defaults. if (isset($this->autofilterParameters['extraFilter'])) { $model->addFilter($this->autofilterParameters['extraFilter']); } if (isset($this->autofilterParameters['extraSort'])) { $model->addSort($this->autofilterParameters['extraSort']); } // $this->addExcelColumns($model); // Hook to modify the model // Use $this->formatExcelData to switch between formatted and unformatted data $excelData = new \Gems_FormattedData($this->getExcelData($model->load(), $model), $model, $this->formatExcelData); $this->view->result = $excelData; $this->view->filename = $this->getRequest()->getControllerName() . '.xls'; $this->view->setScriptPath(GEMS_LIBRARY_DIR . '/views/scripts' ); $this->render('excel', null, true); }
Outputs the model to excel, applying all filters and searches needed When you want to change the output, there are two places to check: 1. $this->addExcelColumns($model), where the model can be changed to have labels for columns you need exported 2. $this->getExcelData($data, $model) where the supplied data and model are merged to get output (by default all fields from the model that have a label)
entailment
public function exportAction() { $step = $this->request->getParam('step'); $post = $this->request->getPost(); $this->autofilterParameters = $this->autofilterParameters + $this->_autofilterExtraParameters; $model = $this->getExportModel(); if (isset($this->autofilterParameters['sortParamAsc'])) { $model->setSortParamAsc($this->autofilterParameters['sortParamAsc']); } if (isset($this->autofilterParameters['sortParamDesc'])) { $model->setSortParamDesc($this->autofilterParameters['sortParamDesc']); } $model->applyParameters($this->getSearchFilter(false), true); if (!empty($post)) { $this->accesslog->logChange($this->request, null, $post + $model->getFilter()); } // Add any defaults. if (isset($this->autofilterParameters['extraFilter'])) { $model->addFilter($this->autofilterParameters['extraFilter']); } if (isset($this->autofilterParameters['extraSort'])) { $model->addSort($this->autofilterParameters['extraSort']); } if ((!$step) || ($post && $step == 'form')) { $this->addSnippet($this->exportFormSnippets); $batch = $this->loader->getTaskRunnerBatch('export_data'); $batch->reset(); } elseif ($step == 'batch') { $batch = $this->loader->getTaskRunnerBatch('export_data'); $batch->setVariable('model', $model); if (!$batch->count()) { $batch->minimalStepDurationMs = 2000; $batch->finishUrl = $this->view->url(array('step' => 'download')); $batch->setSessionVariable('files', array()); if (! isset($post['type'])) { // Export type is needed, use most basic type $post['type'] = 'CsvExport'; } $batch->addTask('Export_ExportCommand', $post['type'], 'addExport', $post); $batch->addTask('addTask', 'Export_ExportCommand', $post['type'], 'finalizeFiles'); $export = $this->loader->getExport()->getExport($post['type']); if ($snippet = $export->getHelpSnippet()) { $this->addSnippet($snippet); } $batch->autoStart = true; } if (MUtil_Console::isConsole()) { // This is for unit tests, if we want to be able to really export from // cli we need to place the exported file somewhere. // This is out of scope for now. $batch->runContinuous(); } elseif ($batch->run($this->request)) { exit; } else { $controller = $this; if ($batch->isFinished()) { /*\MUtil_Echo::track('finished'); $file = $batch->getSessionVariable('file'); if ((!empty($file)) && isset($file['file']) && file_exists($file['file'])) { // Forward to download action $this->_session->exportFile = $file; }*/ } 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') ); } } } elseif ($step == 'download') { $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $batch = $this->loader->getTaskRunnerBatch('export_data'); $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; } }
Export model data
entailment
protected function firstAllowedMenuItem($action, $action2 = null) { $actions = \MUtil_Ra::args(func_get_args()); $controller = $this->_getParam('controller'); foreach ($actions as $action) { $menuItem = $this->menu->find(array('controller' => $controller, 'action' => $action, 'allowed' => true)); if ($menuItem) { return $menuItem; } } }
Finds the first item with one of the actions specified as parameter and using the current controller @param string $action @param string $action2 @return \Gems_Menu_SubMenuItem
entailment
protected function getExcelData($data, \MUtil_Model_ModelAbstract $model) { $headings = array(); $emptyMsg = $this->_('No data found.'); foreach ($model->getItemsOrdered() as $name) { if ($label = $model->get($name, 'label')) { $headings[$name] = (string) $label; } } $results = array(); $results[] = $headings; if ($headings) { if ($data) { foreach ($data as $row) { foreach ($headings as $key => $value) { $result[$key] = isset($row[$key]) ? $row[$key] : null; } $results[] = $result; } return $results; } else { foreach ($headings as $key => $value) { $result[$key] = $emptyMsg; } $results[] = $result; return $results; } } else { return array($emptyMsg); } }
Returns an array with all columns from the model that have a label @param array $data @param \MUtil_Model_ModelAbstract $model @return array
entailment
protected function getExportModel() { $model = $this->getModel(); $noExportColumns = $model->getColNames('noExport'); foreach($noExportColumns as $colName) { $model->remove($colName, 'label'); } return $model; }
Get the model for export and have the option to change it before using for export @return
entailment
public function getImporter() { return $this->loader->getImportLoader()->getImporter( $this->getRequest()->getControllerName(), $this->getModel() ); }
Get an Importer object for this actions @return \MUtil_Model_Importer
entailment
public function getMessenger() { if (! $this->messenger) { $this->setMessenger($this->loader->getMessenger()); } return $this->messenger; }
Returns a session based message store for adding messages to. @return \Zend_Controller_Action_Helper_FlashMessenger
entailment
public function getTitle($separator = null) { if ($title_set = parent::getTitle($separator)) { return $title_set; } $title = array(); foreach($this->menu->getActivePath($this->getRequest()) as $menuItem) { $title[] = $menuItem->get('label'); } if ($id = $this->getInstanceId()) { $title[] = $id; } return implode($separator, $title); }
Returns the current html/head/title for this page. If the title is an array the seperator concatenates the parts. @param string $separator @return string
entailment
public function indexAction() { $this->autofilterParameters = $this->autofilterParameters + $this->_autofilterExtraParameters; if (! isset($this->indexParameters['contentTitle'])) { $this->indexParameters['contentTitle'] = $this->getIndexTitle(); } return parent::indexAction(); }
Action for showing a browse page
entailment
public function initHtml($reset = false) { if (! $this->html) { \Gems_Html::init(); } parent::initHtml($reset); }
Intializes the html component. @param boolean $reset Throws away any existing html output when true @return void
entailment
public function setMessenger(\Zend_Controller_Action_Helper_FlashMessenger $messenger) { $this->messenger = $messenger; $this->view->messenger = $messenger; return $this; }
Set the session based message store. @param \Zend_Controller_Action_Helper_FlashMessenger $messenger @return \MUtil_Controller_Action
entailment
public function showAction() { if (! isset($this->showParameters['contentTitle'])) { $this->showParameters['contentTitle'] = $this->getShowTitle(); } parent::showAction(); }
Action for showing an item page with title
entailment
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model) { $this->mailElements->setForm($bridge->getForm()); $this->initItems(); $this->addItems($bridge, 'gct_name'); $this->addItems($bridge, 'gct_id_template', 'gct_target'); $this->addItems($bridge, 'gct_code'); $bridge->getForm()->getElement('gct_target')->setAttrib('onchange', 'this.form.submit()'); $defaultTab = $this->project->getLocaleDefault(); $this->mailElements->addFormTabs($bridge, 'gctt', 'active', $defaultTab, 'tabcolumn', 'gctt_lang', 'selectedTabElement', 'send_language'); $config = array( 'extraPlugins' => 'bbcode,availablefields', 'toolbar' => array( array('Source','-','Undo','Redo'), array('Find','Replace','-','SelectAll','RemoveFormat'), array('Link', 'Unlink', 'Image', 'SpecialChar'), '/', array('Bold', 'Italic','Underline'), array('NumberedList','BulletedList','-','Blockquote'), array('Maximize'), array('availablefields') ) ); $mailfields = $this->mailer->getMailFields(); foreach($mailfields as $field => $value) { $mailfields[$field] = utf8_encode($value); } $config['availablefields'] = $mailfields; $config['availablefieldsLabel'] = $this->_('Fields'); $this->view->inlineScript()->prependScript(" CKEditorConfig = ".\Zend_Json::encode($config)."; "); $bridge->addFakeSubmit('preview', array('label' => $this->_('Preview'))); $bridge->addElement($this->mailElements->createEmailElement('to', $this->_('To (test)'), false)); $bridge->addElement($this->mailElements->createEmailElement('from', $this->_('From'), false)); //$bridge->addRadio('send_language', array('label' => $this->_('Test language'), 'multiOptions' => )) $bridge->addHidden('send_language'); $bridge->addFakeSubmit('sendtest', array('label' => $this->_('Send (test)'))); $bridge->addElement($this->getSaveButton($bridge->getForm())); $bridge->addElement($this->mailElements->createPreviewHtmlElement($this->_('Preview HTML'))); $bridge->addElement($this->mailElements->createPreviewTextElement($this->_('Preview Text'))); $bridge->addHtml('available_fields', array('label' => $this->_('Available fields'))); }
Adds elements from the model to the bridge that creates the form. @param \MUtil_Model_Bridge_FormBridgeInterface $bridge @param \MUtil_Model_ModelAbstract $model
entailment
public function afterRegistry() { $this->mailElements = $this->loader->getMailLoader()->getMailElements(); $this->mailTargets = $this->loader->getMailLoader()->getMailTargets(); parent::afterRegistry(); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
protected function getPreview($templateArray) { $multi = false; if (count($templateArray) > 1) { $multi = true; $allLanguages = $this->util->getLocalized()->getLanguages(); } $htmlView = \MUtil_Html::create()->div(); $textView = \MUtil_Html::create()->div(); foreach($templateArray as $template) { $content = ''; if ($template['gctt_subject'] || $template['gctt_body']) { if ($multi) { $htmlView->h3()->append($allLanguages[$template['gctt_lang']]); $textView->h3()->append($allLanguages[$template['gctt_lang']]); } $content .= '[b]'; $content .= $this->_('Subject:'); $content .= '[/b] [i]'; $content .= $this->mailer->applyFields($template['gctt_subject']); $content .= "[/i]\n\n"; $content .= $this->mailer->applyFields($template['gctt_body']); $htmlView->div(array('class' => 'mailpreview')) ->raw(\MUtil_Markup::render($content, 'Bbcode', 'Html')); $textView->pre(array('class' => 'mailpreview')) ->raw(wordwrap(\MUtil_Markup::render($content, 'Bbcode', 'Text'), 80)); } } return array('html' => $htmlView, 'text' => $textView); }
Style the template previews @param array $templateArray template data @return array html and text views
entailment
protected function loadFormData() { parent::loadFormData(); $this->loadMailer(); if (isset($this->formData['gctt'])) { $multi = false; if (count($this->formData['gctt']) > 1) { $multi = true; $allLanguages = $this->util->getLocalized()->getLanguages(); } $preview = $this->getPreview($this->formData['gctt']); $this->formData['preview_html'] = $preview['html']; $this->formData['preview_text'] = $preview['text']; } if (!isset($this->formData['to'])) { $organization = $this->mailer->getOrganization(); $this->formData['to'] = $this->formData['from'] = $this->currentUser->getEmailAddress(); if ($organization->getEmail()) { $this->formData['from'] = $organization->getEmail(); } elseif ($this->project->getSiteEmail ()) { $this->formData['from'] = $this->project->getSiteEmail(); } } $this->formData['available_fields'] = $this->mailElements->displayMailFields($this->mailer->getMailFields()); }
Load extra data not from the model into the form
entailment
protected function loadMailer() { $this->mailTarget = false; if (isset($this->formData['gct_target']) && isset($this->mailTargets[$this->formData['gct_target']])) { $this->mailTarget = $this->formData['gct_target']; } else { reset($this->mailTargets); $this->mailTarget = key($this->mailTargets); } $this->mailer = $this->loader->getMailLoader()->getMailer($this->mailTarget); }
Loads the correct mailer
entailment
protected function onFakeSubmit() { if ($this->request->isPost()) { if (! empty($this->formData['preview'])) { $this->addMessage($this->_('Preview updated')); return; } if (! empty($this->formData['sendtest'])) { $this->mailer->setTo($this->formData['to']); // Make sure at least one template is set (for single language projects) $template = reset($this->formData['gctt']); $languageId = key($this->formData['gctt']); if ($this->formData['send_language']) { foreach($this->formData['gctt'] as $languageId => $templateLanguage) { // Find the current template (for multi language projects) if ($templateLanguage['gctt_lang'] == $this->formData['send_language']) { $template = $templateLanguage; } } } // \MUtil_Echo::track($this->formData); $errors = false; if (! $template['gctt_subject']) { $this->addMessage(sprintf( $this->_('Subject required for %s part.'), strtoupper($template['gctt_lang']) )); $errors = true; } if (! $template['gctt_body']) { $this->addMessage(sprintf( $this->_('Body required for %s part.'), strtoupper($template['gctt_lang'])) ); $errors = true; } if ($errors) { return; } $this->mailer->setFrom($this->formData['from']); $this->mailer->setSubject($template['gctt_subject']); $this->mailer->setBody($template['gctt_body'], 'Bbcode'); $this->mailer->setTemplateId($this->formData['gct_id_template']); $this->mailer->send(); $this->addMessage(sprintf($this->_('Test mail sent to %s'), $this->formData['to'])); } } }
When the form is submitted with a non 'save' button
entailment
protected function afterSave($changed) { parent::afterSave($changed); $model = $this->getModel(); if ($model instanceof \Gems_Model_AppointmentModel) { $count = $model->getChangedTokenCount(); if ($count) { $this->addMessage(sprintf($this->plural('%d token changed', '%d tokens changed', $count), $count)); } } }
Hook that allows actions when data was saved When not rerouted, the form will be populated afterwards @param int $changed The number of changed rows (0 or 1 usually, but can be more)
entailment
public function execute($row = null, $noToken = \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR, $tokenCompletion = \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR) { // \MUtil_Echo::track($row); if ($this->iterator instanceof \Iterator && !is_array($row) && is_int($row)) { $key = $row; if ($key < $this->iterator->key()) { $this->iterator->rewind(); } while ($key > $this->iterator->key()) { $this->iterator->next(); } $current = $this->iterator->current(); $row = $this->modelTranslator->translateRowValues($current, $key); if ($row) { $row = $this->modelTranslator->validateRowValues($row, $key); } $errors = $this->modelTranslator->getRowErrors($key); } if ($row) { $answers = $row; $prevAnswers = false; $token = null; $tracker = $this->loader->getTracker(); $userId = $this->loader->getCurrentUser()->getUserId(); // \Gems_Tracker::$verbose = true; $batch = $this->getBatch(); $batch->addToCounter('imported'); // Remove all "non-answer" fields unset($answers['token'], $answers['patient_id'], $answers['organization_id'], $answers['track_id'], $answers['survey_id'], $answers['completion_date'], $answers['gto_id_token']); if (isset($row['survey_id'])) { $model = $this->targetModel; foreach ($answers as $key => &$value) { if ($value instanceof \Zend_Date) { $value = $value->toString($model->getWithDefault($key, 'storageFormat', 'yyyy-MM-dd HH:mm:ss')); } } } if (isset($row['token']) && $row['token']) { $token = $tracker->getToken($row['token']); if ($token->exists && $token->isCompleted() && $token->getReceptionCode()->isSuccess()) { $prevAnswers = true; } } if (! ($token && $token->exists)) { if (! (isset($row['track_id']) && $row['track_id'])) { } // create token? } if ($answers) { if ($prevAnswers) { if (\Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_OVERWRITE == $tokenCompletion) { $code = $this->util->getReceptionCode('redo'); $oldComment = ""; if ($token->getComment()) { $oldComment .= "\n\n"; $oldComment .= $this->_('Previous comments:'); $oldComment .= "\n"; $oldComment .= $token->getComment(); } $newComment = sprintf($this->_('Token %s overwritten by import.'), $token->getTokenId()); $replacementTokenId = $token->createReplacement($newComment . $oldComment, $userId); $count = $batch->addToCounter('overwritten', 1); $batch->setMessage('overwritten', sprintf( $this->plural('%d token overwrote an existing token.', '%d tokens overwrote existing tokens.', $count), $count)); $oldToken = $token; $token = $tracker->getToken($replacementTokenId); // Make sure the Next token is set right $oldToken->setNextToken($token); $oldToken->setReceptionCode( $code, sprintf($this->_('Token %s overwritten by import.'), $token->getTokenId()) . $oldComment, $userId ); } else { $oldComment = ""; if ($token->getComment()) { $oldComment .= "\n\n"; $oldComment .= $this->_('Previous comments:'); $oldComment .= "\n"; $oldComment .= $token->getComment(); } $newComment = sprintf($this->_('More answers for token %s by import.'), $token->getTokenId()); $replacementTokenId = $token->createReplacement($newComment . $oldComment, $userId); $count = $batch->addToCounter('addedAnswers', 1); $batch->setMessage('addedAnswers', sprintf( $this->plural('%d token was imported as a new extra token.', '%d tokens were imported as a new extra token.', $count), $count)); $oldToken = $token; $token = $tracker->getToken($replacementTokenId); // Make sure the Next token is set right $oldToken->setNextToken($token); $oldToken->setReceptionCode( $oldToken->getReceptionCode(), sprintf($this->_('Additional answers in imported token %s.'), $token->getTokenId()) . $oldComment, $userId ); } } // There are still answers left to save // Make sure the token is known $token->getUrl($this->locale->getLanguage(), $userId); $token->setRawAnswers($answers); if (isset($row['completion_date']) && $row['completion_date']) { $token->setCompletionTime($row['completion_date'], $userId); } elseif (! $token->isCompleted()) { $token->setCompletionTime(new \MUtil_Date(), $userId); } $token->getRespondentTrack()->checkTrackTokens($userId, $token); $count = $batch->addToCounter('changed', 1); $batch->setMessage('changed', sprintf( $this->plural('%d token imported.', '%d tokens imported.', $count), $count)); } } }
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 $row Row to save
entailment
protected function _getArrayRendered() { $results = parent::_getArrayRendered(); if (isset($results[\MUtil_Model::REQUEST_ID1], $results[\MUtil_Model::REQUEST_ID2]) && ($results[\MUtil_Model::REQUEST_ID2] == $this->_hiddenOrgId)) { $results[\MUtil_Model::REQUEST_ID] = $results[\MUtil_Model::REQUEST_ID1]; unset($results[\MUtil_Model::REQUEST_ID1], $results[\MUtil_Model::REQUEST_ID2]); } return $results; }
Returns the rendered values of th earray elements @return array
entailment
public function formatValues($value) { $options = $this->getOptions(); if (is_array($value)) { if ($options) { foreach ($value as &$val) { if (isset($options[$val])) { $val = $options[$val]; } } } return implode($this->_('; '), $value); } if (isset($options[$value])) { return $options[$value]; } return $value; }
This formatFunction is needed because the options are not set before the concatenated row @param string $value @return string
entailment
public function getChanges(array $context, $new) { $options = $this->getOptions($context['gtf_id_track']); if ($options) { // formatFunction is needed because the options are not set before the concatenated row return array( 'htmlCalc' => array( 'label' => ' ', 'elementClass' => 'Exhibitor', ), 'gtf_calculate_using' => array( 'label' => $this->_('Calculate from'), 'description' => $this->_('Automatically calculate this field using other fields'), 'elementClass' => 'MultiCheckbox', 'formatFunction' => array($this, 'formatValues'), 'multiOptions' => $this->getOptions($context['gtf_id_track']), ), ); } }
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 getOptions($trackId = null) { if (null === $trackId) { $trackId = $this->_trackId; } $appFields = $this->db->fetchPairs(" SELECT gtap_id_app_field, gtap_field_name FROM gems__track_appointments WHERE gtap_id_track = ? ORDER BY gtap_id_order", $trackId); $options = array(); if ($appFields) { foreach ($appFields as $id => $label) { $key = FieldsDefinition::makeKey(FieldMaintenanceModel::APPOINTMENTS_NAME, $id); $options[$key] = $label; } } return $options; }
Get the calculate from options @param int $trackId @return array
entailment
protected function loadFields() { $forResp = $this->_('for respondents'); $forStaff = $this->_('for staff'); $this->addField('tokens') ->setLabel($this->_('Activated surveys')) ->setToCount("gto_id_token"); $tUtil = $this->util->getTokenData(); foreach ($this->statiUsed as $key) { $this->addField('stat_' . $key) ->setLabel([$tUtil->getStatusIcon($key), ' ', $tUtil->getStatusDescription($key)]) ->setToSumWhen($tUtil->getStatusExpressionFor($key)); } }
Tells the models which fields to expect.
entailment
protected function processFilter(\Zend_Controller_Request_Abstract $request, array $filter) { // \MUtil_Echo::r($filter, __CLASS__ . '->' . __FUNCTION__); $mainFilter = isset($filter['main_filter']) ? $filter['main_filter'] : null; unset($filter['main_filter']); $forGroup = isset($filter['forgroup']) ? $filter['forgroup'] : null; unset($filter['forgroup']); if ($forGroup) { $filter[] = $this->db->quoteinto('(ggp_name = ? AND gto_id_relationfield IS NULL) or gtf_field_name = ?', $forGroup); } $output = parent::processFilter($request, $filter); if ($mainFilter) { $output['main_filter'] = $mainFilter; } return $output; }
Processing of filter, can be overriden. @param \Zend_Controller_Request_Abstract $request @param array $filter @return array
entailment
protected function processSelect(\Zend_Db_Select $select) { // $select->joinLeft('gems__rounds', 'gto_id_round = gro_id_round', array()); // $select->join('gems__tracks', 'gto_id_track = gtr_id_track', array()); $select->join('gems__surveys', 'gto_id_survey = gsu_id_survey', array()); $select->join('gems__groups', 'gsu_id_primary_group = ggp_id_group', array()); $select->join('gems__respondents', 'gto_id_respondent = grs_id_user', array()); $select->join('gems__respondent2org', '(gto_id_organization = gr2o_id_organization AND gto_id_respondent = gr2o_id_user)', array()); $select->join('gems__respondent2track','gto_id_respondent_track = gr2t_id_respondent_track', array()); $select->join('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array()); $select->joinLeft('gems__respondent_relations', '(gto_id_relation = grr_id AND gto_id_respondent = grr_id_respondent)', array()); // Add relation $select->joinLeft('gems__track_fields', '(gto_id_relationfield = gtf_id_field AND gtf_field_type = "relation")', array()); // Add relation fields }
Stub function to allow extension of standard one table select. @param \Zend_Db_Select $select
entailment
public function calcultateName($value, $isNew = false, $name = null, array $context = array()) { $filter[] = $context['gaf_filter_text1']; $filter[] = $context['gaf_filter_text2']; $filter[] = $context['gaf_filter_text3']; $filter = array_filter($filter); if ($filter) { if (1 == count($filter)) { return sprintf( $this->_('Episode diagnosis contains %s after key: %s'), $context['gaf_filter_text4'], reset($filter) ); } else { return sprintf( $this->_('Episode diagnosis contains %s after keys: %s'), $context['gaf_filter_text4'], implode(', ', $filter) ); } } else { return sprintf($this->_('Diagnosis data contains %s'), $context['gaf_filter_text4']); } }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return string
entailment
public function send(Message $mail): void { // Trace sent mails $this->mails[] = $mail; // Delegate to original mailer $this->mailer->send($mail); }
Sends email
entailment
protected function createModel() { $model = $this->token->getModel(); $model->set('gto_reception_code', 'label', $model->get('grc_description', 'label'), 'required', true); return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function getReceptionCodes() { $rcLib = $this->util->getReceptionCodeLibrary(); if ($this->unDelete) { return $rcLib->getTokenRestoreCodes(); } if ($this->token->isCompleted()) { return $rcLib->getCompletedTokenDeletionCodes(); } return $rcLib->getUnansweredTokenDeletionCodes(); }
Called after loadFormData() and isUndeleting() but before the form is created @return array
entailment
public function setReceptionCode($newCode, $userId) { // Get the code object $code = $this->util->getReceptionCode($newCode); // Use the token function as that cascades the consent code $changed = $this->token->setReceptionCode($code, $this->formData['gto_comment'], $userId); if ($code->isSuccess()) { $this->addMessage(sprintf($this->_('Token %s restored.'), $this->token->getTokenId())); } else { $this->addMessage(sprintf($this->_('Token %s deleted.'), $this->token->getTokenId())); if ($code->hasRedoCode()) { $newComment = sprintf($this->_('Redo of token %s.'), $this->token->getTokenId()); if ($this->formData['gto_comment']) { $newComment .= "\n\n"; $newComment .= $this->_('Old comment:'); $newComment .= "\n"; $newComment .= $this->formData['gto_comment']; } $this->_replacementTokenId = $this->token->createReplacement($newComment, $userId); // Create a link for the old token $oldToken = strtoupper($this->token->getTokenId()); $menuItem = $this->menu->findAllowedController('track', 'show'); if ($menuItem) { $paramSource['gto_id_token'] = $this->token->getTokenId(); $paramSource[\Gems_Model::ID_TYPE] = 'token'; $href = $menuItem->toHRefAttribute($paramSource); if ($href) { // \MUtil_Echo::track($oldToken); $link = \MUtil_Html::create('a', $href, $oldToken); $oldToken = $link->setView($this->view); } } // Tell what the user what happened $this->addMessage(new \MUtil_Html_Raw(sprintf( $this->_('Created this token %s as replacement for token %s.'), strtoupper($this->_replacementTokenId), $oldToken ))); // Lookup token $newToken = $this->loader->getTracker()->getToken($this->_replacementTokenId); // Make sure the Next token is set right $this->token->setNextToken($newToken); // Copy answers when requested. /* Copy moved to \Gems_Track_Token->getUrl() if ($code->hasRedoCopyCode()) { $newToken->setRawAnswers($this->token->getRawAnswers()); } */ } } $respTrack = $this->token->getRespondentTrack(); if ($nextToken = $this->token->getNextToken()) { if ($recalc = $respTrack->checkTrackTokens($userId, $nextToken)) { $this->addMessage(sprintf($this->plural( '%d token changed by recalculation.', '%d tokens changed by recalculation.', $recalc ), $recalc)); } } return $changed; }
Hook performing actual save @param string $newCode @param int $userId @return $changed
entailment
protected function setAfterSaveRoute() { // Default is just go to the index if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) { $tokenId = $this->_replacementTokenId ? $this->_replacementTokenId : $this->token->getTokenId(); $this->afterSaveRouteUrl = array( $this->request->getActionKey() => $this->routeAction, \MUtil_Model::REQUEST_ID => $tokenId, ); } return $this; }
Set what to do when the form is 'finished'. @return DeleteTrackTokenSnippet (continuation pattern)
entailment
public function getSessionData(bool $checkExists = true) : ?array { if ($checkExists) { $manager = Container::getDefaultManager(); if (!$manager->sessionExists()) { return null; } } $container = new Container(); $arraysession = $container->getManager()->getStorage()->toArray(); return $this->collectSessionData($arraysession); }
{@inheritdoc}
entailment
private function collectSessionData(array $arraysession) : array { $data = []; foreach ($arraysession as $key => $row) { if ($row instanceof ArrayObject) { $iterator = $row->getIterator(); while ($iterator->valid()) { $data[$key][$iterator->key()] = $iterator->current(); $iterator->next(); } } } return $data; }
{@inheritdoc}
entailment
public function sessionSetting(string $containerName, string $keysession, string $value = null, array $options = []) : bool { $container = new Container($containerName); $new = $options['new'] ?? false; if ($new && $value) { return $this->addSession($container, $keysession, $value); } $set = $options['set'] ?? false; return $this->setUnset($container, $keysession, $value, $set); }
{@inheritdoc}
entailment
private function addSession(Container $container, string $keysession, string $value) : bool { if ($container->offsetExists($keysession)) { return false; } $container->offsetSet($keysession, $value); return true; }
Add new session data.
entailment
private function setUnset(Container $container, string $keysession, ?string $value, bool $set = false) : bool { if (!$container->offsetExists($keysession)) { return false; } if ($set && $value) { $container->offsetSet($keysession, $value); return true; } $container->offsetUnset($keysession); return true; }
Set/Unset session data.
entailment
public function clearSession(string $byContainer = null) : void { (new Container())->getManager() ->getStorage() ->clear($byContainer); }
{@inheritdoc}
entailment
public function calcultateName($value, $isNew = false, $name = null, array $context = array()) { $output = array(); if (isset($context['gaf_filter_text1']) && $context['gaf_filter_text1']) { $output[] = sprintf($this->_('Activity "%s"'), $context['gaf_filter_text1']); } if (isset($context['gaf_filter_text2']) && $context['gaf_filter_text2']) { $output[] = sprintf($this->_('procedure "%s"'), $context['gaf_filter_text2']); } if (isset($context['gaf_filter_text3']) && $context['gaf_filter_text3']) { $output[] = sprintf($this->_('but not "%s"'), $context['gaf_filter_text3']); } if ($output) { return ucfirst(implode($this->_(', '), $output)); } else { return $this->_('empty filter'); } }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return string
entailment
public function getTextSettings() { $description = sprintf($this->_( "Use the %%-sign to search for zero or more random characters and an _ for a single random character." )); return array( 'gaf_filter_text1' => array( 'label' => $this->_('Activity'), 'description' => $description, 'required' => true, ), 'gaf_filter_text2' => array( 'label' => $this->_('Procedure'), 'description' => $description, ), 'gaf_filter_text3' => array( 'label' => $this->_('But not when'), 'description' => sprintf($this->_("But skip when this text is found - use %%-sign as well.")), ), ); }
Get the settings for the gaf_filter_textN fields Fields not in this array are not shown in any way @return array gaf_filter_textN => array(modelFieldName => fieldValue)
entailment
public function isValid($conditionId, $context) { $result = false; if (isset($context['gro_id_track']) && $context['gro_id_track']) { $trackEngine = $this->tracker->getTrackEngine($context['gro_id_track']); $codes = $trackEngine->getFieldCodes(); $result = in_array($this->_data['gcon_condition_text1'], $codes); } return $result; }
Does this track have the fieldcode the condition depends on? @param type $conditionId @param type $context @return boolean
entailment
protected function createModel($detailed, $action) { $model = $this->loader->getModels()->getConditionModel(); if ($detailed) { if (('edit' == $action) || ('create' == $action)) { $model->applyEditSettings(('create' == $action)); } else { $model->applyDetailSettings(); } } else { $model->applyBrowseSettings(); } return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
protected function addScript() { $view = $this->view; \MUtil_JQuery::enableView($view); $jquery = $view->jQuery(); $jquery->enable(); //Just to make sure $handler = \ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(); $script = "$('input[type=\"submit\"]').mousedown(function(e) { e.preventDefault(); // prevents blur() to be called when clicking submit });"; $fields = array( 'jQuery' => $handler, ); $js = str_replace(array_keys($fields), $fields, $script); $jquery->addOnLoad($js); }
This script disables the onchange that is fired just before the click on the submit button fires. The onchange submits the form, changes the csrf token and then the submit button fires with the old csrf that is invalid. This could prevent a needed (fake)submit to change values, but for now it does not seem like a problem.
entailment
public function execute($trackId = null, $roundId = null) { $batch = $this->getBatch(); $select = $this->db->select(); $select->from('gems__rounds', array( 'gro_id_order', 'gro_id_relationfield', 'gro_round_description', 'gro_icon_file', 'gro_changed_event', 'gro_display_event', 'gro_valid_after_source', 'gro_valid_after_field', 'gro_valid_after_unit', 'gro_valid_after_length', 'gro_valid_for_source', 'gro_valid_for_field', 'gro_valid_for_unit', 'gro_valid_for_length', 'gro_organizations', 'gro_code', 'gro_condition' )) ->joinInner('gems__surveys', 'gems__rounds.gro_id_survey = gsu_id_survey', array( 'survey_export_code' => 'gsu_export_code', )) // gro_id_survey ->joinLeft('gems__rounds AS va', 'gems__rounds.gro_valid_after_id = va.gro_id_round', array( 'valid_after' => 'va.gro_id_order', )) // gro_valid_after_id ->joinLeft('gems__rounds AS vf', 'gems__rounds.gro_valid_for_id = vf.gro_id_round', array( 'valid_for' => 'vf.gro_id_order', )) // gro_valid_for_id ->where('gems__rounds.gro_id_round = ?', $roundId); // \MUtil_Echo::track($select->__toString(), $roundId); $data = $this->db->fetchRow($select); // \MUtil_Echo::track($data); if ($data) { $fields = $this->loader->getTracker()->getTrackEngine($trackId)->getFieldsDefinition(); $tests = array( \Gems_Tracker_Engine_StepEngineAbstract::APPOINTMENT_TABLE, \Gems_Tracker_Engine_StepEngineAbstract::RESPONDENT_TRACK_TABLE, ); if (isset($data['gro_id_relationfield']) && $data['gro_id_relationfield']) { // -1 means the respondent itself, also gro_id_relationfield stores a "bare" // field id, not one with a table prefix if ($data['gro_id_relationfield'] >= 0) { $data['gro_id_relationfield'] = $this->translateFieldCode( $fields, FieldsDefinition::makeKey(FieldMaintenanceModel::FIELDS_NAME, $data['gro_id_relationfield']) ); } } if (isset($data['gro_valid_after_source'], $data['gro_valid_after_field']) && in_array($data['gro_valid_after_source'], $tests)) { // Translate field to {order} $data['gro_valid_after_field'] = $this->translateFieldCode($fields, $data['gro_valid_after_field']); } if (isset($data['gro_valid_for_source'], $data['gro_valid_for_field']) && in_array($data['gro_valid_for_source'], $tests)) { // Translate field to {order} $data['gro_valid_for_field'] = $this->translateFieldCode($fields, $data['gro_valid_for_field']); } $count = $batch->addToCounter('rounds_exported'); if ($count == 1) { $this->exportTypeHeader('rounds'); $this->exportFieldHeaders($data); } $this->exportFieldData($data); $this->exportFlush(); $batch->setMessage('rounds_export', sprintf( $this->plural('%d round exported', '%d rounds exported', $count), $count )); } }
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 createModel() { // Replace two checkboxes with on radio button control $this->model->set('ggp_staff_members', 'elementClass', 'Hidden'); $this->model->setOnSave('ggp_staff_members', array($this, 'saveIsStaff')); $this->model->set('ggp_respondent_members', 'elementClass', 'Hidden'); $this->model->setOnSave('ggp_respondent_members', array($this, 'saveIsRespondent')); $options = array( '1' => $this->model->get('ggp_staff_members', 'label'), '2' => $this->model->get('ggp_respondent_members', 'label') ); $this->model->set('staff_respondent', 'label', $this->_('Can be assigned to'), 'elementClass', 'Radio', 'multiOptions', $options, 'order', $this->model->getOrder('ggp_staff_members') + 1); $this->model->setOnLoad('staff_respondent', array($this, 'loadStaffRespondent')); return $this->model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
protected function loadFormData() { if (! $this->formData) { parent::loadFormData(); $model = $this->getModel(); $roles = $model->get('ggp_role', 'multiOptions'); $userRoles = $this->currentUser->getAllowedRoles(); // \MUtil_Echo::track($userRoles, $roles); // Make sure we get the roles as they are labeled foreach ($roles as $role => $label) { if (! isset($userRoles[$role])) { unset($roles[$role]); } } if ($this->formData['ggp_role'] && (! isset($roles[$this->formData['ggp_role']]))) { if ($this->createData) { $this->formData['ggp_role'] = reset($roles); } else { $this->addMessage($this->_('You do not have sufficient privilege to edit this group.')); $this->afterSaveRouteUrl = array($this->request->getActionKey() => 'show'); $this->resetRoute = false; return; } } $model->set('ggp_role', 'multiOptions', $roles); $this->menu->getParameterSource()->offsetSet('ggp_role', $this->formData['ggp_role']); } }
Hook that loads the form data from $_POST or the model Or from whatever other source you specify here.
entailment
public function loadStaffRespondent($value, $isNew = false, $name = null, array $context = array(), $isPost = false) { if (! $isPost) { if (!isset($context['staff_respondent'])) { if (isset($context['ggp_staff_members']) && $context['ggp_staff_members'] == 1) { return 1; } else if (isset($context['ggp_respondent_members']) && $context['ggp_respondent_members'] == 1) { return 2; } } } return $value; }
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 saveIsRespondent($value, $isNew = false, $name = null, array $context = array()) { return (isset($context['staff_respondent']) && (2 == $context['staff_respondent'])) ? 1 : 0; }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return \Zend_Date
entailment
public function saveIsStaff($value, $isNew = false, $name = null, array $context = array()) { return (isset($context['staff_respondent']) && (1 == $context['staff_respondent'])) ? 1 : 0; }
A ModelAbstract->setOnSave() function that returns the input date as a valid date. @see \MUtil_Model_ModelAbstract @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return \Zend_Date
entailment
public function addSeparator($token) { $this->wikiContent .= $this->wikiContentArr[$this->separatorCount]; if (count($this->cell) === 0) { $this->generator->setColSpan($this->generator->getColSpan() + 1); } else { if ($this->hasStartHeader && $this->hasEndHeader) { $this->generator->setIsHeader(true); } elseif ($this->hasStartHeader) { // no header, we revert the '=' removal $words = $this->documentGenerator->getInlineGenerator('words'); $words->addRawContent('='); array_unshift($this->cell, $words); } elseif ($this->hasEndHeader) { // no header, we revert the '=' removal $words = $this->documentGenerator->getInlineGenerator('words'); $words->addRawContent('='); array_push($this->cell, $words); } foreach ($this->cell as $gen) { $this->generator->addContent($gen); } $this->row->addGenerator($this->generator); $this->generator = $this->documentGenerator->getInlineGenerator($this->generatorName); ++$this->separatorCount; $this->contents[$this->separatorCount] = ''; $this->wikiContentArr[$this->separatorCount] = ''; } $this->hasStartHeader = $this->hasEndHeader = false; $this->cell = array(); $this->currentSeparator = $token; $this->wikiContent .= $token; }
called by the inline parser, when it found a separator. @param string $token
entailment
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $this->bridge = $bridge; if ($this->useColumns && $this->columns) { parent::addBrowseTableColumns($bridge, $model); return; } 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)); } } // make sure search results are highlighted $this->applyTextMarker(); $this->addBrowseColumn1($bridge, $model); $this->addBrowseColumn2($bridge, $model); $this->addBrowseColumn3($bridge, $model); $this->addBrowseColumn4($bridge, $model); $this->addBrowseColumn5($bridge, $model); if ($this->showMenu) { $editMenuItems = $this->getEditMenuItems(); foreach ($editMenuItems as $menuItem) { $bridge->addItemLink($menuItem->toActionLinkLower($this->request, $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 createModel() { if (! $this->model instanceof \Gems_Model_RespondentModel) { $this->model = $this->loader->getModels()->createRespondentModel(); $this->model->applyBrowseSettings(); } return $this->model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function execute($respId = null, $orgId = null) { $batch = $this->getBatch(); $org = $this->loader->getOrganization($orgId); $changeEventClass = $org->getRespondentChangeEventClass(); if ($changeEventClass) { $event = $this->loader->getEvents()->loadRespondentChangedEvent($changeEventClass); if ($event) { $respondent = $this->loader->getRespondent(null, $orgId, $respId); $batch->addToCounter('respondentsChecked'); if ($respondent->getReceptionCode()->isSuccess() && $event->processChangedRespondent($respondent)) { $batch->addToCounter('respondentsChanged'); } } } $batch->setMessage( 'respCheck', sprintf( $this->_('%d respondents checked, %d respondents were changed.'), $batch->getCounter('respondentsChecked'), $batch->getCounter('respondentsChanged') )); }
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 getLabeledColumns() { if (!$this->model->hasMeta('labeledColumns')) { $orderedCols = $this->model->getItemsOrdered(); $results = array(); foreach ($orderedCols as $name) { if ($this->model->has($name, 'label')) { $results[] = $name; } } $this->model->setMeta('labeledColumns', $results); } return $this->model->getMeta('labeledColumns'); }
Returns an array of ordered columnnames that have a label @return array Array of columnnames
entailment
protected function addFile() { $exportTempDir = GEMS_ROOT_DIR . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR; if (! is_dir($exportTempDir)) { \MUtil_File::ensureDir($exportTempDir); } $tempFilename = $exportTempDir . 'export-' . md5(time() . rand()); $this->tempFilename = $tempFilename; $basename = $this->cleanupName($this->model->getName()); $filename = $basename; $i = 1; while (isset($this->files[$filename . $this->fileExtension])) { $filename = $basename . '_' . $i; $i++; } $this->filename = $filename; $this->files[$filename . $this->fileExtension] = $tempFilename . $this->fileExtension; $file = fopen($tempFilename . $this->fileExtension, 'w'); fclose($file); }
Creates a new file and adds it to the files array
entailment
public function addRows($data, $modelId, $tempFilename, $filter) { $this->data = $data; $this->modelId = $modelId; $this->model = $this->getModel(); $this->model->setFilter($filter + $this->model->getFilter()); if ($this->model) { $rows = $this->model->load(); $file = fopen($tempFilename . $this->fileExtension, 'a'); foreach ($rows as $row) { $this->addRow($row, $file); } fclose($file); } }
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
protected function cleanupName($filename) { $filename = str_replace(array('/', '\\', ':', ' '), '_', $filename); // Remove dot if it starts with one $filename = trim($filename, '.'); return \MUtil_File::cleanupName($filename); }
Clean a proposed filename up so it can be used correctly as a filename @param string $filename Proposed filename @return string filtered filename
entailment
protected function filterCsvInjection($input) { // Try to prevent csv injection $dangers = ['=', '+', '-', '@']; // Trim leading spaces for our test $trimmed = trim($input); if (strlen($trimmed)>1 && in_array($trimmed[0], $dangers)) { return "'" . $input; } else { return $input; } }
Single point for mitigating csv injection vulnerabilities https://www.owasp.org/index.php/CSV_Injection @param string $input @return string
entailment
protected function filterRow($row) { $exportRow = array(); foreach ($row as $columnName => $result) { if ($this->model->get($columnName, 'label')) { $options = $this->model->get($columnName, $this->modelFilterAttributes); foreach ($options as $optionName => $optionValue) { switch ($optionName) { case 'dateFormat': // if there is a formatFunction skip the date formatting if (array_key_exists('formatFunction', $options)) { continue; } $result = $this->filterDateFormat($result, $optionValue, $columnName); break; case 'formatFunction': $result = $this->filterFormatFunction($result, $optionValue); break; case 'itemDisplay': $result = $this->filterItemDisplay($result, $optionValue); break; case 'multiOptions': $result = $this->filterMultiOptions($result, $optionValue); break; default: break; } } if ($result instanceof \MUtil_Date) { $result = $this->filterDateFormat($result, 'yyyy-MM-dd HH:mm:ss', $columnName); } $result = $this->filterHtml($result); $exportRow[$columnName] = $result; } } return $exportRow; }
Filter the data in a row so that correct values are being used @param array $row a row in the model @return array The filtered row
entailment
public function finalizeFiles() { $this->getFiles(); if (count($this->files) === 0) { return false; } $firstName = key($this->files); $file = array(); if (count($this->files) === 1) { $firstFile = $this->files[$firstName]; $file['file'] = $firstFile; $file['headers'][] = "Content-Type: application/download"; $file['headers'][] = "Content-Disposition: attachment; filename=\"" . $firstName . "\""; } elseif (count($this->files) >= 1) { $nameArray = explode('.', $firstName); array_pop($nameArray); $filename = join('.', $nameArray) . '.zip'; $zipFile = dirname($this->files[$firstName]) . '/export-' . md5(time() . rand()) . '.zip'; $zipArchive = new \ZipArchive(); $zipArchive->open($zipFile, \ZipArchive::CREATE); foreach ($this->files as $newName => $tempName) { $zipArchive->addFile($tempName, $newName); } $zipArchive->close(); foreach ($this->files as $tempName) { if (file_exists($tempName)) { unlink($tempName); } } $file = array(); $file['file'] = $zipFile; $file['headers'][] = "Content-Type: application/download"; $file['headers'][] = "Content-Disposition: attachment; filename=\"" . $filename . "\""; } $file['headers'][] = "Expires: Mon, 26 Jul 1997 05:00:00 GMT"; // Date in the past $file['headers'][] = "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"; $file['headers'][] = "Cache-Control: must-revalidate, post-check=0, pre-check=0"; $file['headers'][] = "Pragma: cache"; // HTTP/1.0 if ($this->batch) { $this->batch->setSessionVariable('file', $file); } else { return $file; } }
Finalizes the files stored in $this->files. If it has 1 file, it will return that file, if it has more, it will return a zip containing all the files, named as the first file in the array. @return File with download headers
entailment
protected function getAnswerModel(array $filter, array $data, $sort) { $exportModelSource = $this->loader->getExportModelSource('AnswerExportModelSource'); $model = $exportModelSource->getModel($filter, $data); $noExportColumns = $model->getColNames('noExport'); foreach($noExportColumns as $colName) { $model->remove($colName, 'label'); } $model->applyParameters($filter, true); $model->addSort($sort); return $model; }
Return the answermodel for the given filter @param array $filter @param array $data @param array|string $sort @return type
entailment
protected function getFiles() { if (!$this->files) { $files = array(); if ($this->batch) { $files = $this->batch->getSessionVariable('files'); } else { $files = $this->_session->files; } if (!is_array($files)) { $files = array(); } $this->files = $files; } return $this->files; }
Returns the files array. It might be stored in the batch session or normal session. @return array Files array
entailment
public function getModel() { if ($this->batch) { $model = $this->batch->getVariable('model'); } else { $model = $this->_session->model; } if (is_array($model)) { if ($this->modelId && isset($model['surveys'][$this->modelId])) { $currentFilter = $model['filter']; $currentFilter['gto_id_survey'] = $this->modelId; $data = $model['data']; $sort = $model['sort']; $model = $this->getAnswerModel($currentFilter, $data, $sort); } else { return false; //$model = false; } } $this->model = $model; if ($this->model->getMeta('exportPreprocess') === null) { $this->preprocessModel(); $this->model->setMeta('exportPreprocess', true); } return $this->model; }
Get the model to export @return \MUtil_Model_ModelAbstract
entailment
protected function getModelCount($filter = true) { if ($this->model && $this->model instanceof \MUtil_Model_ModelAbstract) { $totalCount = $this->model->loadPaginator()->getTotalItemCount(); return $totalCount; } return 0; }
Get the number of items in a specific model, using the models paginator @param array $filter Filter for the model @return int Number of items in the model
entailment
public function createModel($detailed, $action) { // $model = new \Gems_Model_JoinModel('resptrack' , 'gems__respondent2track'); $model->addTable('gems__respondent2org', array( 'gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization' )); $model->addTable('gems__respondents', array('gr2o_id_user' => 'grs_id_user')); $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track')); $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code')); $model->addFilter(array('grc_success' => 1)); $model->addColumn( "TRIM(CONCAT(COALESCE(CONCAT(grs_last_name, ', '), '-, '), COALESCE(CONCAT(grs_first_name, ' '), ''), COALESCE(grs_surname_prefix, '')))", 'respondent_name'); $model->resetOrder(); $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr')); if (! $this->currentUser->isFieldMaskedPartial('respondent_name')) { $model->set('respondent_name', 'label', $this->_('Name')); } $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy'); $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy'); $filter = $this->getSearchFilter($action !== 'export'); if (! (isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) { $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter())); } if (! (isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) { $model->setFilter(array('1=0')); $this->autofilterParameters['onEmpty'] = $this->_('No track selected...'); return $model; } // Add the period filter - if any if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) { $model->addFilter(array($where)); } $trackId = $filter['gr2t_id_track']; $engine = $this->loader->getTracker()->getTrackEngine($trackId); $engine->addFieldsToModel($model, false); // Add masking if needed $group = $this->currentUser->getGroup(); if ($group instanceof Group) { $group->applyGroupToModel($model, false); } 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 excelAction() { $model = $this->getModel(); $model->set('gr2t_id_respondent_track', 'label', 'attribute_4', 'order', '5'); foreach ($model->getColNames('has_orig') as $name) { $model->set($name . '_orig', 'label', $model->get($name, 'label') . ' {RAW]'); } return parent::excelAction(); }
Outputs the model to excel, applying all filters and searches needed When you want to change the output, there are two places to check: 1. $this->addExcelColumns($model), where the model can be changed to have labels for columns you need exported 2. $this->getExcelData($data, $model) where the supplied data and model are merged to get output (by default all fields from the model that have a label)
entailment
protected function _translateAndSort(array $pairs) { $translations = array_map([$this->translateAdapter, '_'], $pairs); asort($translations); return $translations; }
Translate and sort while maintaining key association @param array $pairs @return array
entailment
public function getCompletedTokenDeletionCodes() { $select = $this->_getDeletionCodeSelect(); $select->where('grc_for_surveys = ?', self::APPLY_DO); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the token deletion reception code list. @return array a value => label array.
entailment
public function getRedoValues() { static $data; if (! $data) { $data = array( self::REDO_NONE => $this->_('No'), self::REDO_ONLY => $this->_('Yes (forget answers)'), self::REDO_COPY => $this->_('Yes (keep answers)')); } return $data; }
Return the field values for the redo code. <ul><li>0: do not redo</li> <li>1: redo but do not copy answers</li> <li>2: redo and copy answers</li></ul> @staticvar array $data @return array
entailment
public function getSurveyApplicationValues() { static $data; if (! $data) { $data = array( self::APPLY_NOT => $this->_('No'), self::APPLY_DO => $this->_('Yes (for individual tokens)'), self::APPLY_STOP => $this->_('Stop (for tokens in uncompleted tracks)')); } return $data; }
Return the field values for surveys. <ul><li>0: do not use</li> <li>1: use (and cascade)</li> <li>2: use for open rounds only</li></ul> @staticvar array $data @return array
entailment
public function getRespondentDeletionCodes() { $select = $this->_getDeletionCodeSelect(); $select->where('grc_for_respondents = 1'); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the respondent deletion reception code list. @return array a value => label array.
entailment
public function getRespondentRestoreCodes() { $select = $this->_getRestoreSelect(); $select->where('grc_for_respondents = 1'); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the respondent deletion reception code list. @return array a value => label array.
entailment
public function getTokenRestoreCodes() { $select = $this->_getRestoreSelect(); $select->where('grc_for_surveys = ?', self::APPLY_DO); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the token deletion reception code list. @return array a value => label array.
entailment
public function getTrackDeletionCodes() { $select = $this->_getDeletionCodeSelect(); $select->where('(grc_for_tracks = 1 OR grc_for_surveys = ?)', self::APPLY_STOP); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the track deletion reception code list. @return array a value => label array.
entailment
public function getTrackRestoreCodes() { $select = $this->_getRestoreSelect(); $select->where('(grc_for_tracks = 1 OR grc_for_surveys = ?)', self::APPLY_STOP); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the track deletion reception code list. @return array a value => label array.
entailment
public function getUnansweredTokenDeletionCodes() { $select = $this->_getDeletionCodeSelect(); $select->where('grc_for_surveys = ?', self::APPLY_DO) ->where('grc_redo_survey = ?', self::REDO_NONE); return $this->_translateAndSort($this->db->fetchPairs($select)); }
Returns the token deletion reception code list. @return array a value => label array.
entailment
public function addByController($controller, $action = 'index', $label = null) { $query['controller'] = $controller; $query['action'] = $action; if ($menuItem = $this->menu->findFirst($query)) { $this->addMenuItem($menuItem, $label); } return $this; }
Add a menu item by specifying the controller @param string $controller Controller name @param string $action Action name @param string $label Optional alternative label @return \Gems_Menu_MenuList (continuation pattern)
entailment
public function addCurrentChildren() { foreach ($this->menu->getCurrentChildren() as $menuItem) { $this->addMenuItem($menuItem); } return $this; }
Adds the children of the current menu item to this list @return \Gems_Menu_MenuList (continuation pattern)
entailment
public function addCurrentGrandParent($label = null) { $parent = $this->menu->getCurrentParent(); if ($parent && (! $parent->isTopLevel())) { $grandPa = $parent->getParent(); if ($grandPa && (! $grandPa->isTopLevel())) { $this->addMenuItem($grandPa, $label); } } return $this; }
Adds the parent of parent of the current menu item Does nothing when the parent is a top level item (has no controllor or is the \Gems_menu itself). @param string $label Optional alternative label @return \Gems_Menu_MenuList (continuation pattern)
entailment