sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function execute($trackId = null, $exportOrganizations = false) { $versions = $this->loader->getVersions(); $data = array( 'gems_version' => $versions->getGemsVersion(), 'project' => $this->project->getName(), 'project_env' => APPLICATION_ENV, 'project_url' => $this->util->getCurrentURI(), 'project_version' => $versions->getProjectVersion(), ); // Main version data $this->exportTypeHeader('version', false); $this->exportFieldHeaders($data); $this->exportFieldData($data); $this->exportFlush(); }
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 addSaveTask(\MUtil_Task_TaskBatch $importBatch, $key, array $row) { $importBatch->setTask( $this->saveTask, 'import-' . $key, $key, $this->getNoToken(), $this->getTokenCompleted() ); return $this; }
Add the current row to a (possibly separate) batch that does the importing. @param \MUtil_Task_TaskBatch $importBatch The import batch to impor this row into @param string $key The current iterator key @param array $row translated and validated row @return \MUtil_Model_ModelTranslatorAbstract (continuation pattern)
entailment
public function afterRegistry() { parent::afterRegistry(); $this->orgTranslations = $this->db->fetchPairs(' SELECT gor_provider_id, gor_id_organization FROM gems__organizations WHERE gor_provider_id IS NOT NULL ORDER BY gor_provider_id'); $this->orgTranslations = $this->orgTranslations + $this->db->fetchPairs(' SELECT gor_code, gor_id_organization FROM gems__organizations WHERE gor_code IS NOT NULL ORDER BY gor_id_organization'); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
protected function checkPatient($patientNr, $orgId) { if (! ($patientNr && $orgId)) { return false; } $select = $this->db->select(); $select->from('gems__respondent2org', array('gr2o_id_user')) ->where('gr2o_patient_nr = ?', $patientNr) ->where('gr2o_id_organization = ?', $orgId); return $this->db->fetchOne($select); }
Check should a patient be imported @param string $patientNr @param int $orgId @return boolean
entailment
public function getFieldsTranslations() { $this->_targetModel->set('completion_date', 'label', $this->_('Completion date'), 'order', 9, 'type', \MUtil_Model::TYPE_DATETIME ); $fieldList = array('completion_date' => 'completion_date'); foreach ($this->_targetModel->getCol('survey_question') as $name => $use) { if ($use) { $fieldList[$name] = $name; } } return $fieldList; }
Get information on the field translations @return array of fields sourceName => targetName @throws \MUtil_Model_ModelException
entailment
public function translateRowValues($row, $key) { $row = parent::translateRowValues($row, $key); if (! $row) { return false; } // Get the real organization from the provider_id or code if it exists if (isset($row[$this->orgIdField], $this->orgTranslations[$row[$this->orgIdField]])) { $row[$this->orgIdField] = $this->orgTranslations[$row[$this->orgIdField]]; } if ($this->_skipUnknownPatients && isset($row[$this->patientNrField], $row[$this->orgIdField])) { if (! $this->checkPatient($row[$this->patientNrField], $row[$this->orgIdField])) { return false; } } $row['track_id'] = $this->getTrackId(); $row['survey_id'] = $this->_surveyId; $row['token'] = strtolower($this->findTokenFor($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 validateRowValues(array $row, $key) { $row = parent::validateRowValues($row, $key); $token = $this->loader->getTracker()->getToken($row['token'] ? $row['token'] : 'emptytoken'); if ($token->exists) { // If token is not completed we can use it, otherwise it depends on the settings if ($token->isCompleted()) { switch ($this->getTokenCompleted()) { case self::TOKEN_SKIP: return false; case self::TOKEN_ERROR: $this->_addErrors(sprintf( $this->_('Token %s is completed.'), $token->getTokenId() ), $key); break; // Intentional fall-through, // other case are handled in SaveAnswerTask } } } else { switch ($this->getNoToken()) { case self::TOKEN_SKIP: return false; case self::TOKEN_ERROR: $this->_addErrors($this->getNoTokenError($row, $key), $key); break; default: $respTrack = $this->findRespondentTrackFor($row); if ($respTrack) { $row['resp_track_id'] == $respTrack; } else { $this->_addErrors(sprintf( $this->_('No track for inserting found for %s.'), implode(" / ", $row) ), $key); } } } return $row; }
Validate the data against the target form @param array $row @param scalar $key @return mixed Row array or false when errors occurred
entailment
protected function createModel() { $model = $this->loader->getTracker()->getRespondentTrackModel(); $model->set('gtr_track_name', 'label', $this->_('Track')); $model->set('gr2t_track_info', 'label', $this->_('Description'), 'description', $this->_('Enter the particulars concerning the assignment to this respondent.')); $model->set('assigned_by', 'label', $this->_('Assigned by')); $model->set('gr2t_start_date', 'label', $this->_('Start'), 'dateFormat', 'dd-MM-yyyy', 'formatFunction', $this->loader->getUtil()->getTranslated()->formatDate, 'default', new \Zend_Date()); $model->set('gr2t_reception_code'); return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $seq = $this->getHtmlSequence(); $seq->h3($this->getTitle()); $table = parent::getHtmlOutput($view); $this->applyHtmlAttributes($table); $seq->append($table); return $seq; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
protected function getRespondentName() { if ($this->respondentTrack instanceof \Gems_Tracker_RespondentTrack) { return $this->respondentTrack->getRespondentName(); } else { $select = $this->db->select(); $select->from('gems__respondents') ->joinInner('gems__respondent2org', 'grs_id_user = gr2o_id_user', array()) ->where('gr2o_patient_nr = ?', $this->patientId) ->where('gr2o_id_organization = ?', $this->organizationId); $data = $this->db->fetchRow($select); if ($data) { return trim($data['grs_first_name'] . ' ' . $data['grs_surname_prefix']) . ' ' . $data['grs_last_name']; } } return ''; }
Get a display version of the patient name @return string
entailment
public function hasHtmlOutput() { // Try to set $this->respondentTrackId, it can be ok when not set if (! $this->respondentTrackId) { if ($this->respondentTrack) { $this->respondentTrackId = $this->respondentTrack->getRespondentTrackId(); } else { $this->respondentTrackId = $this->request->getParam(\Gems_Model::RESPONDENT_TRACK); } } // First attempt at trackId if ((! $this->trackId) && $this->trackEngine) { $this->trackId = $this->trackEngine->getTrackId(); } // Check if a sufficient set of data is there if (! ($this->trackId || $this->patientId || $this->organizationId)) { // Now we really need $this->respondentTrack if (! $this->respondentTrack) { if ($this->respondentTrackId) { $this->respondentTrack = $this->loader->getTracker()->getRespondentTrack($this->respondentTrackId); } else { // Parameters not valid return false; } } } if (! $this->trackId) { $this->trackId = $this->respondentTrack->getTrackId(); } if (! $this->patientId) { $this->patientId = $this->respondentTrack->getPatientNumber(); } if (! $this->organizationId) { $this->organizationId = $this->respondentTrack->getOrganizationId(); } // \MUtil_Echo::track($this->trackId, $this->patientId, $this->organizationId, $this->respondentTrackId); return $this->getModel()->loadFirst() && parent::hasHtmlOutput(); }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model) { if ($this->request) { $this->processSortOnly($model); } $filter['gtr_id_track'] = $this->trackId; $filter['gr2o_patient_nr'] = $this->patientId; $filter['gr2o_id_organization'] = $this->organizationId; if ($this->excludeCurrent) { $filter[] = $this->db->quoteInto('gr2t_id_respondent_track != ?', $this->respondentTrackId); } $model->setFilter($filter); }
Overrule to implement snippet specific filtering and sorting. @param \MUtil_Model_ModelAbstract $model
entailment
public function execute($tokenData = null, $userId = null) { $tracker = $this->loader->getTracker(); $token = $tracker->getToken($tokenData[0]); $survey = $token->getSurvey(); $source = $survey->getSource(); if (method_exists($source, 'getCompletedTokens')) { $completed = $source->getCompletedTokens($tokenData, $survey->getSourceSurveyId()); } else { // No bulk method, check all individually $completed = $tokenData; } if ($completed) { $batch = $this->getBatch(); foreach($completed as $tokenId) { $batch->setTask('Tracker_CheckTokenCompletion', 'tokchk-' . $tokenId, $tokenId, $userId); } } }
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 addNextButton() { parent::addNextButton(); if (! (isset($this->formData['survey']) && $this->formData['survey'])) { $this->_nextButton->setAttrib('disabled', 'disabled'); } }
Add the next button
entailment
protected function createModel() { if (! $this->importModel instanceof \MUtil_Model_ModelAbstract) { $surveyId = $this->request->getParam(\MUtil_Model::REQUEST_ID); if ($surveyId) { $this->formData['survey'] = $surveyId; $this->_survey = $this->loader->getTracker()->getSurvey($surveyId); $surveys[$surveyId] = $this->_survey->getName(); $elementClass = 'Exhibitor'; $tracks = $this->util->getTranslated()->getEmptyDropdownArray() + $this->util->getTrackData()->getTracksBySurvey($surveyId); } else { $empty = $this->util->getTranslated()->getEmptyDropdownArray(); $trackData = $this->util->getTrackData(); $surveys = $empty + $trackData->getActiveSurveys(); $tracks = $empty + $trackData->getAllTracks(); $elementClass = 'Select'; } parent::createModel(); $order = $this->importModel->getOrder('trans') - 5; $this->importModel->set('survey', 'label', $this->_('Survey'), 'elementClass', $elementClass, 'multiOptions', $surveys, 'onchange', 'this.form.submit();', 'order', $order, 'required', true); $this->importModel->set('track', 'label', $this->_('Track'), 'description', $this->_('Optionally assign answers only within a single track'), 'multiOptions', $tracks //, // 'onchange', 'this.form.submit();' ); $this->importModel->set('skipUnknownPatients', 'label', $this->_('Skip unknowns'), 'default', 0, 'description', $this->_('What to do when the respondent does not exist'), 'elementClass', 'Checkbox', 'multiOptions', $this->util->getTranslated()->getYesNo() ); $tokenCompleted = array( \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_OVERWRITE => $this->_('Delete old token and create new'), \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_DOUBLE => $this->_('Create new extra set of answers'), \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR => $this->_('Abort the import'), \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_SKIP => $this->_('Skip the token'), ); $this->importModel->set('tokenCompleted', 'label', $this->_('When token completed'), 'default', \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR, 'description', $this->_('What to do when an imported token has already been completed'), 'elementClass', 'Radio', 'multiOptions', $tokenCompleted ); $tokenTreatments = array( // \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_DOUBLE => // $this->_('Create new token'), \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR => $this->_('Abort the import'), \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_SKIP => $this->_('Skip the token'), ); $this->importModel->set('noToken', 'label', $this->_('Token does not exist'), 'default', \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR, 'description', $this->_('What to do when no token exist to import to'), 'elementClass', 'Radio', 'multiOptions', $tokenTreatments ); if (\MUtil_Bootstrap::enabled()) { $this->importModel->set('tokenCompleted', 'separator', ''); } else { $this->importModel->set('trans', 'separator', '<br/>'); } } return $this->importModel; }
Called after the check that all required registry values have been set correctly has run. @return void / public function afterRegistry() { parent::afterRegistry(); } Creates the model @return \MUtil_Model_ModelAbstract
entailment
protected function getFormFor($step) { $model = $this->getModel(); $baseform = $this->createForm(); if ((\MUtil_Bootstrap::enabled() !== true) && ($baseform instanceof \MUtil_Form)) { $table = new \MUtil_Html_TableElement(); $table->setAsFormLayout($baseform, true, true); // There is only one row with formLayout, so all in output fields get class. $table['tbody'][0][0]->appendAttrib('class', $this->labelClass); } $baseform->setAttrib('class', $this->class); $bridge = $model->getBridgeFor('form', $baseform); $this->_items = null; $this->initItems(); $this->addFormElementsFor($bridge, $model, $step); return $baseform; }
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 getImportTranslator() { $translator = parent::getImportTranslator(); if ($translator instanceof \Gems_Model_Translator_AnswerTranslatorAbstract) { // Set answer specific options $surveyId = isset($this->formData['survey']) ? $this->formData['survey'] : null; $tokenCompleted = isset($this->formData['tokenCompleted']) ? $this->formData['tokenCompleted'] : \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR; $skipUnknownPatients = isset($this->formData['skipUnknownPatients']) && $this->formData['skipUnknownPatients']; $noToken = isset($this->formData['noToken']) ? $this->formData['noToken'] : \Gems_Model_Translator_AnswerTranslatorAbstract::TOKEN_ERROR; $trackId = isset($this->formData['track']) ? $this->formData['track'] : null; $translator->setSurveyId($surveyId); $translator->setSkipUnknownPatients($skipUnknownPatients); $translator->setTokenCompleted($tokenCompleted); $translator->setNoToken($noToken); $translator->setTrackId($trackId); } return $translator; }
Try to get the current translator @return \MUtil_Model_ModelTranslatorInterface or false if none is current
entailment
protected function loadFormData() { parent::loadFormData(); $surveyId = $this->request->getParam(\MUtil_Model::REQUEST_ID); if (isset($this->formData['survey']) && $this->formData['survey'] && (! $this->_survey instanceof \Gems_Tracker_Survey)) { $this->_survey = $this->loader->getTracker()->getSurvey($this->formData['survey']); } if ($this->_survey instanceof \Gems_Tracker_Survey) { // Add (optional) survey specific translators $extraTrans = $this->importLoader->getAnswerImporters($this->_survey); if ($extraTrans) { $this->importTranslators = $extraTrans + $this->importTranslators; $this->_translatorDescriptions = false; $this->importModel->set('trans', 'multiOptions', $this->getTranslatorDescriptions()); } } if ($this->_survey instanceof \Gems_Tracker_Survey) { $this->targetModel = $this->_survey->getAnswerModel($this->locale->toString()); $this->importer->setTargetModel($this->targetModel); $source = $this->menu->getParameterSource(); $source->offsetSet('gsu_has_pdf', $this->_survey->hasPdf() ? 1 : 0); $source->offsetSet('gsu_active', $this->_survey->isActive() ? 1 : 0); } // \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
public function execute($surveyId = null, $questionId = null, $order = null) { $batch = $this->getBatch(); $survey = $this->loader->getTracker()->getSurvey($surveyId); // Now save the questions $answerModel = $survey->getAnswerModel('en'); $questionModel = new \MUtil_Model_TableModel('gems__survey_questions'); \Gems_Model::setChangeFieldsByPrefix($questionModel, 'gsq'); $label = $answerModel->get($questionId, 'label'); /* if ($label instanceof \MUtil_Html_HtmlInterface) { $label = $label->render($this->view); } // */ $question['gsq_id_survey'] = $surveyId; $question['gsq_name'] = $questionId; $question['gsq_name_parent'] = $answerModel->get($questionId, 'parent_question'); $question['gsq_order'] = $order; $question['gsq_type'] = $answerModel->getWithDefault($questionId, 'type', \MUtil_Model::TYPE_STRING); $question['gsq_class'] = $answerModel->get($questionId, 'thClass'); $question['gsq_group'] = $answerModel->get($questionId, 'group'); $question['gsq_label'] = $label; $question['gsq_description'] = $answerModel->get($questionId, 'description'); // \MUtil_Echo::track($question); try { $questionModel->save($question); } catch (\Exception $e) { $batch->addMessage(sprintf( $this->_('Save failed for survey %s, question %s: %s'), $survey->getName(), $questionId, $e->getMessage() )); } $batch->addToCounter('checkedQuestions'); if ($questionModel->getChanged()) { $batch->addToCounter('changedQuestions'); } $batch->setMessage('questionschanged', sprintf( $this->_('%d of %d questions changed.'), $batch->getCounter('changedQuestions'), $batch->getCounter('checkedQuestions'))); $options = $answerModel->get($questionId, 'multiOptions'); if ($options) { $optionModel = new \MUtil_Model_TableModel('gems__survey_question_options'); \Gems_Model::setChangeFieldsByPrefix($optionModel, 'gsqo'); $option['gsqo_id_survey'] = $surveyId; $option['gsqo_name'] = $questionId; $i = 0; // \MUtil_Echo::track($options); foreach ($options as $key => $label) { $option['gsqo_order'] = $i; $option['gsqo_key'] = $key; $option['gsqo_label'] = $label; try { $optionModel->save($option); } catch (\Exception $e) { $batch->addMessage(sprintf( $this->_('Save failed for survey %s, question %s, option "%s" => "%s": %s'), $survey->getName(), $questionId, $key, $label, $e->getMessage() )); } $i++; } $batch->addToCounter('checkedOptions', count($options)); $batch->addToCounter('changedOptions', $optionModel->getChanged()); $batch->setMessage('optionschanged', sprintf( $this->_('%d of %d options changed.'), $batch->getCounter('changedOptions'), $batch->getCounter('checkedOptions'))); } }
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 _applyOptions(\MUtil_Model_ModelAbstract $model, $fieldName, array $options, array &$itemData) { if ($options) { $model->set($fieldName, 'multiOptions', $options); if (! array_key_exists($itemData[$fieldName], $options)) { // Set the value to the first possible value reset($options); $itemData[$fieldName] = key($options); return true; } } else { $model->del($fieldName, 'label'); } return false; }
Helper function for default handling of multi options value sets @param \MUtil_Model_ModelAbstract $model @param string $fieldName @param array $options @param array $itemData The current items data @param boolean True if the update changed values (usually by changed selection lists).
entailment
protected function _sourceUsesSurvey($source) { switch ($source) { case self::APPOINTMENT_TABLE: case self::NO_TABLE: case self::RESPONDENT_TRACK_TABLE: return false; default: return true; } }
Returns true if the source uses values from another token. @param string $source The current source @return boolean
entailment
protected function applyDatesValidAfter(\MUtil_Model_ModelAbstract $model, array &$itemData, $language) { // Set the after date fields that can be chosen for the current values $dateOptions = $this->getDateOptionsFor($itemData['gro_valid_after_source'], $itemData['gro_valid_after_id'], $language, true); return $this->_applyOptions($model, 'gro_valid_after_field', $dateOptions, $itemData); }
Set the after dates to be listed for this item and the way they are displayed (if at all) @param \MUtil_Model_ModelAbstract $model The round model @param array $itemData The current items data @param string $language (ISO) language string @param boolean True if the update changed values (usually by changed selection lists).
entailment
protected function applyDatesValidFor(\MUtil_Model_ModelAbstract $model, array &$itemData, $language) { $dateOptions = $this->getDateOptionsFor($itemData['gro_valid_for_source'], $itemData['gro_valid_for_id'], $language, true); if ($itemData['gro_id_round'] == $itemData['gro_valid_for_id']) { // Cannot use the valid until of the same round to calculate that valid until unset($dateOptions['gto_valid_until']); } if ($itemData['gro_valid_for_source'] == self::NO_TABLE) { $model->del('gro_valid_for_unit', 'label'); $model->del('gro_valid_for_length', 'label'); } return $this->_applyOptions($model, 'gro_valid_for_field', $dateOptions, $itemData); }
Set the for dates to be listed for this item and the way they are displayed (if at all) @param \MUtil_Model_ModelAbstract $model The round model @param array $itemData The current items data @param string $language (ISO) language string @param boolean True if the update changed values (usually by changed selection lists).
entailment
protected function applyRespondentRelation(\MUtil_Model_ModelAbstract $model, array &$itemData) { $model->set('gro_id_survey', 'onchange', 'this.form.submit();'); if (!empty($itemData['gro_id_survey']) && $model->has('gro_id_relationfield')) { $forStaff = $this->tracker->getSurvey($itemData['gro_id_survey'])->isTakenByStaff(); if (!$forStaff) { $empty = array('-1' => $this->_('Patient')); $relations = $this->getRespondentRelationFields(); if (!empty($relations)) { $relations = $empty + $relations; $model->set('gro_id_relationfield', 'label', $this->_('Assigned to'), 'multiOptions', $relations, 'order', 25); } $model->del('ggp_name'); } else { $model->set('ggp_name', 'label', $this->translateAdapter->_('Assigned to'), 'elementClass', 'Exhibitor', 'order', 25); $model->set('gro_id_relationfield', 'elementClass', 'hidden'); $itemData['ggp_name'] = $this->db->fetchOne('select ggp_name from gems__groups join gems__surveys on ggp_id_group = gsu_id_primary_group and gsu_id_survey = ?', $itemData['gro_id_survey']); if (!is_null($itemData['gro_id_relationfield'])) { $itemData['gro_id_relationfield'] = null; } } } else { $model->del('gro_id_relationfield', 'label'); $model->del('ggp_name'); if ($model->has('gro_id_relationfield')) { $itemData['gro_id_relationfield'] = null; } } }
Apply respondent relation settings to the round model For respondent surveys, we allow to set a relation, with possible choices: null => the respondent 0 => undefined (specifiy when assigning) >0 => the id of the track field of type relation to use @param \MUtil_Model_ModelAbstract $model The round model @param array $itemData The current items data @return boolean True if the update changed values (usually by changed selection lists).
entailment
protected function checkTokenCondition(\GemS_Tracker_Token $token, $round, $userId) { $skipCode = $this->util->getReceptionCodeLibrary()->getSkipString(); // Only if we have a condition, the token is not yet completed and // receptioncode is ok or skip we evaluate the condition if (empty($round['gro_condition']) || $token->isCompleted() || !($token->getReceptionCode()->isSuccess() || $token->getReceptionCode()->getCode() == $skipCode)) { return 0; } $changed = 0; $condition = $this->loader->getConditions()->loadCondition($round['gro_condition']); $newStatus = $condition->isRoundValid($token); $oldStatus = $token->getReceptionCode()->isSuccess(); if ($newStatus !== $oldStatus) { $changed = 1; if ($newStatus == false) { $message = $this->_('Skipped by condition %s: %s'); $newCode = $skipCode; } else { $message = $this->_('Activated by condition %s: %s'); $newCode = $this->util->getReceptionCodeLibrary()->getOKString(); } $token->setReceptionCode($newCode, sprintf($message, $condition->getName(), $condition->getRoundDisplay($token->getTrackId(), $token->getRoundId())), $userId); if ($newStatus == true) { // Token was made valid, now calc the dates $this->checkTokenDates($token, $round, $userId); } } return $changed; }
Check if the token should be enabled / disabled due to conditions @param \GemS_Tracker_Token $token @param array $round @param int $userId Id of the user who takes the action (for logging) @return int The number of tokens changed by this code
entailment
protected function checkTokenDates($token, $round, $userId) { // Change only not-completed tokens with a positive successcode where at least one date // is not set by user input if ($token->isCompleted() || !$token->getReceptionCode()->isSuccess() || ($token->isValidFromManual() && $token->isValidUntilManual())) { return 0; } $respTrack = $token->getRespondentTrack(); if ($token->isValidFromManual()) { $validFrom = $token->getValidFrom(); } else { $fromDate = $this->getValidFromDate( $round['gro_valid_after_source'], $round['gro_valid_after_field'], $round['gro_valid_after_id'], $token, $respTrack ); $validFrom = $this->calculateFromDate( $fromDate, $round['gro_valid_after_unit'], $round['gro_valid_after_length'] ); } if ($token->isValidUntilManual()) { $validUntil = $token->getValidUntil(); } else { $untilDate = $this->getValidUntilDate( $round['gro_valid_for_source'], $round['gro_valid_for_field'], $round['gro_valid_for_id'], $token, $respTrack, $validFrom ); $validUntil = $this->calculateUntilDate( $untilDate, $round['gro_valid_for_unit'], $round['gro_valid_for_length'] ); } return $token->setValidFrom($validFrom, $validUntil, $userId); }
Check the valid from and until dates for this token @param \GemS_Tracker_Token $token @param array $round @param int $userId Id of the user who takes the action (for logging) @return int 1 if the token has changed
entailment
public function checkTokensFrom(\Gems_Tracker_RespondentTrack $respTrack, \Gems_Tracker_Token $startToken, $userId, \Gems_Tracker_Token $skipToken = null) { // Make sure the rounds are loaded $this->_ensureRounds(); // Make sure the tokens are loaded and linked. $respTrack->getTokens(); // Go $changed = 0; $token = $startToken; while ($token) { // \MUtil_Echo::track($token->getTokenId()); //Only process the token when linked to a round $round = false; $changes = 0; if (array_key_exists($token->getRoundId(), $this->_rounds)) { $round = $this->_rounds[$token->getRoundId()]; } if ($round && $token !== $skipToken) { $changes = $this->checkTokenDates($token, $round, $userId); $changes += $this->checkTokenCondition($token, $round, $userId); } // If condition changed and dates changed, we only signal one change $changed += min($changes, 1); $token = $token->getNextToken(); } return $changed; }
Check the valid from and until dates in the track starting at a specified token @param \Gems_Tracker_RespondentTrack $respTrack The respondent track to check @param \Gems_Tracker_Token $startToken The token to start at @param int $userId Id of the user who takes the action (for logging) @param \Gems_Tracker_Token $skipToken Optional token to skip in the recalculation @return int The number of tokens changed by this code
entailment
public function checkTokensFromStart(\Gems_Tracker_RespondentTrack $respTrack, $userId) { $token = $respTrack->getFirstToken(); if ($token instanceof \Gems_Tracker_Token) { return $this->checkTokensFrom($respTrack, $respTrack->getFirstToken(), $userId); } else { return 0; } }
Check the valid from and until dates in the track @param \Gems_Tracker_RespondentTrack $respTrack The respondent track to check @param int $userId Id of the user who takes the action (for logging) @return int The number of tokens changed by this code
entailment
public function displayDateCalculation($value, $new, $name, array $context = array()) { $fieldBase = substr($name, 0, -5); // Strip field $validAfter = (bool) strpos($fieldBase, 'after'); // When always valid, just return nothing if ($context[$fieldBase . 'source'] == self::NO_TABLE) return ''; $fields = $this->getDateOptionsFor( $context[$fieldBase . 'source'], $context[$fieldBase . 'id'], $this->locale->getLanguage(), $validAfter ); if (isset($fields[$context[$fieldBase . 'field']])) { $field = $fields[$context[$fieldBase . 'field']]; } else { $field = $context[$fieldBase . 'field']; } if ($context[$fieldBase . 'length'] > 0) { $format = $this->_('%s plus %s %s'); } elseif($context[$fieldBase . 'length'] < 0) { $format = $this->_('%s minus %s %s'); } else { $format = $this->_('%s'); } $units = $this->util->getTranslated()->getPeriodUnits(); if (isset($units[$context[$fieldBase . 'unit']])) { $unit = $units[$context[$fieldBase . 'unit']]; } else { $unit = $context[$fieldBase . 'unit']; } // \MUtil_Echo::track(func_get_args()); return sprintf($format, $field, abs($context[$fieldBase . 'length']), $unit); }
Changes the display of gro_valid_[after|for]_field into something readable @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 The value to use
entailment
public function displayRoundId($value, $new, $name, array $context = array()) { $fieldSource = substr($name, 0, -2) . 'source'; if ($this->_sourceUsesSurvey($context[$fieldSource])) { return $value; } return ''; }
Changes the display of gro_valid_[for|after]_id into something readable Makes it empty when not applicable @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 The value to use
entailment
protected function getDateOptionsFor($sourceType, $roundId, $language, $validAfter) { switch ($sourceType) { case self::NO_TABLE: return array(); case self::ANSWER_TABLE: if (! isset($this->_rounds[$roundId], $this->_rounds[$roundId]['gro_id_survey'])) { return array(); } $surveyId = $this->_rounds[$roundId]['gro_id_survey']; $survey = $this->tracker->getSurvey($surveyId); return $survey->getDatesList($language); case self::APPOINTMENT_TABLE: return $this->_fieldsDefinition->getFieldLabelsOfType(FieldsDefinition::TYPE_APPOINTMENT); case self::RESPONDENT_TRACK_TABLE: $results = array( 'gr2t_start_date' => $this->_('Track start'), 'gr2t_end_date' => $this->_('Track end'), // 'gr2t_created' => $this->_('Track created'), ); return $results + $this->_fieldsDefinition->getFieldLabelsOfType(array( FieldsDefinition::TYPE_DATE, FieldsDefinition::TYPE_DATETIME, )); case self::TOKEN_TABLE: return array( 'gto_valid_from' => $this->_('Valid from'), 'gto_valid_until' => $this->_('Valid until'), 'gto_start_time' => $this->_('Start time'), 'gto_completion_time' => $this->_('Completion date'), ); } }
Returns the date fields selectable using the current source @param string $source The date list source as defined by this object @param int $roundId Gems round id @param string $language (ISO) language string @param boolean $validAfter True if it concenrs _valid_after_ dates @return type
entailment
public function getRespondentRelationFields() { $fields = array(); $relationFields = $this->getFieldsOfType('relation'); if (!empty($relationFields)) { $fieldNames = $this->getFieldNames(); $fieldPrefix = FieldMaintenanceModel::FIELDS_NAME . FieldsDefinition::FIELD_KEY_SEPARATOR; foreach ($this->getFieldsOfType('relation') as $key => $field) { $id = str_replace($fieldPrefix, '', $key); $fields[$id] = $fieldNames[$key]; } } return $fields; }
Get all respondent relation fields Returns an array of field id => field name @return array
entailment
public function getRoundModel($detailed, $action) { $model = parent::getRoundModel($detailed, $action); // Add information about surveys and groups $model->addLeftTable('gems__surveys', array('gro_id_survey' => 'gsu_id_survey')); $model->addLeftTable('gems__groups', array('gsu_id_primary_group' => 'ggp_id_group')); $model->addLeftTable('gems__track_fields', array('gro_id_relationfield = gtf_id_field'), 'gtf', false); $model->addColumn(new \Zend_Db_Expr('COALESCE(gtf_field_name, ggp_name)'), 'ggp_name'); $model->set('ggp_name', 'label', $this->_('Assigned to')); // Reset display order to class specific order $model->resetOrder(); if (! $detailed) { $model->set('gro_id_order'); } $model->set('gro_id_track'); $model->set('gro_id_survey'); $model->set('gro_round_description'); if ($detailed) { $model->set('gro_id_order'); } $model->set('gro_icon_file'); // Calculate valid from if ($detailed) { $html = \MUtil_Html::create()->h4($this->_('Valid from calculation')); $model->set('valid_after', 'default', $html, 'label', ' ', 'elementClass', 'html', 'value', $html ); } $model->set('gro_valid_after_source', 'label', $this->_('Date source'), 'default', self::TOKEN_TABLE, 'elementClass', 'Radio', 'escape', false, 'required', true, 'onchange', 'this.form.submit();', 'multiOptions', $this->getSourceList(true, false, false) ); $model->set('gro_valid_after_id', 'label', $this->_('Round used'), 'onchange', 'this.form.submit();' ); if ($detailed) { $periodUnits = $this->util->getTranslated()->getPeriodUnits(); $model->set('gro_valid_after_field', 'label', $this->_('Date used'), 'default', 'gto_valid_from', 'onchange', 'this.form.submit();' ); $model->set('gro_valid_after_length', 'label', $this->_('Add to date'), 'description', $this->_('Can be negative'), 'required', false, 'filter', 'Int' ); $model->set('gro_valid_after_unit', 'label', $this->_('Add to date unit'), 'multiOptions', $periodUnits ); } else { $model->set('gro_valid_after_source', 'label', $this->_('Source'), 'tableDisplay', 'small' ); $model->set('gro_valid_after_id', 'label', $this->_('Round'), 'multiOptions', $this->getRoundTranslations(), 'tableDisplay', 'small' ); $model->setOnLoad('gro_valid_after_id', array($this, 'displayRoundId')); $model->set('gro_valid_after_field', 'label', $this->_('Date calculation'), 'tableHeaderDisplay', 'small' ); $model->setOnLoad('gro_valid_after_field', array($this, 'displayDateCalculation')); $model->set('gro_valid_after_length'); $model->set('gro_valid_after_unit'); } if ($detailed) { // Calculate valid until $html = \MUtil_Html::create()->h4($this->_('Valid for calculation')); $model->set('valid_for', 'label', ' ', 'default', $html, 'elementClass', 'html', 'value', $html ); } $model->set('gro_valid_for_source', 'label', $this->_('Date source'), 'default', self::TOKEN_TABLE, 'elementClass', 'Radio', 'escape', false, 'required', true, 'onchange', 'this.form.submit();', 'multiOptions', $this->getSourceList(false, false, false) ); $model->set('gro_valid_for_id', 'label', $this->_('Round used'), 'default', '', 'onchange', 'this.form.submit();' ); if ($detailed) { $model->set('gro_valid_for_field', 'label', $this->_('Date used'), 'default', 'gto_valid_from', 'onchange', 'this.form.submit();' ); $model->set('gro_valid_for_length', 'label', $this->_('Add to date'), 'description', $this->_('Can be negative'), 'required', false, 'default', 2, 'filter', 'Int' ); $model->set('gro_valid_for_unit', 'label', $this->_('Add to date unit'), 'multiOptions', $periodUnits ); // Continue with last round level items $model->set('gro_condition'); $model->set('condition_display'); $model->set('gro_active'); $model->set('gro_changed_event'); } else { $model->set('gro_valid_for_source', 'label', $this->_('Source'), 'tableDisplay', 'small' ); $model->set('gro_valid_for_id', 'label', $this->_('Round'), 'multiOptions', $this->getRoundTranslations(), 'tableDisplay', 'small' ); $model->setOnLoad('gro_valid_for_id', array($this, 'displayRoundId')); $model->set('gro_valid_for_field', 'label', $this->_('Date calculation'), 'tableHeaderDisplay', 'small' ); $model->setOnLoad('gro_valid_for_field', array($this, 'displayDateCalculation')); $model->set('gro_valid_for_length'); $model->set('gro_valid_for_unit'); } return $model; }
Returns a model that can be used to retrieve or save the data. @param boolean $detailed Create a model for the display of detailed item data or just a browse table @param string $action The current action @return \MUtil_Model_ModelAbstract
entailment
protected function getSourceList($validAfter, $firstRound, $detailed = true) { if (! ($validAfter || $this->project->isValidUntilRequired())) { $results[self::NO_TABLE] = array($this->_('Does not expire')); } if (! ($validAfter && $firstRound)) { $results[self::ANSWER_TABLE] = array($this->_('Answers'), $this->_('Use an answer from a survey.')); } if ($this->_fieldsDefinition->hasAppointmentFields()) { $results[self::APPOINTMENT_TABLE] = array( $this->_('Appointment'), $this->_('Use an appointment linked to this track.'), ); } if (! ($validAfter && $firstRound)) { $results[self::TOKEN_TABLE] = array($this->_('Token'), $this->_('Use a standard token date.')); } $results[self::RESPONDENT_TRACK_TABLE] = array($this->_('Track'), $this->_('Use a track level date.')); if ($detailed) { foreach ($results as $key => $value) { if (is_array($value)) { $results[$key] = \MUtil_Html::raw(sprintf('<strong>%s</strong> %s', reset($value), next($value))); } } } else { foreach ($results as $key => $value) { if (is_array($value)) { $results[$key] = reset($value); } } } return $results; }
Returns the source choices in an array. @param boolean $validAfter True if it concerns _valid_after_ dates @param boolean $firstRound List for first round @param boolean $detailed Return extended info @return array source_name => label
entailment
protected function getSurveyId($roundId) { $this->_ensureRounds(); if (isset($this->_rounds[$roundId]['gro_id_survey'])) { return $this->_rounds[$roundId]['gro_id_survey']; } throw new \Gems_Exception_Coding("Requested non existing survey id for round $roundId."); }
Look up the survey id associated with a round @param int $roundId Gems round id @return int Gems survey id
entailment
public function getTokenShowSnippetNames(\Gems_Tracker_Token $token) { $output[] = 'Token\\ShowTrackTokenSnippet'; if ($token->isCompleted() && $this->currentUser->hasPrivilege('pr.token.answers')) { $output[] = 'Tracker_Answers_SingleTokenAnswerModelSnippet'; } elseif ($this->currentUser->hasPrivilege('pr.project.questions')) { $output[] = 'Survey\\SurveyQuestionsSnippet'; } return $output; }
An array of snippet names for displaying a token @param \Gems_Tracker_Token $token Allows token status dependent show snippets @return array of string snippet names
entailment
protected function setDateListFor(\MUtil_Model_ModelAbstract $model, $fieldName, $source, $roundId, $language, $validAfter) { $dateOptions = $this->getDateOptionsFor($source, $roundId, $language, $validAfter); switch (count($dateOptions)) { case 0: $model->del($fieldName, 'label'); break; case 1: $model->set($fieldName, 'elementClass', 'exhibitor'); // Intentional fall through default: $model->set($fieldName, 'multiOptions', $dateOptions); break; } }
The logic to set the display of the valid_X_field date list field. @param \MUtil_Model_ModelAbstract $model The round model @param string $fieldName The valid_X_field to set @param string $source The date list source as defined by this object @param int $roundId Optional a round id @param string $language (ISO) language string @param boolean $validAfter True if it concerns _valid_after_ dates
entailment
public function updateRoundModelToItem(\MUtil_Model_ModelAbstract $model, array &$itemData, $language) { $this->_ensureRounds(); // Is this the first token? $first = ! $this->getPreviousRoundId($itemData['gro_id_round'], $itemData['gro_id_order']); // Update the current round data if (isset($this->_rounds[$itemData['gro_id_round']])) { $this->_rounds[$itemData['gro_id_round']] = $itemData + $this->_rounds[$itemData['gro_id_round']]; } else { $this->_rounds[$itemData['gro_id_round']] = $itemData; } // Default result $result = false; // VALID AFTER DATE if (! $this->_sourceUsesSurvey($itemData['gro_valid_after_source'])) { $model->del('gro_valid_after_id', 'label'); } else { // Survey list is independent of the actual chosen source, but not // vice versa. So we have to set it now. $result = $this->applySurveyListValidAfter($model, $itemData) || $result; } // Set allowed after sources $result = $this->_applyOptions($model, 'gro_valid_after_source', $this->getSourceList(true, $first), $itemData) || $result; // Set the after date fields that can be chosen for the current values $result = $this->applyDatesValidAfter($model, $itemData, $language) || $result; // VALID FOR DATE // Display used survey only when appropriate if (! $this->_sourceUsesSurvey($itemData['gro_valid_for_source'])) { $model->del('gro_valid_for_id', 'label'); } else { // Survey list is indepedent of the actual chosen source, but not // vice versa. So we have to set it now. $result = $this->applySurveyListValidFor($model, $itemData) || $result; } // Set allowed for sources $result = $this->_applyOptions($model, 'gro_valid_for_source', $this->getSourceList(false, $first), $itemData) || $result; // Set the for date fields that can be chosen for the current values $result = $this->applyDatesValidFor($model, $itemData, $language) || $result; // Apply respondent relation settings $result = $this->applyRespondentRelation($model, $itemData) || $result; return $result; }
Updates the model to reflect the values for the current item data @param \MUtil_Model_ModelAbstract $model The round model @param array $itemData The current items data @param string $language (ISO) language string @param boolean True if the update changed values (usually by changed selection lists).
entailment
public function createActionButtons(\MUtil_Model_Bridge_TableBridge $bridge) { $tData = $this->util->getTokenData(); // Action links $actionLinks['ask'] = $tData->getTokenAskLinkForBridge($bridge, true); $actionLinks['email'] = $tData->getTokenEmailLinkForBridge($bridge); $actionLinks['answer'] = $tData->getTokenAnswerLinkForBridge($bridge); $output = []; foreach ($actionLinks as $key => $actionLink) { if ($actionLink) { $output[] = ' '; $output[$key] = \MUtil_Html::create( 'div', $actionLink, ['class' => 'rightFloat', 'renderWithoutContent' => false, 'style' => 'clear: right;'] ); } } return $output; }
Return a list of possible action buttons for the token @param \MUtil_Model_Bridge_TableBridge $bridge @return array of HtmlElements
entailment
protected function createInfoPlusCol(\MUtil_Model_Bridge_TableBridge $bridge) { $tData = $this->util->getTokenData(); return [ 'class' => 'text-right', $tData->getTokenStatusLinkForBridge($bridge), ' ', $tData->getTokenShowLinkForBridge($bridge, true) ]; }
Returns a '+' token button @param \MUtil_Model_Bridge_TableBridge $bridge @return \MUtil_Html_AElement
entailment
protected function createShowTokenButton(\MUtil_Model_Bridge_TableBridge $bridge) { $link = $this->util->getTokenData()->getTokenShowLinkForBridge($bridge, true); if ($link) { return $link; } }
Returns a '+' token button @param \MUtil_Model_Bridge_TableBridge $bridge @return \MUtil_Html_AElement
entailment
public function execute($trackId = null) { $batch = $this->getBatch(); $select = $this->db->select(); // Join conditions on rounds, handle and / or conditions when implemented $select->from('gems__conditions', array( 'gcon_id', 'gcon_type', 'gcon_class', 'gcon_name', 'gcon_condition_text1', 'gcon_condition_text2', 'gcon_condition_text3', 'gcon_condition_text4', )) ->joinInner('gems__rounds', 'gems__conditions.gcon_id = gems__rounds.gro_condition', array()) ->where('gems__rounds.gro_id_track = ?', $trackId) ->distinct(true); // \MUtil_Echo::track($select->__toString(), $roundId); $data = $this->db->fetchAll($select); // \MUtil_Echo::track($data); if ($data) { $this->exportTypeHeader('conditions'); $this->exportFieldHeaders(reset($data)); foreach($data as $row) { $this->exportFieldData($row); $count = $batch->addToCounter('conditions_exported'); } $this->exportFlush(); $batch->setMessage('conditions_export', sprintf( $this->plural('%d condition exported', '%d conditions 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 addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $tData = $this->util->getTokenData(); // Signal the bridge that we need these values $bridge->gr2t_id_respondent_track; $bridge->gr2o_patient_nr; $bridge->tr()->appendAttrib('class', \MUtil_Lazy::iif( $bridge->gro_id_round, $bridge->row_class, array($bridge->row_class , ' inserted') )); // Add token status $bridge->td($tData->getTokenStatusLinkForBridge($bridge, false))->appendAttrib('class', 'text-right'); // Columns $bridge->addSortable('gsu_survey_name') ->append(\MUtil_Lazy::iif( $bridge->gro_icon_file, \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->addSortable('gto_round_description'); $bridge->addSortable('ggp_name'); $bridge->addSortable('gto_valid_from', null, 'date'); $bridge->addSortable('gto_completion_time', null, 'date'); $bridge->addSortable('gto_valid_until', null, 'date'); // Rights depended score column if ($this->currentUser->hasPrivilege('pr.respondent.result') && (! $this->currentUser->isFieldMaskedWhole('gto_result'))) { $bridge->addSortable('gto_result', $this->_('Score'), 'date'); } $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
public function getHtmlOutput(\Zend_View_Abstract $view) { $table = parent::getHtmlOutput($view); $table->class = $this->class; $this->applyHtmlAttributes($table); $this->class = false; $tableContainer = \MUtil_Html::create()->div(array('class' => 'table-container'), $table); return $tableContainer; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
public function hasHtmlOutput() { if (! $this->respondentTrackId) { if (isset($this->trackData['gr2t_id_respondent_track'])) { $this->respondentTrackId = $this->trackData['gr2t_id_respondent_track']; } elseif (isset($this->trackData['gto_id_respondent_track'])) { $this->respondentTrackId = $this->trackData['gto_id_respondent_track']; } elseif ($this->request && ($respondentTrackId = $this->request->getParam(\Gems_Model::RESPONDENT_TRACK))) { $this->respondentTrackId = $respondentTrackId; } } if ($this->respondentTrackId) { return parent::hasHtmlOutput(); } else { return false; } }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model) { $model->setFilter(array('gto_id_respondent_track' => $this->respondentTrackId)); $this->processSortOnly($model); }
Overrule to implement snippet specific filtering and sorting. @param \MUtil_Model_ModelAbstract $model
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $tabs = $this->getTabs(); $tabCount = count($tabs); if ($tabs && ($this->displaySingleTab || $tabCount > 1)) { // Is there a better helper to include JS? $view->headScript()->appendFile($this->basepath->getBasePath() . '/gems/js/jquery.horizontalScrollMenu.js'); $script = '(function($) {$(".'.$this->class.'").horizontalScrollMenu();}(jQuery));'; $view->inlineScript()->appendScript($script); // Set the correct parameters $this->getCurrentTab(); $scrollContainer = \MUtil_Html::create()->div(); if ($tabCount > $this->scrollFromSize) { $scrollContainer->a('#', $this->prevLabel, array('class' => 'prev')); } else { $scrollContainer->span(array('class' => 'prev disabled')) ->raw(str_repeat('&nbsp', strlen($this->prevLabel))); } $tabRow = $scrollContainer->div(array('class' => 'container'))->ul(); foreach ($tabs as $tabId => $content) { $li = $tabRow->li(array('class' => $this->tabClass)); if (strlen($content) > $this->tabLabelLength) { $content = substr($content, 0, $this->tabLabelLength) . $this->tabLabelCutOffString; } $li->a($this->getParameterKeysFor($tabId) + $this->href, $content); if ($tabId == $this->currentTab) { $li->appendAttrib('class', $this->tabActiveClass); } } if ($tabCount > $this->scrollFromSize) { $scrollContainer->a('#', $this->nextLabel, array('class' => 'next')); } else { $scrollContainer->span(array('class' => 'next disabled')) ->raw(str_repeat('&nbsp', strlen($this->nextLabel))); } return $scrollContainer; } else { return null; } }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
protected function createEditPrepare() { $this->createEditSnippets = $this->getTrackEngine()->getRoundEditSnippetNames(); \MUtil_JQuery::enableView($this->view); $this->view->headScript()->appendFile($this->basepath->getBasePath() . '/gems/js/jquery.showOnChecked.js'); if (\MUtil_Bootstrap::enabled()) { $this->view->headScript()->appendScript("jQuery(document).ready(function($) { $('input[name=\"organizations[]\"]').closest('div').showOnChecked( { showInput: $('#org_specific_round-1') }); });"); } else { $this->view->headScript()->appendScript("jQuery(document).ready(function($) { $('input[name=\"organizations[]\"]').closest('tr').showOnChecked( { showInput: $('#org_specific_round-1') }); });"); } }
Preparations for creating and editing
entailment
public function createModel($detailed, $action) { $trackEngine = $this->getTrackEngine(); $trackId = $trackEngine->getTrackId(); $model = $trackEngine->getRoundModel($detailed, $action); $model->set('gro_id_track', 'default', $trackId); if ($detailed) { if ($action == 'create') { // Set the default round order $newOrder = $this->db->fetchOne( "SELECT MAX(gro_id_order) FROM gems__rounds WHERE gro_id_track = ?", $trackId ); if ($newOrder) { $model->set('gro_id_order', 'default', $newOrder + 10); } else { $model->set('gro_valid_after_source', 'default', 'rtr'); } } } return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \Gems_Model_TrackModel
entailment
protected function setAfterDeleteRoute() { parent::setAfterDeleteRoute(); if ($this->afterSaveRouteUrl) { $this->afterSaveRouteUrl[\Gems_Model::APPOINTMENT_ID] = $this->request->getParam(\Gems_Model::APPOINTMENT_ID); } }
Set what to do when the form is 'finished'. @return \MUtil_Snippets_ModelYesNoDeleteSnippetAbstract
entailment
private function _setMenuParameters(array $data) { $source = $this->menu->getParameterSource(); $source['script'] = $data['script'] ? true : false; $source['exists'] = $data['exists'] ? true : false; }
Set the parameters needed by the menu. @param array $data The current model item
entailment
private function _cleanCache() { if ($this->cache instanceof \Zend_Cache_Core) { $this->cache->clean(); $this->addMessage($this->_('Cache cleaned')); } }
Make sure the cache is cleaned. As a lot of cache depends on the database, it is best to clean the cache now since import tables might have changed. @return void
entailment
public function createModel($detailed, $action) { $moreDetails = ! in_array($action, array('run', 'deleted')); $model = new \Gems_Model_DbaModel($this->db, $this->escort->getDatabasePaths()); if ($this->project->databaseFileEncoding) { $model->setFileEncoding($this->project->databaseFileEncoding); } $model->set('type', 'label', $this->_('Type')); $model->set('name', 'label', $this->_('Name')); if ($moreDetails) { $model->set('group', 'label', $this->_('Group')); $model->set('order', 'label', $this->_('Order')); $model->set('location', 'label', $this->_('Location')); } // $model->set('path', 'label', $this->_('Path')); $model->set('state', 'label', $this->_('Status')); if ($detailed) { $model->set('script', 'label', $this->_('Script'), 'itemDisplay', 'pre'); } else { $model->set('lastChanged', 'label', $this->_('Changed on'), 'dateFormat', 'yyyy-MM-dd HH:mm:ss'); } 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 getShowTable($columns = 1, $filter = null, $sort = null) { $model = $this->getModel(); $bridge = $model->getBridgeFor('itemTable'); $bridge->setColumnCount($columns); foreach($model->getItemsOrdered() as $name) { if ($label = $model->get($name, 'label')) { $bridge->addItem($name, $label); } } $table = $bridge->getTable(); $table->class = 'displayer table'; return $table; }
Creates from the model a \MUtil_Html_TableElement for display of a single item. It can and will display multiple items, but that is not what this function is for. @param integer $columns The number of columns to use for presentation @param mixed $filter A valid filter for \MUtil_Model_ModelAbstract->load() @param mixed $sort A valid sort for \MUtil_Model_ModelAbstract->load() @return \MUtil_Html_TableElement
entailment
public function showChangesAction() { $patchLevels = $this->db->fetchPairs('SELECT DISTINCT gpa_level, gpa_level FROM gems__patches ORDER BY gpa_level DESC'); $searchData['gpa_level'] = reset($patchLevels); if ($this->request instanceof \Zend_Controller_Request_Abstract) { $searchData = $this->request->getParams() + $searchData; } $snippet = $this->addSnippet( 'Database\\StructuralChanges', 'patchLevels', $patchLevels, 'searchData', $searchData ); if (1 == $this->request->getParam('download')) { $snippet->outputText($this->view, $this->_helper); } }
Show the changes in the database
entailment
private function _setMulti($value, $name1, $name2 = null) { $args = func_get_args(); array_shift($args); foreach ($args as $key) { $this->offsetSet($key, $value); } }
Helper function to set more than one array key to the same value @param mixed $value The value to set @param string $name1 The first key to set @param string $name2 Optional, second key, number of keys is unlimited
entailment
protected function createRequest($class, array $parameters) { if (!isset($parameters['credentials'])) { $parameters['credentials'] = new Credentials(array_intersect_key($this->getCredentialFields(), $parameters)); } return new $class($parameters); }
Initialize a request object This function is usually used to initialise objects of type BaseRequest (or a non-abstract subclass of it) using existing parameters from this gateway. If a client has been set on this class it will passed through, allowing a mock guzzle client to be used for testing. Example: <code> function myRequest($parameters) { $this->createRequest('MyRequest', $parameters); } class MyRequest extends SilverpopBaseRequest {}; // Create the mailer $mailer = Omnimail::create('Silverpop', $parameters); // Create the request object $myRequest = $mailer->myRequest($someParameters); </code> @param string $class The request class name @param array $parameters @return RequestInterface
entailment
public function getTokenElement() { $element = $this->getElement($this->_tokenFieldName); if (! $element) { $tokenLib = $this->tracker->getTokenLibrary(); $max_length = $tokenLib->getLength(); // Veld token $element = new \Zend_Form_Element_Text($this->_tokenFieldName); $element->setLabel($this->translate->_('Token')); $element->setDescription(sprintf($this->translate->_('Enter tokens as %s.'), $tokenLib->getFormat())); $element->setAttrib('size', $max_length + 2); $element->setAttrib('maxlength', $max_length); $element->setRequired(true); $element->addFilter($this->tracker->getTokenFilter()); $element->addValidator($this->tracker->getTokenValidator()); $this->addElement($element); } return $element; }
Returns/sets a password element. @return \Zend_Form_Element_Password
entailment
public function addAskPage($label) { $page = $this->addPage($label, null, 'ask'); // Routes for token controller $page->addAction(null, null, 'forward'); $page->addAction(null, null, 'return'); $page->addAction(null, null, 'to-survey')->setModelParameters(1); $page->addAction(null, null, 'token'); return $page; }
Shortcut function to create a ask menu, with hidden options. This function is in \Gems_Menu instead of AbstractMenu because you should ALWAYS put this menu in the root menu. @param string $label Label for the whole menu
entailment
public function addContactPage($label) { $project = $this->escort->project; $page = $this->addPage($label, null, 'contact'); $page->addAction(sprintf($this->_('About %s'), $project->getName()), null, 'about'); $page->addAction(sprintf($this->_('About %s'), $this->_('GemsTracker')), 'pr.contact.gems', 'gems'); $page->addAction($this->_('Reporting bugs'), 'pr.contact.bugs', 'bugs'); $page->addAction($this->_('Support'), 'pr.contact.support', 'support'); return $page; }
Shortcut function to create a contact container. This function is in \Gems_Menu instead of AbstractMenu because you should ALWAYS put this menu in the root menu. @param string $label Label for the whole menu @return \Gems_Menu_MenuAbstract The new contact page
entailment
public function addGemsSetupContainer($label) { $setup = $this->addContainer($label); // PROJECT LEVEL $cont = $setup->addProjectInfoPage($this->_('Project setup')); // DATABASE CONTROLLER $page = $setup->addPage($this->_('Database'), 'pr.database', 'database'); $page->addAutofilterAction(); // Creation not possible $showPage = $page->addShowAction('pr.database'); $showPage->addAction($this->_('Content'), 'pr.database', 'view') ->addParameters(\MUtil_Model::REQUEST_ID) ->setParameterFilter('exists', true); $showPage->addAction($this->_('Execute'), 'pr.database.create', 'run') ->addParameters(\MUtil_Model::REQUEST_ID) ->setParameterFilter('script', true); $showPage->addDeleteAction('pr.database.delete') ->setParameterFilter('exists', true); $page->addAction($this->_('Execute new'), 'pr.database.create', 'run-all'); $page->addAction($this->_('Patches'), 'pr.database.patches', 'patch'); $page->addAction($this->_('Show structure changes'), 'pr.database', 'show-changes'); if (isset($this->escort->project->databaseTranslations)) { $page->addAction($this->_('Refresh translateables'), 'pr.database', 'refresh-translations'); } $page->addAction($this->_('Run SQL'), 'pr.database.execute', 'run-sql'); $databaseBackup = $page->addPage($this->_('Database backup'), 'pr.database.backup', 'database-backup', 'index'); $databaseBackup->addActionButton($this->_('Backup'), 'pr.database.backup', 'backup'); // CODE LEVEL $cont = $setup->addContainer($this->_('Codes')); $cont->addBrowsePage($this->_('Reception codes'), 'pr.reception', 'reception'); $cont->addBrowsePage($this->_('Consents'), 'pr.consent', 'consent'); // ACCESS LEVEL $cont = $setup->addContainer($this->_('Access')); // ROLES CONTROLLER $page = $cont->addBrowsePage($this->_('Roles'), 'pr.role', 'role'); // ASSIGNED CONTROLLER $assiPage = $page->addPage($this->_('Assigned'), 'pr.role', 'role-overview', 'index'); $assiPage->addAutofilterAction(); $assiPage->addExportAction(); // PRIVILEGES CONTROLLER $privPage = $page->addPage($this->_('Privileges'), 'pr.role', 'privileges', 'index'); $privPage->addAutofilterAction(); $privPage->addExportAction(); // GROUPS CONTROLLER $cont->addGroupsPage($this->_('Groups')); // ORGANIZATIONS CONTROLLER $orgsPage = $cont->addBrowsePage($this->_('Organizations'), 'pr.organization', 'organization'); $orgsPage->addAction($this->_('Check all respondents'), 'pr.organization.check-all', 'check-all'); $orgPage = $this->findController('organization', 'show'); $orgPage->addAction($this->_('Check respondents'), 'pr.organization.check-org', 'check-org') ->setModelParameters(1); // STAFF CONTROLLER $page = $cont->addStaffPage($this->_('Staff')); // AGENDA CONTAINER $setup->addAgendaSetupMenu($this->_('Agenda')); // MAIL CONTAINER $setup->addCommSetupMenu($this->_('Communication')); // LOG CONTROLLER $setup->addLogControllers(); // OpenRosa $this->addOpenRosaContainer($this->_('OpenRosa'), $setup); return $setup; }
Shortcut function to create a setup container. This function is in \Gems_Menu instead of AbstractMenu because you should ALWAYS put this menu in the root menu. @param string $label Label for the whole menu @param string $privilegeShow The limited privilege (look and edit some items) @param string $privilegeEdits The privilege for being allowed to do anything
entailment
public function addHiddenPrivilege($privilege, $label = null) { if (null === $label) { $label = $this->_('Stand-alone privilege: %s'); } $this->_hiddenPrivileges[$privilege] = sprintf($label, $privilege); return $this; }
Use this to add a privilege that is not associated with a menu item. @param string $privilege @param string $label @return \Gems_Menu
entailment
public function addOpenRosaContainer($label, $parent = null) { if ($this->escort->getOption('useOpenRosa')) { if (is_null($parent)) { $parent = $this; } $page = $parent->addBrowsePage($label, 'pr.openrosa','openrosa'); $page->addButtonOnly($this->_('Scan Responses'), 'pr.openrosa.scan', 'openrosa', 'scanresponses'); $this->addPage(null, null, 'openrosa', 'submission'); $this->addPage(null, null, 'openrosa', 'formList'); //mind the capital L here $this->addPage(null, null, 'openrosa', 'download'); $this->addPage(null, null, 'openrosa', 'barcode'); // For barcode rendering $this->addPage(null, 'pr.islogin', 'openrosa', 'image'); // For image rendering $this->addPage(null, null, 'open-rosa-form', 'edit'); } }
Shortcut function to add all items needed for OpenRosa Should be enabled in application.ini by using useOpenRosa = 1 @param string $label Label for the container
entailment
public function addParticipatePage($label) { $participate = $this->addContainer($label); $subscr = $participate->addPage($this->_('Subscribe'), 'pr.participate.subscribe', 'participate', 'subscribe'); $subscr->addPage(null, 'pr.participate.subscribe', 'participate', 'subscribe-thanks'); $unsub = $participate->addPage($this->_('Unsubscribe'), 'pr.participate.unsubscribe', 'participate', 'unsubscribe'); $unsub->addPage(null, 'pr.participate.unsubscribe', 'participate', 'unsubscribe-thanks'); return $participate; }
Shortcut function to create a participate page This function is in \Gems_Menu instead of AbstractMenu because you should ALWAYS put this menu in the root menu. @param string $label Label for the whole menu
entailment
public function addRespondentPage($label) { $orgId = $this->user->getCurrentOrganizationId(); $params = array(\MUtil_Model::REQUEST_ID1 => 'gr2o_patient_nr', \MUtil_Model::REQUEST_ID2 => 'gr2o_id_organization'); // MAIN RESPONDENTS ITEM $page = $this->addPage($label, 'pr.respondent', 'respondent'); $page->addAutofilterAction(); $page->addCreateAction('pr.respondent.create')->setParameterFilter('can_add_respondents', true); $page->addExportAction(); $page->addImportAction(); $page->addAction(null, 'pr.respondent.simple-api', 'simple-api'); $rPage = $page->addShowAction() ->setNamedParameters($params) ->setHiddenOrgId($orgId); $rPage->addEditAction('pr.respondent.edit') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $rPage->addAction($this->_('Change organization'), 'pr.respondent.change-org', 'change-organization') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $rPage->addAction(null, 'pr.token.answers', 'overview') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $rPage->addPage($this->_('View survey'), 'pr.track.insert', 'track', 'view-survey', array('button_only' => true)) ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::SURVEY_ID, 'gsu_id_survey') ->setHiddenOrgId($orgId); // Add "episodes of care" $epiParams = array(\Gems_Model::EPISODE_ID => 'gec_episode_of_care_id'); // + $params; $epage = $rPage->addPage($this->_('Episodes'), 'pr.episodes', 'care-episode'); $epage->setNamedParameters($params) ->setHiddenOrgId($orgId); $epage->addAutofilterAction(); $epage->addCreateAction()->setNamedParameters($params)->setHiddenOrgId($orgId); $epage = $epage->addShowAction()->setNamedParameters($epiParams); $epage->addEditAction()->setNamedParameters($epiParams); $epage->addDeleteAction()->setNamedParameters($epiParams); // Add "appointments" $appParams = array(\Gems_Model::APPOINTMENT_ID => 'gap_id_appointment'); // + $params; $apage = $rPage->addPage($this->_('Appointments'), 'pr.appointments', 'appointment'); $apage->setNamedParameters($params) ->setHiddenOrgId($orgId); $apage->addAutofilterAction(); $apage->addCreateAction()->setNamedParameters($params)->setHiddenOrgId($orgId); $apage = $apage->addShowAction()->setNamedParameters($appParams); $apage->addEditAction()->setNamedParameters($appParams); $apage->addDeleteAction()->setNamedParameters($appParams); if ($this->escort instanceof \Gems_Project_Tracks_SingleTrackInterface) { $subPage = $rPage->addPage($this->_('Track'), 'pr.track', 'track', 'show-track') ->setNamedParameters($params) ->setHiddenOrgId($orgId) ->addHiddenParameter(\Gems_Model::TRACK_ID, $this->escort->getTrackId()); $subPage->addAction($this->_('Add'), 'pr.track.create', 'create') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 1) ->addHiddenParameter('track_can_be_created', 1); $subPage->addAction($this->_('Preview'), 'pr.track', 'view') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 1) ->addHiddenParameter('track_can_be_created', 1); $subPage->addAction($this->_('Edit'), 'pr.track.edit', 'edit-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 0) ->addHiddenParameter('track_can_be_created', 0); $tkPage = $subPage->addAction($this->_('Token'), 'pr.token', 'show') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter(\Gems_Model::ID_TYPE, 'token'); $subPage->addAction($this->_('Insert'), 'pr.track.insert', 'insert') ->setNamedParameters($params) ->addOptionalParameters(\Gems_Model::SURVEY_ID, 'gsu_id_survey') ->setHiddenOrgId($orgId); $subPage->addAction($this->_('Check answers'), 'pr.track.answers', 'check-track-answers') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 0) ->addHiddenParameter('track_can_be_created', 0); $subPage->addAction($this->_('Check rounds'), 'pr.track.check', 'check-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 0, 'gtr_active', 1, 'gr2t_active', 1) ->addHiddenParameter('track_can_be_created', 0); $subPage->addAction($this->_('Recalculate fields'), 'pr.track.check', 'recalc-fields') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId) ->setParameterFilter('track_can_be_created', 0, 'gtr_active', 1, 'gr2t_active', 1) ->addHiddenParameter('track_can_be_created', 0); } else { $trPage = $rPage->addPage($this->_('Tracks'), 'pr.track', 'track'); $trPage->setNamedParameters($params) ->setHiddenOrgId($orgId) ->addAutofilterAction(); $trPage->addAction($this->_('Add'), 'pr.track.create', 'create') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId); $trPage->addAction($this->_('Assignments'), 'pr.track', 'view') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::TRACK_ID, 'gtr_id_track') ->setHiddenOrgId($orgId); $trPage->addAction($this->_('Insert'), 'pr.track.insert', 'insert') ->setNamedParameters($params) ->addOptionalParameters(\Gems_Model::SURVEY_ID, 'gsu_id_survey') ->setHiddenOrgId($orgId); $itemPage = $trPage->addAction($this->_('Show track'), 'pr.track', 'show-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId); $itemPage->addAction($this->_('Edit'), 'pr.track.edit', 'edit-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 1); $itemPage->addAction($this->_('Delete'), 'pr.track.delete', 'delete-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 1); $itemPage->addAction($this->_('Undelete!'), 'pr.track.undelete', 'undelete-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 0); $itemPage->addAction($this->_('Check answers'), 'pr.track.answers', 'check-track-answers') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId); $itemPage->addAction($this->_('Check rounds'), 'pr.track.check', 'check-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 1, 'gtr_active', 1, 'gr2t_active', 1); $itemPage->addAction($this->_('Recalculate fields'), 'pr.track.check', 'recalc-fields') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 1, 'gtr_active', 1, 'gr2t_active', 1); $itemPage->addAction($this->_('Export track'), 'pr.track', 'export-track') ->setNamedParameters($params) ->addNamedParameters(\Gems_Model::RESPONDENT_TRACK, 'gr2t_id_respondent_track') ->setHiddenOrgId($orgId) ->setParameterFilter('can_edit', 1); $tkPage = $itemPage->addAction($this->_('Token'), 'pr.token', 'show') ->setNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter(\Gems_Model::ID_TYPE, 'token'); $trPage->addAction($this->_('Check all answers'), 'pr.track.answers', 'check-all-answers') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $trPage->addAction($this->_('Check all rounds'), 'pr.track.check', 'check-all-tracks') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $trPage->addAction($this->_('Recalculate all fields'), 'pr.track.check', 'recalc-all-fields') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $trPage = $rPage->addPage($this->_('Surveys'), 'pr.survey', 'token'); // Surveys overview $trPage->setNamedParameters($params) ->setHiddenOrgId($orgId) ->addAutofilterAction(); } $tkPage->addEditAction('pr.token.edit') ->setNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('grc_success', 1, \Gems_Model::ID_TYPE, 'token'); $tkPage->addAction($this->_('Correct answers'), 'pr.token.correct', 'correct') ->addNamedParameters(MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('is_completed', 1, 'grc_success', 1, Gems_Model::ID_TYPE, 'token'); $tkPage->addDeleteAction('pr.token.delete') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('grc_success', 1, \Gems_Model::ID_TYPE, 'token'); $tkPage->addAction($this->_('Undelete!'), 'pr.token.undelete', 'undelete') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('grc_success', 0, \Gems_Model::ID_TYPE, 'token'); $tkPage->addButtonOnly($this->_('Fill in'), 'pr.ask', 'ask', 'take') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('can_be_taken', 1, \Gems_Model::ID_TYPE, 'token'); $tkPage->addPdfButton($this->_('Print PDF'), 'pr.token.print') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('gsu_has_pdf', 1, \Gems_Model::ID_TYPE, 'token'); $tkPage->addAction($this->_('E-Mail now!'), 'pr.token.mail', 'email') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('can_be_taken', 1, 'can_email', 1, \Gems_Model::ID_TYPE, 'token'); $tkPage->addAction($this->_('Preview'), 'pr.project.questions', 'questions') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter(\Gems_Model::ID_TYPE, 'token'); $tkPage->addActionButton($this->_('Answers'), 'pr.token.answers', 'answer') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('gto_in_source', 1, \Gems_Model::ID_TYPE, 'token') ->set('target', \MUtil_Model::REQUEST_ID); $tkPage->addAction($this->_('(Re)check answers'), 'pr.token.answers', 'check-token-answers') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter(\Gems_Model::ID_TYPE, 'token'); $tkPage->addActionButton($this->_('Export answers'), 'pr.token.answers', 'answer-export') ->addNamedParameters(\MUtil_Model::REQUEST_ID, 'gto_id_token') ->setParameterFilter('is_completed', 1, \Gems_Model::ID_TYPE, 'token'); $rPage->addAction($this->_('Export archive'), 'pr.respondent.export-html', 'export-archive') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $mailLogPage = $rPage->addPage($this->_('Communication log'), 'pr.respondent-commlog', 'respondent-mail-log', 'index') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $mailLogPage->addAutofilterAction(); $mailLogPage->addShowAction(); // LOG CONTROLLER $logPage = $rPage->addPage($this->_('Activity log'), 'pr.respondent-log', 'respondent-log', 'index'); $logPage->setNamedParameters($params) ->setHiddenOrgId($orgId); $logPage->addAutofilterAction(); $logParams = $params + array(\Gems_Model::LOG_ITEM_ID => 'gla_id'); $logPage->addShowAction() ->setNamedParameters($logParams) ->setHiddenOrgId($orgId); $rPage->addDeleteAction('pr.respondent.delete') ->setNamedParameters($params) ->setParameterFilter('resp_deleted', 0) ->setHiddenOrgId($orgId); $rPage->addAction($this->_('Undelete!'), 'pr.respondent.undelete', 'undelete') ->setNamedParameters($params) ->setParameterFilter('resp_deleted', 1) ->setHiddenOrgId($orgId); /* Add respondent relations */ $relParams = $params + array('rid' => 'grr_id'); $relationsPage = $rPage->addPage($this->_('Relations'), 'pr.respondent.relation', 'respondent-relation', 'index') ->setNamedParameters($params) ->setHiddenOrgId($orgId); $relationsPage->addAutofilterAction(); $relationsPage->addCreateAction(); $relationsPage->addEditAction(); $relationsPage->addDeleteAction(); foreach ($relationsPage->getChildren() as $relation) { if (!in_array($relation->get('action'), array('autofilter', 'create'))) { $relation->setNamedParameters($relParams) ->setHiddenOrgId($orgId); } else { $relation->setNamedParameters($params) ->setHiddenOrgId($orgId); } } return $rPage; }
Shortcut function to create the respondent page. @param string $label Label for the container @return \Gems_Menu_MenuAbstract The new respondent page
entailment
public function getCurrentMenuList(\Zend_Controller_Request_Abstract $request, $parentLabel = null) { $controller = $request->getControllerName(); $action = $request->getActionName(); $menuList = $this->getMenuList(); if ($controller !== 'index') { $menuList->addByController($controller, 'index', $parentLabel); } foreach ($this->getCurrent()->getChildren() as $child) { if ($child instanceof \Gems_Menu_SubMenuItem) { $chAction = $child->get('action'); $chContr = $child->get('controller'); if (! ($controller == $chContr && $action == $chAction)) { $menuList->addByController($chContr, $chAction); } } } return $menuList; }
Menulist populated with current items @param \Zend_Controller_Request_Abstract $request @param $parentLabel @return \Gems_Menu_MenuList
entailment
public function loadDefaultMenu() { // MAIN RESPONDENTS ITEM $this->addRespondentPage($this->_('Respondents')); // MAIN CALENDAR ITEM $this->addCalendarPage($this->_('Calendar')); // MAIN PLANNING ITEM $this->addPlanPage($this->_('Overview')); // PROJECT INFO $this->addProjectPage($this->_('Project')); // SETUP CONTAINER $this->addGemsSetupContainer($this->_('Setup')); // TRACK BUILDER $this->addTrackBuilderMenu($this->_('Track Builder')); // EXPORT $this->addExportContainer($this->_('Export')); // IMPORT $this->addImportContainer($this->_('Import')); // OTHER ITEMS $this->addLogonOffToken(); // CONTACT MENU $this->addContactPage($this->_('Contact')); // Privileges not associated with menu item $this->addHiddenPrivilege('pr.organization-switch', $this->_( 'Grant access to all organization.' )); $this->addHiddenPrivilege('pr.plan.mail-as-application', $this->_( 'Grant right to impersonate the site when mailing.' )); $this->addHiddenPrivilege('pr.respondent.multiorg', $this->_( 'Display multiple organizations in respondent overview.' )); $this->addHiddenPrivilege('pr.episodes.rawdata', $this->_( 'Display raw data in Episodes of Care.' )); $this->addHiddenPrivilege('pr.respondent.result', $this->_( 'Display results in token overviews.' )); $this->addHiddenPrivilege('pr.respondent.select-on-track', $this->_( 'Grant checkboxes to select respondents on track status in respondent overview.' )); $this->addHiddenPrivilege('pr.respondent.show-deleted', $this->_( 'Grant checkbox to view deleted respondents in respondent overview.' )); $this->addHiddenPrivilege('pr.respondent.who', $this->_( 'Display staff member name in token overviews.' )); $this->addHiddenPrivilege('pr.staff.edit.all', $this->_( 'Grant right to edit staff members from all organizations.' )); $this->addHiddenPrivilege('pr.export.add-resp-nr', $this->_( 'Grant right to export respondent numbers with survey answers.' )); $this->addHiddenPrivilege('pr.export.gender-age', $this->_( 'Grant right to export gender and age information with survey answers.' )); $this->addHiddenPrivilege('pr.staff.see.all', $this->_( 'Display all organizations in staff overview.' )); $this->addHiddenPrivilege('pr.group.switch', $this->_( 'Grant right to switch groups.' )); $this->addHiddenPrivilege('pr.token.mail.freetext', $this->_( 'Grant right to send free text (i.e. non-template) email messages.' )); /* MD 20160826: We probably don't need this as it is under the projectinfopage //Changelog added as button only $this->addButtonOnly($this->_('Changelog'), 'pr.project-information.changelog', 'project-information','changelog'); */ $this->addPage(null, 'pr.cron.job', 'cron', 'index'); $this->addPage(null, 'pr.cron.job', 'cron', 'monitor'); $this->addPage(null, 'pr.cron.job', 'cron', 'test'); $this->addPage(null, null, 'email', 'index'); }
This is where we load the default menu, be very careful to overload this function as it makes upgrading a lot more difficult
entailment
public function render(\Zend_View_Abstract $view) { $request = $this->_getOriginalRequest(); if ($this->_onlyActiveBranchVisible) { $activePath = $this->_findPath($request); // \MUtil_Echo::r($activePath); $this->setBranchVisible($activePath); } $parameterSources[] = $request; if ($this->_menuParameters) { $parameterSources[] = $this->_menuParameters; } $source = new \Gems_Menu_ParameterCollector($parameterSources); // self::$verbose = true; $nav = $this->_toNavigationArray($source); // \MUtil_Echo::track($nav); $ul = $this->renderFirst(); $this->renderItems($ul, $nav, true); return $ul->render($view); }
Renders the element into a html string The $view is used to correctly encode and escape the output @param \Zend_View_Abstract $view @return string Correctly encoded and escaped html output
entailment
protected function renderItems(\MUtil_Html_ListElement $ul, array $items, $cascade) { foreach ($items as $item) { if (isset($item['visible'], $item['label']) && $item['visible'] && $item['label']) { $url = $item['params']; $url['controller'] = $item['controller']; $url['action'] = $item['action']; $url['RouteReset'] = true; $li = $ul->li(); if (isset($item['active']) && $item['active']) { $li->class = 'active'; } if (isset($item['liClass']) && $item['liClass']) { $li->appendAttrib('class', $item['liClass']); } $a = $li->a($url, $item['label']); if (isset($item['class'])) { $a->class = $item['class']; } if (isset($item['target'])) { $a->target = $item['target']; } if ($cascade && isset($item['pages']) && is_array($item['pages'])) { $this->renderItems($li->ul(array('class' => 'subnav '. $this->_menuUlClass)), $item['pages'], true); } } } }
Helper function to load the menu items to the html element. Allows overloading by sub classes. @param \MUtil_Html_ListElement $ul @param array $items @param boolean $cascade render nested items
entailment
public function toActiveBranchElement() { $request = $this->_getOriginalRequest(); $activePath = $this->_findPath($request); if (! $activePath) { return null; } $this->setBranchVisible($activePath); $activeItem = array_pop($activePath); if (! $activeItem instanceof \Gems_Menu_SubMenuItem) { return null; } // \MUtil_Echo::track($activeItem->get('label')); $parameterSources[] = $request; if ($this->_menuParameters) { $parameterSources[] = $this->_menuParameters; } $source = new \Gems_Menu_ParameterCollector($parameterSources); // self::$verbose = true; $nav = $this->_toNavigationArray($source); $ul = $this->renderFirst(); foreach ($nav as $item => $sub) { if ($sub['label'] === $activeItem->get('label')) { if (isset($sub['pages'])) { $this->renderItems($ul, $sub['pages'], true); } return $ul; } } return null; }
Renders the top level menu items into a html element @return \MUtil_Html_HtmlElement
entailment
public function toTopLevelElement() { $request = $this->_getOriginalRequest(); $activeItems = $this->_findPath($request); $this->setBranchVisible($activeItems); foreach ($activeItems as $activeItem) { if ($activeItem instanceof \Gems_Menu_SubMenuItem) { $activeItem->set('class', 'active'); } } $parameterSources[] = $request; if ($this->_menuParameters) { $parameterSources[] = $this->_menuParameters; } $source = new \Gems_Menu_ParameterCollector($parameterSources); $nav = $this->_toNavigationArray($source); // \MUtil_Echo::track($nav); $ul = $this->renderFirst(); $this->renderItems($ul, $nav, false); return $ul; }
Renders the top level menu items into a html element @return \MUtil_Html_HtmlElement
entailment
public function toZendNavigation(\Zend_Controller_Request_Abstract $request, $actionController = null) { if ($this->_onlyActiveBranchVisible) { $activePath = $this->_findPath($request); // \MUtil_Echo::r($activePath); $this->setBranchVisible($activePath); } $parameterSources = func_get_args(); if ($this->_menuParameters) { $parameterSources[] = $this->_menuParameters; } $source = new \Gems_Menu_ParameterCollector($parameterSources); // self::$verbose = true; $nav = new \Zend_Navigation($this->_toNavigationArray($source)); // \MUtil_Echo::track($this->_toNavigationArray($source), $nav); return $nav; }
Generates a \Zend_Navigation object from the current menu @param \Zend_Controller_Request_Abstract $request @param mixed $actionController @return \Zend_Navigation
entailment
public function addExport($data, $modelId = false) { $this->files = $this->getFiles(); $this->data = $data; $this->modelId = $modelId; if ($model = $this->getModel()) { if ($this->model->getMeta('nested', false)) { $this->rowsPerBatch = $this->nestedRowsPerBatch; } $totalRows = $this->getModelCount(); $this->addFile(); $this->addHeader($this->tempFilename . $this->fileExtension); $currentRow = 0; do { $filter['limit'] = array($this->rowsPerBatch, $currentRow); if ($this->batch) { $this->batch->addTask('Export_ExportCommand', $data['type'], 'addRows', $data, $modelId, $this->tempFilename, $filter); } else { $this->addRows($data, $modelId, $this->tempFilename, $filter); } $currentRow = $currentRow + $this->rowsPerBatch; } while ($currentRow < $totalRows); if ($this->batch) { $this->batch->addTask('Export_ExportCommand', $data['type'], 'addFooter', $this->tempFilename . $this->fileExtension, $modelId); $this->batch->setSessionVariable('files', $this->files); } else { $this->addFooter($this->tempFilename . $this->fileExtension, $modelId); $this->_session = new \Zend_Session_Namespace(__CLASS__); $this->_session->files = $this->files; } } }
Add an export command with specific details. Can be batched. COPIED from ExportAbstract to add $modelId to footer. @param array $data Data submitted by export form @param array $modelId Model Id when multiple models are passed
entailment
public function addRows($data, $modelId, $tempFilename, $filter) { $this->data = $data; $this->modelId = $modelId; $this->model = $this->getModel(); if ($this->model) { $this->model->setFilter($filter + $this->model->getFilter()); if ($this->batch) { $rowNumber = $this->batch->getSessionVariable('rowNumber'); $iteration = $this->batch->getSessionVariable('iteration'); } else { $this->_session = new \Zend_Session_Namespace(__CLASS__); $rowNumber = $this->_session->rowNumber; $iteration = $this->_session->iteration; } // Reset internal rownumber when we move to a new file if ($filter = $this->model->getFilter()) { if (array_key_exists('limit', $filter)) { if ($filter['limit'][1] == 0) { $rowNumber = 0; } } } if (empty($rowNumber)) { $rowNumber = 0; } if (empty($iteration)) { $iteration = 0; } $filename = $tempFilename . '_' . $iteration . $this->fileExtension; $rows = $this->model->load(); $exportName = $this->getName(); $writer = new XMLWriter(); $writer->openURI($filename); $writer->setIndent(true); if ($this->model->getMeta('nested', false)) { $nestedNames = $this->model->getMeta('nestedNames'); $rows = $this->addNestedRows($rows, $nestedNames); } foreach($rows as $row) { $this->addRowWithCount($row, $writer, $rowNumber); $rowNumber++; } } if ($this->batch) { $this->batch->setSessionVariable('rowNumber', $rowNumber); $this->batch->setSessionVariable('iteration', $iteration+1); } else { $this->_session->rowNumber = $rowNumber; $this->_session->iteration = $iteration++; } }
Add model rows to file. Can be batched @param array $data Data submitted by export form @param array $modelId Model Id when multiple models are passed @param string $tempFilename The temporary filename while the file is being written @param array $filter Filter (limit) to use
entailment
public function addRowWithCount($row, $writer, $rowNumber) { $exportRow = $this->filterRow($row); $labeledCols = $this->getLabeledColumns(); $exportRow = array_replace(array_flip($labeledCols), $exportRow); $writer->startElement('o'); $writer->writeAttribute('num', $rowNumber); if ($this->batch) { $stringSizes = $this->batch->getSessionVariable('stringSizes'); } else { $stringSizes = $this->_session->stringSizes; } foreach($labeledCols as $columnName) { $variableName = $this->model->get($columnName, 'variableName'); $type = $this->model->get($columnName, 'type'); if (($type == \MUtil_Model::TYPE_DATE || $type == \MUtil_Model::TYPE_DATETIME) && $exportRow[$columnName] !== null) { if (!empty($exportRow[$columnName])) { if ($exportRow[$columnName] instanceof \Zend_Date) { if ($type == \MUtil_Model::TYPE_DATE) { $exportRow[$columnName] = floor(($exportRow[$columnName]->getTimestamp() + 315619200) / 86400); } else { $exportRow[$columnName] = ($exportRow[$columnName]->getTimestamp() + 315619200) * 1000; } } else { if ($type == \MUtil_Model::TYPE_DATE) { $exportRow[$columnName] = floor((strtotime($exportRow[$columnName] . ' GMT') + 315619200) / 86400); } else { $exportRow[$columnName] = (strtotime($exportRow[$columnName] . ' GMT') + 315619200) * 1000 ; } } } } if ($type == \MUtil_Model::TYPE_STRING && !$this->model->get($columnName, 'multiOptions')) { $size = strlen($exportRow[$columnName]); if ((!isset($stringSizes[$variableName]) || ($stringSizes[$variableName] < $size)) && $size > 0) { $stringSizes[$variableName] = $size; if ($this->batch) { $this->batch->setSessionVariable('stringSizes', $stringSizes); } else { $this->_session->stringSizes = $stringSizes; } } } if ($multiOptions = $this->model->get($columnName, 'multiOptions')) { if ($exportRow[$columnName] !== null) { $numeric = true; $newValue = 0; $i=0; foreach($multiOptions as $key=>$value) { if (!is_numeric($key)) { $numeric = false; } if ($key == $exportRow[$columnName]) { $newValue = $i; } } if($numeric) { $newValue = $exportRow[$columnName]; $exportRow[$columnName] = $newValue; } else { $newMultiOptions = array_keys($multiOptions); $newValue = array_search($exportRow[$columnName], $newMultiOptions); $exportRow[$columnName] = $newValue; } } } $writer->startElement('v'); $writer->writeAttribute('varname', $variableName); if (is_array($exportRow[$columnName])) { $exportRow[$columnName] = join(', ', $exportRow[$columnName]); } $writer->text($exportRow[$columnName]); // End v $writer->endElement(); } // End o $writer->endElement(); }
Add a separate row to a file @param array $row a row in the model @param file $file The already opened file
entailment
public function addFooter($filename, $modelId = null) { $tempFilename = str_replace($this->fileExtension, '', $filename); $this->model = $this->getModel(); $this->modelId = $modelId; if ($this->batch) { $iteration = $this->batch->getSessionVariable('iteration'); } else { $this->_session = new \Zend_Session_Namespace(__CLASS__); $iteration = $this->_session->iteration; } $writer = new XMLWriter(); $writer->openURI($filename); $writer->setIndent(true); $writer->startDocument('1.0', 'UTF-8'); //Added padding comparable to xml output; $writer->startElement('dta'); $this->createHeaderFile($writer, $filename); $writer->startElement('data'); for($i=0;$i<$iteration;$i++) { $partFilename = $tempFilename . '_' . $i . $this->fileExtension; $data = file_get_contents($partFilename); $writer->writeRaw($data); unlink($partFilename); } $writer->endElement(); $writer->endElement(); // reset rowNumber if ($this->batch) { $this->batch->setSessionVariable('rowNumber', 0); $this->batch->setSessionVariable('iteration', 0); $this->batch->setSessionVariable('stringSizes', array()); } else { $this->_session->rowNumber = 0; $this->_session->iteration = 0; $this->_session->stringSizes = array(); } }
Add a footer to a specific file @param string $filename The temporary filename while the file is being written
entailment
protected function preprocessModel() { parent::preprocessModel(); $labeledCols = $this->getLabeledColumns(); $newColNames = array(); foreach($labeledCols as $columnName) { $options = array(); $this->model->remove($columnName, 'dateFormat'); $type = $this->model->get($columnName, 'type'); switch ($type) { case \MUtil_Model::TYPE_DATE: break; case \MUtil_Model::TYPE_DATETIME: break; case \MUtil_Model::TYPE_TIME: break; case \MUtil_Model::TYPE_NUMERIC: break; case \MUtil_Model::TYPE_CHILD_MODEL; 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); if ($multiOptions = $this->model->get($columnName, 'multiOptions')) { $keys = array_keys($multiOptions); if ($keys == array('Y', 'N') || $keys == array('Y', '')) { $multiOptions = array_reverse($multiOptions); $this->model->set($columnName, 'multiOptions', $multiOptions); } } // A variable name in stata has a max of 32 characters. If it's longer, get a unique shorter version. $colName = $this->fixName($columnName); if (strlen($colName) > 32) { $colName = substr($colName, 0, 32); $i = 1; while (isset($newColNames[$colName])) { $varLength = 32 - strlen($i); $colName = substr($colName, 0, $varLength) . $i; } } $newColNames[$colName] = true; $this->model->set($columnName, 'variableName', $colName); } }
Preprocess the model to add specific options
entailment
public function getChanges(array $context, $new) { if (isset($context['gsf_id_organization'])) { $org = $this->loader->getOrganization($context['gsf_id_organization']); if ($org instanceof \Gems_User_Organization) { return ['gul_user_class' => ['multiOptions' => $org->getAllowedUserClasses()]]; } } }
Returns the changes that must be made in an array consisting of <code> array( field1 => array(setting1 => $value1, setting2 => $value2, ...), field2 => array(setting3 => $value3, setting4 => $value4, ...), </code> By using [] array notation in the setting name you can append to existing values. Use the setting 'value' to change a value in the original data. When a 'model' setting is set, the workings cascade. @param array $context The current data this object is dependent on @param boolean $new True when the item is a new record not yet saved @return array name => array(setting => value)
entailment
public function getFieldInfo(\MUtil_Model_ModelAbstract $model) { // Many definitions use load transformers $model->setMeta(\MUtil_Model_ModelAbstract::LOAD_TRANSFORMER, true); return $this->fieldsDefinition->getDataModelSettings(); }
If the transformer add's fields, these should be returned here. Called in $model->AddTransformer(), so the transformer MUST know which fields to add by then (optionally using the model for that). @param \MUtil_Model_ModelAbstract $model The parent model @return array Of filedname => set() values
entailment
public function transformLoad(\MUtil_Model_ModelAbstract $model, array $data, $new = false, $isPostData = false) { if ($isPostData) { return $data; } $empty = false; foreach ($data as $key => $row) { if (isset($row[$this->respTrackIdField]) && $row[$this->respTrackIdField]) { $fields = $this->fieldsDefinition->getFieldsDataFor($row[$this->respTrackIdField]); } else { if (! $empty) { $empty = $this->getEmptyFieldsData(); } $fields = $empty; } //$data[$key] = array_merge($row, $fields); $data[$key] = array_replace($row, $fields); //$data[$key] = $row $fields; } return $data; }
The transform function performs the actual transformation of the data and is called after the loading of the data in the source model. @param \MUtil_Model_ModelAbstract $model The parent model @param array $data Nested array @param boolean $new True when loading a new item @param boolean $isPostData With post data, unselected multiOptions values are not set so should be added @return array Nested array containing (optionally) transformed data
entailment
public function transformRowAfterSave(\MUtil_Model_ModelAbstract $model, array $row) { if (isset($row[$this->respTrackIdField]) && $row[$this->respTrackIdField]) { if (! $this->tracker) { $this->tracker = $this->loader->getTracker(); } if ((! $this->respTrackIdField) || ($this->respTrackIdField == 'gr2t_id_respondent_track')) { // Load && refresh when using standard gems__respondent2track data $respTrack = $this->tracker->getRespondentTrack($row); } else { $respTrack = $this->tracker->getRespondentTrack($row[$this->respTrackIdField]); } // We use setFieldDate instead of saveFields() since it handles updating related values // like dates derived from appointments $before = $respTrack->getFieldData(); // Get old so we can detect changes $after = $respTrack->setFieldData($row); $row = $after + $row; $changed = ($before !== $after); if ($changed && (! $model->getChanged())) { $model->addChanged(1); } } // No changes return $row; }
This transform function performs the actual save (if any) of the transformer data and is called after the saving of the data in the source model. @param \MUtil_Model_ModelAbstract $model The parent model @param array $row Array containing row @return array Row array containing (optionally) transformed data
entailment
protected function addUserLogin(\Gems_Model_JoinModel $model, $loginField, $organizationField) { $model->addTable( 'gems__user_logins', array($loginField => 'gul_login', $organizationField => 'gul_id_organization'), 'gul', \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_INSERT | \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_UPDATE | \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_DELETE ); if ($model->has('gul_enable_2factor') && $model->has('gul_two_factor_key')) { $model->addColumn( new \Zend_Db_Expr("CASE WHEN gul_enable_2factor IS NULL THEN -1 WHEN gul_enable_2factor = 1 AND gul_two_factor_key IS NULL THEN 1 WHEN gul_enable_2factor = 1 AND gul_two_factor_key IS NOT NULL THEN 2 ELSE 0 END"), 'has_2factor' ); } }
Link the model to the user_logins table. @param \Gems_Model_JoinModel $model @param string $loginField Field that links to login name field. @param string $organizationField Field that links to the organization field.
entailment
public function createGemsUserId($value, $isNew = false, $name = null, array $context = array()) { if ($value) { return $value; } $creationTime = new \MUtil_Db_Expr_CurrentTimestamp(); do { $out = mt_rand(1, 9); for ($i = 1; $i < $this->userIdLen; $i++) { $out .= mt_rand(0, 9); } // Make it a number $out = intval($out); try { if (0 === $this->db->insert('gems__user_ids', array('gui_id_user' => $out, 'gui_created' => $creationTime))) { $out = null; } } catch (\Zend_Db_Exception $e) { $out = null; } } while (null === $out); return $out; }
Create a Gems project wide unique user id @see \Gems_Model_RespondentModel @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 int
entailment
public function getCommLogModel($detailed) { $model = $this->_loadClass('CommLogModel', true); $model->applySetting($detailed); return $model; }
Load the comm log model @param boolean $detailed True when the current action is not in $summarizedActions. @return \Gems\Model\CommLogModel
entailment
public function getRespondentModel($detailed) { static $isDetailed; static $model; if ($model && ($isDetailed === $detailed)) { return $model; } $isDetailed = $detailed; $model = $this->createRespondentModel(); if ($detailed) { $model->applyDetailSettings(); } else { $model->applyBrowseSettings(); } return $model; }
Load project specific respondent model or general Gems model otherwise @param boolean $detail When true more information needed for individual item display is added to the model. @return \Gems_Model_RespondentModel
entailment
public function getStaffModel($addLogin = true) { $model = $this->_loadClass('StaffModel', true); if ($addLogin) { $this->addUserLogin($model, 'gsf_login', 'gsf_id_organization'); } $this->setAsGemsUserId($model, 'gsf_id_user'); return $model; }
Load the staffmodel @param boolean $addLogin Add the login tables to the model @return \Gems_Model_StaffModel
entailment
public function setAsGemsUserId(\MUtil_Model_DatabaseModelAbstract $model, $idField) { // Make sure field is added to save when not there $model->setAutoSave($idField); // Make sure the fields get a userid when empty $model->setOnSave($idField, array($this, 'createGemsUserId')); }
Set a field in this model as a gems unique user id @param \MUtil_Model_DatabaseModelAbstract $model @param string $idField Field that uses global id.
entailment
public static function setChangeFieldsByPrefix(\MUtil_Model_DatabaseModelAbstract $model, $prefix, $userid = null) { $changed_field = $prefix . '_changed'; $changed_by_field = $prefix . '_changed_by'; $created_field = $prefix . '_created'; $created_by_field = $prefix . '_created_by'; foreach (array($changed_field, $changed_by_field, $created_field, $created_by_field) as $field) { $model->set($field, 'elementClass', 'none'); } $model->setOnSave($changed_field, new \MUtil_Db_Expr_CurrentTimestamp()); $model->setSaveOnChange($changed_field); $model->setOnSave($created_field, new \MUtil_Db_Expr_CurrentTimestamp()); $model->setSaveWhenNew($created_field); if (! $userid && self::$currentUserId) { $userid = self::$currentUserId; } if (! $userid) { $escort = \GemsEscort::getInstance(); if ($escort) { $currentUser = $escort->currentUser; if ($currentUser instanceof Gems_User_User) { // During some unit tests this will be null $userid = $currentUser->getUserId(); } if (!$userid) { $userid = 1; } } } if ($userid) { $model->setOnSave($changed_by_field, $userid); $model->setSaveOnChange($changed_by_field); $model->setOnSave($created_by_field, $userid); $model->setSaveWhenNew($created_by_field); } }
Function that automatically fills changed, changed_by, created and created_by fields with a certain prefix. @param \MUtil_Model_DatabaseModelAbstract $model @param string $prefix Three letter code @param int $userid Gems user id
entailment
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $br = \MUtil_Html::create('br'); $tData = $this->util->getTokenData(); // Add link to patient to overview $menuItems = $this->findMenuItems('respondent', 'show'); if ($menuItems) { $menuItem = reset($menuItems); if ($menuItem instanceof \Gems_Menu_SubMenuItem) { $href = $menuItem->toHRefAttribute($bridge); if ($href) { $aElem = new \MUtil_Html_AElement($href); $aElem->setOnEmpty(''); // Make sure org is known $model->get('gr2o_id_organization'); $model->set('gr2o_patient_nr', 'itemDisplay', $aElem); $model->set('respondent_name', 'itemDisplay', $aElem); } } } $model->set('gto_id_token', 'formatFunction', 'strtoupper'); $bridge->setDefaultRowClass(\MUtil_Html_TableElement::createAlternateRowClass('even', 'even', 'odd', 'odd')); $tr1 = $bridge->tr(); $tr1->appendAttrib('class', $bridge->row_class); $tr1->appendAttrib('title', $bridge->gto_comment); $bridge->addColumn( $this->createInfoPlusCol($bridge), ' ')->rowspan = 2; // Space needed because TableElement does not look at rowspans $bridge->addSortable('gto_valid_from'); $bridge->addSortable('gto_valid_until'); $bridge->addSortable('gto_id_token'); // $bridge->addSortable('gto_mail_sent_num', $this->_('Contact moments'))->rowspan = 2; $model->set('gto_round_description', 'tableDisplay', 'smallData'); $bridge->addMultiSort('gsu_survey_name', 'gto_round_description'); $bridge->addMultiSort('ggp_name', [$this->createActionButtons($bridge)]); $tr2 = $bridge->tr(); $tr2->appendAttrib('class', $bridge->row_class); $tr2->appendAttrib('title', $bridge->gto_comment); $bridge->addSortable('gto_mail_sent_date'); $bridge->addSortable('gto_completion_time'); $bridge->addSortable('gto_mail_sent_num', $this->_('Contact moments')); if ($this->multiTracks) { $model->set('gr2t_track_info', 'tableDisplay', 'smallData'); $bridge->addMultiSort('gtr_track_name', 'gr2t_track_info'); } else { $bridge->addSortable('gr2t_track_info'); } $bridge->addSortable('assigned_by'); }
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 _loadAllTraversable() { $data = parent::_loadAllTraversable(); $dataExportWhitelist = $this->getDataExportWhitelist(); foreach($data as $key=>$row) { if (in_array($row['group'], $this->excludeGroups)) { unset($data[$key]); continue; } $data[$key]['exportTable'] = true; $data[$key]['respondentData'] = true; if (in_array($row['name'], $dataExportWhitelist)) { $data[$key]['respondentData'] = false; } } return $data; }
An ArrayModel assumes that (usually) all data needs to be loaded before any load action, this is done using the iterator returned by this function. @return \Traversable Return an iterator over or an array of all the rows in this object
entailment
public function afterRegistry() { parent::afterRegistry(); if (empty($this->trackId)) { throw new Gems_Exception_Coding('Provide a trackId to this snippet!'); } $model = $this->getModel(); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
protected function createModel() { if (!$this->_model instanceof \MUtil_Model_SelectModel) { $trackId = $this->trackId; $db = $this->db; $select = $db->select()->distinct()->from('gems__rounds', ['gro_round_description', 'gro_round_description'])->where('gro_id_track = ?', $trackId); $rounds = $this->db->fetchPairs($select); $fields = [ 'gems__surveys.gsu_survey_name', 'round_order' => new \Zend_Db_Expr('min(gro_id_order)') ]; foreach ($rounds as $round) { $fields[$round] = new \Zend_Db_Expr('max(case when (gro_round_description = ' . $db->quote($round) . ' AND gro_condition IS NULL) then "X" when gro_round_description = ' . $db->quote($round) . ' then "C" else NULL end)'); } $fields['filler'] = new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)'); $sql = $this->db->select()->from('gems__rounds', []) ->join('gems__surveys', 'gro_id_survey = gsu_id_survey', []) ->joinLeft('gems__track_fields', 'gro_id_relationfield = gtf_id_field AND gtf_field_type = "relation"', array()) ->joinLeft('gems__groups', 'gsu_id_primary_group = ggp_id_group', array()) ->where('gro_active = 1') //Only active rounds ->where('gro_id_track = ?', $trackId) ->group(['gro_id_survey', 'filler']) ->columns($fields); $model = new \MUtil_Model_SelectModel($sql, 'track-plan'); //$model->setKeys(array('gsu_survey_name')); $model->resetOrder(); $model->set('filler', 'label', $this->_('Filler')); $model->set('gsu_survey_name', 'label', $this->_('Survey')); foreach ($rounds as $round) { $model->set($round, 'label', $round); } $this->_model = $model; } return $this->_model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function getActiveOrganizationId() { $request = $this->getRequest(); if ($request->isPost()) { $orgId = parent::getActiveOrganizationId(); $topId = $request->getParam($this->topOrganizationFieldName); $children = $this->getChildOrganizations($topId); if ($orgId && isset($children[$orgId])) { return $orgId; } return $topId; } }
Get the organization id that has been currently entered @return int
entailment
public function getChildOrganizations($parentId = null) { static $children; if (is_null($parentId)) { return array(); } if (! isset($children[$parentId])) { $organizations = $this->db->fetchPairs( 'SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active=1 AND gor_has_login=1 AND (gor_accessible_by LIKE ' . $this->db->quote('%:' . $parentId . ':%') . ' OR gor_id_organization = ' . $this->db->quote($parentId) . ') ORDER BY gor_name'); natsort($organizations); $children[$parentId] = $organizations; } return $children[$parentId]; }
Return array of organizations that are a child of the given parentId @param int $parentId @return array
entailment
public function getCurrentOrganizationId() { $userLoader = $this->loader->getUserLoader(); if ($this->getElement($this->organizationFieldName) instanceof \Zend_Form_Element_Hidden) { // Url determines organization first when there is only one organization // and thus the element is of class hidden if ($orgId = $userLoader->getOrganizationIdByUrl()) { $this->_organizationFromUrl = true; $userLoader->getCurrentUser()->setCurrentOrganization($orgId); return $orgId; } } $request = $this->getRequest(); if ($request->isPost() && ($orgId = $request->getParam($this->organizationFieldName))) { return $orgId; } $curOrg = $userLoader->getCurrentUser()->getCurrentOrganizationId(); $orgs = $this->getChildOrganizations($this->getCurrentTopOrganizationId()); if (isset($orgs[$curOrg])) { return $curOrg; } $orgIds = array_keys($orgs); $firstId = reset($orgIds); return $firstId; }
Returns the organization id that should currently be used for this form. @return int Returns the current organization id, if any
entailment
public function getCurrentTopOrganizationId() { $userLoader = $this->loader->getUserLoader(); // Url determines organization first. if ($orgId = $userLoader->getOrganizationIdByUrl()) { $this->_organizationFromUrl = true; return ' '; } $request = $this->getRequest(); if ($request->isPost() && ($orgId = $request->getParam($this->topOrganizationFieldName))) { \Gems_Cookies::set('gems_toporganization', $orgId); return $orgId; } else { $orgs = array_keys($this->getTopOrganizations()); $firstId = reset($orgs); return \Gems_Cookies::get($this->getRequest(), 'gems_toporganization', $firstId); } }
Returns the top organization id that should currently be used for this form. @return int Returns the current organization id, if any
entailment
public function getOrganizationElement() { $element = $this->getElement($this->organizationFieldName); $orgId = $this->getCurrentOrganizationId(); $parentId = $this->getParentId(); $childOrgs = $this->getChildOrganizations($parentId); if (!empty($childOrgs)) { if (count($childOrgs) == 1) { $element = new \Zend_Form_Element_Hidden($this->organizationFieldName); $this->addElement($element); if (! $this->_organizationFromUrl) { $orgIds = array_keys($childOrgs); $orgId = reset($orgIds); } $element->setValue($orgId); $this->getRequest()->setPost($this->organizationFieldName, $orgId); } else { $element = new \Zend_Form_Element_Select($this->organizationFieldName); $element->setLabel($this->childOrganizationDescription); $element->setRegisterInArrayValidator(true); $element->setRequired(true); $element->setMultiOptions($childOrgs); if ($this->organizationMaxLines > 1) { $element->setAttrib('size', min(count($childOrgs) + 1, $this->organizationMaxLines)); } $this->addElement($element); $element->setValue($orgId); } $this->addElement($element); } return $element; }
Returns/sets an element for determining / selecting the organization. Depends on the top-organization @return \Zend_Form_Element_Xhtml
entailment
public function getTopOrganizations() { try { $organizations = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active=1 AND gor_has_login=1 AND (gor_accessible_by IS NULL OR gor_accessible_by = "::") ORDER BY gor_name'); } catch (\Exception $e) { try { // 1.4 fallback $organizations = $this->db->fetchPairs('SELECT gor_id_organization, gor_name FROM gems__organizations WHERE gor_active=1 AND gor_accessible_by IS NULL ORDER BY gor_name'); } catch (\Exception $e) { $organizations = array(); } } natsort($organizations); return $organizations; }
Return a list of organizations that are considered top-organizations, in this case organizations that are not accessible by others as they are considered the children of the top organizations. Feel free to modify to suit your needs. @return array
entailment
public function getTopOrganizationElement() { $element = $this->getElement($this->topOrganizationFieldName); $orgId = $this->getCurrentTopOrganizationId(); $orgs = $this->getTopOrganizations(); $hidden = $this->_organizationFromUrl || (count($orgs) < 2); if ($this->_organizationFromUrl) { return null; } if ($hidden) { if (! $element instanceof \Zend_Form_Element_Hidden) { $element = new \Zend_Form_Element_Hidden($this->topOrganizationFieldName); $this->addElement($element); } $orgIds = array_keys($orgs); $orgId = reset($orgIds); $element->setValue($orgId); } elseif (! $element instanceof \Zend_Form_Element_Select) { $element = new \Zend_Form_Element_Select($this->topOrganizationFieldName); $element->setLabel($this->topOrganizationDescription); $element->setRegisterInArrayValidator(true); $element->setRequired(true); $element->setMultiOptions($orgs); $element->setAttrib('onchange', 'this.form.submit();'); if ($this->organizationMaxLines > 1) { $element->setAttrib('size', min(count($orgs) + 1, $this->organizationMaxLines)); } $element->setValue($orgId); } $this->addElement($element); return $element; }
Returns/sets an element for determining / selecting the top-organization. @return null|\Zend_Form_Element_Select
entailment
public function loadDefaultElements() { // If not already set, set some defaults for organization elements if (is_null($this->topOrganizationDescription)) { $this->topOrganizationDescription = $this->translate->_('Organization'); } if (is_null($this->childOrganizationDescription)) { $this->childOrganizationDescription = $this->translate->_('Department'); } $this->getTopOrganizationElement(); parent::loadDefaultElements(); return $this; }
Load the elements, starting with the extra top organization element and continue with the other elements like in the standard login form @return \Gems_User_Form_LayeredLoginForm
entailment