sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function setLevel($context, $level = null, $force = false) { if (!is_null($level) && $this->_info->$context != $level && ($force || $this->_info->$context < $level)) { $this->_info->$context = $level; $writer = new \Zend_Config_Writer_Ini(); $writer->write($this->upgradeFile, $this->_info); } }
Set the upgrade level for the given $context to a certain level Will only update when the $level is higher than the achieved level, unless when $force = true when it will always update. @param string $context @param int $level @param boolean $force
entailment
protected function addAnswersToModel() { $transformer = new AddAnswersTransformer($this->survey, $this->source); $this->addTransformer($transformer); }
Does the real work @return void
entailment
public function andReceptionCodes($fields = '*') { $this->sql_select->join('gems__reception_codes', 'gems__tokens.gto_reception_code = grc_id_reception_code', $fields); // Some queries use multiple token tables $expr = str_replace('gto_', 'gems__tokens.gto_', (string) $this->util->getTokenData()->getStatusExpression()); $this->sql_select->columns( ['token_status' => new \Zend_Db_Expr($expr)], 'gems__tokens' ); return $this; }
Add reception codes and token status calculation @param string|array $fields @return \Gems_Tracker_Token_TokenSelect
entailment
public function andRespondentTracks($fields = '*', $groupBy = false) { $this->sql_select->join('gems__respondent2track', 'gto_id_respondent_track = gr2t_id_respondent_track', $fields); if ($groupBy && is_array($fields)) { $this->sql_select->group($fields); } return $this; }
Add Respondent Track info to the select statement @param string|array $fields @param boolean $groupBy Optional, add these fields to group by statement @return \Gems_Tracker_Token_TokenSelect
entailment
public function forNextTokenId($tokenId) { $this->sql_select->join('gems__tokens as ct', 'gems__tokens.gto_id_respondent_track = ct.gto_id_respondent_track AND gems__tokens.gto_id_token != ct.gto_id_token AND ((gems__tokens.gto_round_order < ct.gto_round_order) OR (gems__tokens.gto_round_order = ct.gto_round_order AND gems__tokens.gto_created < ct.gto_created))', array()); $this->sql_select ->where('ct.gto_id_token = ?', $tokenId) ->order('gems__tokens.gto_round_order DESC') ->order('gems__tokens.gto_created DESC'); return $this; }
Select the token before the current token @param string|array $fields @return \Gems_Tracker_Token_TokenSelect
entailment
public function forPreviousTokenId($tokenId) { $this->sql_select->join('gems__tokens as ct', 'gems__tokens.gto_id_respondent_track = ct.gto_id_respondent_track AND gems__tokens.gto_id_token != ct.gto_id_token AND ((gems__tokens.gto_round_order > ct.gto_round_order) OR (gems__tokens.gto_round_order = ct.gto_round_order AND gems__tokens.gto_created > ct.gto_created))', array()); $this->sql_select ->where('ct.gto_id_token = ?', $tokenId) ->order('gems__tokens.gto_round_order') ->order('gems__tokens.gto_created'); return $this; }
Select the token before the current token @param string|array $fields @return \Gems_Tracker_Token_TokenSelect
entailment
public function forRespondent($respondentId, $organizationId = null) { if (null !== $respondentId) { $this->sql_select->where('gto_id_respondent = ?', $respondentId); } if (null !== $organizationId) { $this->sql_select->where('gto_id_organization = ?', $organizationId); } return $this; }
Select only a specific respondent @param string $respondentId @param string $organizationId Optional @return \Gems_Tracker_Token_TokenSelect
entailment
public function forWhere($cond, $bind = null) { $this->sql_select->where($cond, $bind); return $this; }
For adding generic where statements @param string $cond SQL Where condition. @param mixed $bind optional bind values @return \Gems_Tracker_Token_TokenSelect
entailment
public function onlyActive($recentCheck = false) { $this->sql_select ->where('gto_in_source = ?', 1) ->where('gto_completion_time IS NULL'); if ($recentCheck) { $this->sql_select->where('gto_start_time > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY)'); //$this->sql_select->where('(gto_valid_until IS NULL OR gto_valid_until > CURRENT_TIMESTAMP)'); } return $this; }
Select only active tokens Active is token already in surveyor and completiondate is null @param boolean $recentCheck Check only tokens with recent gto_start_time's @return \Gems_Tracker_Token_TokenSelect
entailment
public function render($content) { $element = $this->getElement(); $view = $element->getView(); if (null === $view) { return $content; } $jQueryParams = $this->getJQueryParams(); //Combine element attribs and decorator options!! $attribs = array_merge($this->getAttribs(), $this->getOptions()); $helper = $this->getHelper(); $id = $element->getId() . '-container'; return $view->$helper($id, $jQueryParams, $attribs); }
Render an jQuery UI Widget element using its associated view helper Determine view helper from 'helper' option, or, if none set, from the element type. Then call as helper($element->getName(), $element->getValue(), $element->getAttribs()) @param string $content @return string @throws \Zend_Form_Decorator_Exception if element or view are not registered
entailment
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { // \MUtil_Model::$verbose = true; // // Initiate data retrieval for stuff needed by links $bridge->gr2o_patient_nr; $bridge->gr2o_id_organization; $bridge->gr2t_id_respondent_track; $HTML = \MUtil_Html::create(); $roundIcon[] = \MUtil_Lazy::iif($bridge->gto_icon_file, \MUtil_Html::create('img', array('src' => $bridge->gto_icon_file, 'class' => 'icon')), \MUtil_Lazy::iif($bridge->gro_icon_file, \MUtil_Html::create('img', array('src' => $bridge->gro_icon_file, 'class' => 'icon')))); $bridge->addMultiSort('gsu_survey_name', $roundIcon); $bridge->addSortable('ggp_name'); $bridge->addSortable('calc_used_date', null, $HTML->if($bridge->is_completed, 'disabled date', 'enabled date')); $bridge->addSortable('gto_changed'); $bridge->addSortable('assigned_by', $this->_('Assigned by')); // If we are allowed to see the result of the survey, show them if ($this->currentUser->hasPrivilege('pr.respondent.result') && (! $this->currentUser->isFieldMaskedWhole('gto_result'))) { $bridge->addSortable('gto_result', $this->_('Score'), 'date'); } $bridge->useRowHref = false; $actionLinks[] = $this->createMenuLink($bridge, 'track', 'answer'); $actionLinks[] = array( $bridge->ggp_staff_members->if( $this->createMenuLink($bridge, 'ask', 'take'), $bridge->calc_id_token->strtoupper() ), 'class' => $bridge->ggp_staff_members->if(null, $bridge->calc_id_token->if('token'))); // calc_id_token is empty when the survey has been completed // Remove nulls $actionLinks = array_filter($actionLinks); if ($actionLinks) { $bridge->addItemLink($actionLinks); } $this->addTokenLinks($bridge); }
Adds columns from the model to the bridge that creates the browse table. Overrule this function to add different columns to the browse table, without having to recode the core table building code. @param \MUtil_Model_Bridge_TableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
protected function createModel() { $model = parent::createModel(); $translated = $this->util->getTranslated(); $model->set('calc_used_date', 'formatFunction', $translated->formatDateNever, 'tdClass', 'date'); $model->set('gto_changed', 'dateFormat', 'dd-MM-yyyy HH:mm:ss', 'tdClass', 'date'); return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function hasHtmlOutput() { if ($this->menu) { $default = $this->project->getDefaultTrackId(); if ($default) { if ($this->respondent->getReceptionCode()->isSuccess()) { $track = $this->loader->getTracker()->getTrackEngine($default); if ($track->isUserCreatable()) { $list = $this->menu->getMenuList() ->addByController('track', 'create', sprintf($this->_('Add %s track to this respondent'), $track->getTrackName()) ) ->addParameterSources( array( \Gems_Model::TRACK_ID => $default, 'gtr_id_track' => $default, 'track_can_be_created' => 1, ), $this->request ); $this->onEmpty = $list->getActionLink('track', 'create'); } } } if (! $this->onEmpty) { if ($this->respondent->getReceptionCode()->isSuccess()) { $list = $this->menu->getMenuList() ->addByController('track', 'show-track', $this->_('Add a track to this respondent')) ->addParameterSources($this->request); $this->onEmpty = $list->getActionLink('track', 'show-track'); } else { $this->onEmpty = \MUtil_Html::create('em', $this->_('No valid tokens found')); } } } return 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 _getGemsSurveysForSynchronisation() { $select = $this->_gemsDb->select(); $select->from('gems__surveys', array('gsu_id_survey', 'gsu_surveyor_id')) ->where('gsu_id_source = ?', $this->getId()) ->order('gsu_surveyor_id'); return $this->_gemsDb->fetchPairs($select); }
Returns all surveys for synchronization @return array Pairs gemsId => sourceId
entailment
protected function _getTokenFromSqlWhere($from, $fieldName) { $lsDb = $this->getSourceDatabase(); $tokField = $lsDb->quoteIdentifier($fieldName); foreach (str_split($from) as $check) { $checks[] = 'LOCATE(' . $lsDb->quote($check) . ', ' . $tokField . ')'; } return '(' . implode(' OR ', $checks) . ')'; }
Creates a where filter statement for tokens that do not have a correct name and are in a tokens table @param string $from The tokens that should not occur @param string $fieldName Name of database field to use @return string
entailment
protected function _getTokenFromToSql($from, $to, $fieldName) { $lsDb = $this->getSourceDatabase(); if ($from) { // Build the sql statement using recursion return 'REPLACE(' . $this->_getTokenFromToSql(substr($from, 1), substr($to, 1), $fieldName) . ', ' . $lsDb->quote($from[0]) . ', ' . $lsDb->quote($to[0]) . ')'; } else { return $lsDb->quoteIdentifier($fieldName); } }
Creates a SQL update statement for tokens that do not have a correct name and are in a tokens table. @param string $from The tokens that should not occur @param string $to The tokens that replace them @param string $fieldName Name of database field to use @return string
entailment
protected function _updateGemsSurveyExists(array $surveyorSids, $userId) { $sqlWhere = 'gsu_id_source = ' . $this->_gemsDb->quote($this->getId()) . ' AND (gsu_status IS NULL OR gsu_active = 1 OR gsu_surveyor_active = 1) AND gsu_surveyor_id NOT IN (' . implode(', ', $surveyorSids) . ')'; // Fixed values $data['gsu_active'] = 0; $data['gsu_surveyor_active'] = 0; $data['gsu_status'] = 'Survey was removed from source.'; $data['gsu_changed'] = new \MUtil_Db_Expr_CurrentTimestamp(); $data['gsu_changed_by'] = $userId; $this->_gemsDb->update('gems__surveys', $data, $sqlWhere); return $this->_gemsDb->fetchPairs('SELECT gsu_id_survey, gsu_survey_name FROM gems__surveys WHERE ' . $sqlWhere); }
This helper function updates the surveys in the gems_surveys table that no longer exist in in the source and returns a list of their names. @param array $surveyorSids The gsu_surveyor_id's that ARE in the source @param int $userId Id of the user who takes the action (for logging) @return array The names of the surveys that no longer exist
entailment
protected function _updateSource(array $values, $userId) { if ($this->tracker->filterChangesOnly($this->_sourceData, $values)) { if (\Gems_Tracker::$verbose) { $echo = ''; foreach ($values as $key => $val) { $echo .= $key . ': ' . $this->_sourceData[$key] . ' => ' . $val . "\n"; } \MUtil_Echo::r($echo, 'Updated values for ' . $this->getId()); } if (! isset($values['gso_changed'])) { $values['gso_changed'] = new \MUtil_Db_Expr_CurrentTimestamp(); } if (! isset($values['gso_changed_by'])) { $values['gso_changed_by'] = $userId; } // Update values in this object $this->_sourceData = $values + $this->_sourceData; // return 1; return $this->_gemsDb->update('gems__sources', $values, array('gso_id_source = ?' => $this->getId())); } else { return 0; } }
Updates this source, both in the database and in memory. @param array $values The values that this source should be set to @param int $userId The current user @return int 1 if data changed, 0 otherwise
entailment
protected function addDatabasePrefix($tableName, $addDatabaseName = true) { return ($addDatabaseName && $this->_sourceData['gso_ls_database'] ? $this->_sourceData['gso_ls_database'] . '.' : '') . $this->_sourceData['gso_ls_table_prefix'] . $tableName; }
Adds database (if needed) and tablename prefix to the table name @param return $tableName @param boolean $addDatabaseName Optional, when true (= default) and there is a database name then it is prepended to the name. @return string
entailment
protected function filterLimitOffset(&$filter, $select) { $limit = null; $offset = null; if (array_key_exists('limit', $filter)) { $limit = (int) $filter['limit']; unset($filter['limit']); } if (array_key_exists('offset', $filter)) { $offset = (int) $filter['offset']; unset($filter['offset']); } $select->limit($limit, $offset); }
Extract limit and offset from the filter and add it to a select @param array $filter @param \Zend_Db_Select $select
entailment
public function getRawTokenAnswerRowsCount(array $filter, $surveyId, $sourceSurveyId = null) { $answers = $this->getRawTokenAnswerRows($filter, $surveyId, $sourceSurveyId); return count($answers); }
Returns the recordcount for a given filter Abstract implementation is not efficient, sources should handle this as efficient as possible. @param array $filter filter array @param int $surveyId Gems Survey Id @param string $sourceSurveyId Optional Survey Id used by source @return int
entailment
public function getSourceDatabase() { if (! $this->_sourceDb) { if ($dbConfig['dbname'] = $this->_sourceData['gso_ls_database']) { // Default config values from gemsDb $gemsConfig = $this->_gemsDb->getConfig(); $gemsName = $gemsConfig['dbname']; if (($dbConfig['dbname'] != $gemsName) && ($adapter = $this->_sourceData['gso_ls_adapter'])) { //If upgrade has run and we have a 'charset' use it if (array_key_exists('gso_ls_charset', $this->_sourceData)) { $dbConfig['charset'] = $this->_sourceData['gso_ls_charset'] ? $this->_sourceData['gso_ls_charset'] : $gemsConfig['charset']; } $dbConfig['host'] = $this->_sourceData['gso_ls_dbhost'] ? $this->_sourceData['gso_ls_dbhost'] : $gemsConfig['host']; if (isset($this->_sourceData['gso_ls_dbport'])) { $dbConfig['port'] = $this->_sourceData['gso_ls_dbport']; } elseif (isset($gemsConfig['port'])) { $dbConfig['port'] = $gemsConfig['port']; } $dbConfig['username'] = $this->_sourceData['gso_ls_username'] ? $this->_sourceData['gso_ls_username'] : $gemsConfig['username']; $dbConfig['password'] = $this->_sourceData['gso_ls_password'] ? $this->project->decrypt($this->_sourceData['gso_ls_password']) : $gemsConfig['password']; $this->_sourceDb = \Zend_Db::factory($adapter, $dbConfig); } } // In all other cases use $_gemsDb if (! $this->_sourceDb) { $this->_sourceDb = $this->_gemsDb; } } return $this->_sourceDb; }
Get the db adapter for this source @return \Zend_Db_Adapter_Abstract
entailment
protected function getSurveyData($surveyId, $field = null) { static $cache = array(); if (! isset($cache[$surveyId])) { $cache[$surveyId] = $this->_gemsDb->fetchRow( 'SELECT * FROM gems__surveys WHERE gsu_id_survey = ? LIMIT 1', $surveyId, \Zend_Db::FETCH_ASSOC ); } if (null === $field) { return $cache[$surveyId]; } else { if (isset($cache[$surveyId][$field])) { return $cache[$surveyId][$field]; } } }
Returns all info from the Gems surveys table for a givens Gems Survey Id Uses internal caching to prevent multiple db lookups during a program run (so no caching beyond page generation time) @param int $surveyId @param string $field Optional field to retrieve data for @return array
entailment
public function synchronizeSurveyBatch(\Gems_Task_TaskRunnerBatch $batch, $userId) { // Surveys in Gems $select = $this->_gemsDb->select(); $select->from('gems__surveys', array('gsu_id_survey', 'gsu_surveyor_id')) ->where('gsu_id_source = ?', $this->getId()) ->order('gsu_surveyor_id'); $gemsSurveys = $this->_gemsDb->fetchPairs($select); if (!$gemsSurveys) { $gemsSurveys = array(); } // Surveys in Source $sourceSurveys = $this->_getSourceSurveysForSynchronisation(); if ($sourceSurveys) { $sourceSurveys = array_combine($sourceSurveys, $sourceSurveys); } else { $sourceSurveys = array(); } // Always those already in the database foreach ($gemsSurveys as $surveyId => $sourceSurveyId) { if (isset($sourceSurveys[$sourceSurveyId])) { $batch->addTask('Tracker_CheckSurvey', $this->getId(), $sourceSurveyId, $surveyId, $userId); $batch->addTask('Tracker_AddRefreshQuestions', $this->getId(), $sourceSurveyId, $surveyId); } else { // Do not pass the source id when it no longer exists $batch->addTask('Tracker_CheckSurvey', $this->getId(), null, $surveyId, $userId); } } // Now add the new ones foreach (array_diff($sourceSurveys, $gemsSurveys) as $sourceSurveyId) { $batch->addTask('Tracker_CheckSurvey', $this->getId(), $sourceSurveyId, null, $userId); $batch->addTask('Tracker_AddRefreshQuestions', $this->getId(), $sourceSurveyId, null); } }
Updates the gems database with the latest information about the surveys in this source adapter @param \Gems_Task_TaskRunnerBatch $batch @param int $userId Id of the user who takes the action (for logging) @return array Returns an array of messages
entailment
protected function updateTokens($userId, $updateTokens = true) { $tokenLib = $this->tracker->getTokenLibrary(); $sql = 'UPDATE gems__tokens SET gto_id_token = ' . $this->_getTokenFromToSql($tokenLib->getFrom(), $tokenLib->getTo(), 'gto_id_token') . ', gto_changed = CURRENT_TIMESTAMP, gto_changed_by = ' . $this->_gemsDb->quote($userId) . ' WHERE ' . $this->_getTokenFromSqlWhere($tokenLib->getFrom(), 'gto_id_token') . ' AND gto_id_survey IN (SELECT gsu_id_survey FROM gems__surveys WHERE gsu_id_source = ' . $this->_gemsDb->quote($this->getId()) . ')'; return $this->_gemsDb->query($sql)->rowCount(); }
Updates the gems__tokens table so all tokens stick to the (possibly) new token name rules. @param int $userId Id of the user who takes the action (for logging) @return int The number of tokens changed
entailment
protected function _createSelectElement($name, $options, $empty = null) { if ($options instanceof \MUtil_Model_ModelAbstract) { $options = $options->get($name, 'multiOptions'); } elseif (is_string($options)) { $options = $this->db->fetchPairs($options); natsort($options); } if ($options || null !== $empty) { if (null !== $empty) { $options = array('' => $empty) + $options; } $element = $this->form->createElement('select', $name, array('multiOptions' => $options)); return $element; } }
Creates a \Zend_Form_Element_Select @param string $name Name of the select element @param string|array $options Can be a SQL select string or key/value array of options @param string $empty Text to display for the empty selector @return \Zend_Form_Element_Select
entailment
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { if ($model->has('row_class')) { $bridge->getTable()->tbody()->getFirst(true)->appendAttrib('class', $bridge->row_class); } // Add edit button if allowed, otherwise show, again if allowed if ($menuItem = $this->findAllowedMenuItem('show')) { $bridge->addItemLink($menuItem->toActionLinkLower($this->getRequest(), $bridge)); } parent::addBrowseTableColumns($bridge, $model); // Add edit button if allowed, otherwise show, again if allowed if ($menuItem = $this->findAllowedMenuItem('edit')) { $bridge->addItemLink($menuItem->toActionLinkLower($this->getRequest(), $bridge)); } }
Adds columns from the model to the bridge that creates the browse table. Adds a button column to the model, if such a button exists in the model. @param \MUtil_Model_Bridge_TableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
public function afterSaveRoute($data) { $this->accesslog->logChange($this->request, null, $data); //Get default routing $url = $this->getAfterSaveRoute($data); //If we have a route, reroute if ($url !== null && $url !== false) { $this->_helper->redirector->gotoRoute($url, null, true); return true; } // Do not reroute return false; }
Get the afterSaveRoute and execute it @param mixed $data data array or Zend Request @return boolean
entailment
protected function aliasAction($alias) { $request = $this->getRequest(); $request->setActionName($alias); $request->setParam($request->getActionKey(), $alias); }
Set the action key in request Use this when an action is a Ajax action for retrieving information for use within the screen of another action @param string $alias
entailment
public function beforeFormDisplay ($form, $isNew) { if ($this->useTabbedForms || $form instanceof \Gems_Form_TableForm) { //If needed, add a row of link buttons to the bottom of the form if ($links = $this->createMenuLinks($isNew ? $this->menuCreateIncludeLevel : $this->menuEditIncludeLevel)) { $linkContainer = \MUtil_Html::create()->div(array('class' => 'element-container-labelless')); $linkContainer[] = $links; $element = $form->createElement('html', 'formLinks'); $element->setValue($linkContainer); $element->setOrder(999); if ($form instanceof \Gems_TabForm) { $form->resetContext(); } $form->addElement($element); $form->addDisplayGroup(array('formLinks'), 'form_buttons'); } } else { if (\MUtil_Bootstrap::enabled() !== true) { $table = new \MUtil_Html_TableElement(array('class' => 'formTable')); $table->setAsFormLayout($form, true, true); $table['tbody'][0][0]->class = 'label'; // Is only one row with formLayout, so all in output fields get class. if ($links = $this->createMenuLinks($isNew ? $this->menuCreateIncludeLevel : $this->menuEditIncludeLevel)) { $table->tf(); // Add empty cell, no label $linksCell = $table->tf($links); } } elseif ($links = $this->createMenuLinks($isNew ? $this->menuCreateIncludeLevel : $this->menuEditIncludeLevel)) { $element = $form->createElement('html', 'menuLinks'); $element->setValue($links); $element->setOrder(999); $form->addElement($element); } } return $form; }
Perform some actions on the form, right before it is displayed but already populated Here we add the table display to the form. @param \Zend_Form $form @param bool $isNew @return \Zend_Form
entailment
public function createAction() { if ($form = $this->processForm()) { $this->setPageTitle(sprintf($this->_('New %s...'), $this->getTopic())); $this->html[] = $form; } }
Creates a form for a new record Uses $this->getModel() $this->addFormElements()
entailment
public function createForm($options = null) { if ($this->useTabbedForms) { $form = new \Gems_TabForm($options); } else { $form = parent::createForm($options); //$form = new \Gems_Form_TableForm($options); } return $form; }
Retrieve a form object and add extra decorators @param array $options @return \Gems_Form
entailment
public function deleteAction() { if ($this->isConfirmedItem($this->_('Delete %s'))) { $model = $this->getModel(); $deleted = $model->delete(); $this->addMessage(sprintf($this->_('%2$u %1$s deleted'), $this->getTopic($deleted), $deleted), 'success'); $this->_reroute(array('action' => 'index'), true); } }
Creates a form to delete a record Uses $this->getModel() $this->addFormElements()
entailment
public function editAction() { if ($form = $this->processForm()) { if ($this->useTabbedForms && method_exists($this, 'getSubject')) { $data = $this->getModel()->loadFirst(); $subject = $this->getSubject($data); $this->setPageTitle(sprintf($this->_('Edit %s %s'), $this->getTopic(1), $subject)); } else { $this->setPageTitle(sprintf($this->_('Edit %s'), $this->getTopic(1))); } $this->html[] = $form; } }
Creates a form to edit Uses $this->getModel() $this->addFormElements()
entailment
public function excelAction() { ini_set('max_execution_time', 90); // Quickfix as long as it is not in a batchtask // Set the request cache to use the search params from the index action $this->getCachedRequestData(true, 'index'); $model = $this->getModel(); $this->_applySearchParameters($model, true); $this->addExcelColumns($model); // Hook to modify the model // Use $this->formatExcelData to switch between formatted and unformatted data $excelData = new \Gems_FormattedData($this->getExcelData($model->load(), $model), $model, $this->formatExcelData); $this->view->result = $excelData; $this->view->filename = $this->getRequest()->getControllerName() . '.xls'; $this->view->setScriptPath(GEMS_LIBRARY_DIR . '/views/scripts' ); $this->render('excel', null, true); }
Outputs the model to excel, applying all filters and searches needed When you want to change the output, there are two places to check: 1. $this->addExcelColumns($model), where the model can be changed to have labels for columns you need exported 2. $this->getExcelData($data, $model) where the supplied data and model are merged to get output (by default all fields from the model that have a label)
entailment
public function getAfterSaveRoute($data) { if ($currentItem = $this->menu->getCurrent()) { $controller = $this->_getParam('controller'); $url = null; if ($data instanceof \Zend_Controller_Request_Abstract) { $refData = $data; } elseif (is_array($data)) { $refData = $this->getModel()->getKeyRef($data) + $data; } else { throw new \Gems_Exception_Coding('The variable $data must be an array or a ' . 'Zend_Controller_Request_Abstract object.'); } if ($parentItem = $currentItem->getParent()) { if ($parentItem instanceof \Gems_Menu_SubMenuItem) { $controller = $parentItem->get('controller'); } } // Look for allowed show if ($menuItem = $this->menu->find(array('controller' => $controller, 'action' => 'show', 'allowed' => true))) { $url = $menuItem->toRouteUrl($refData); } if (null === $url) { // Look for allowed index if ($menuItem = $this->menu->find(array('controller' => $controller, 'action' => 'index', 'allowed' => true))) { $url = $menuItem->toRouteUrl($refData); } } if ((null === $url) && ($parentItem instanceof \Gems_Menu_SubMenuItem)) { // Still nothing? Try parent item. $url = $parentItem->toRouteUrl($refData); } if (null !== $url) { return $url; } } return false; }
Return an array with route options depending on de $data given. @param mixed $data array or \Zend_Controller_Request_Abstract @return mixed array with route options or false when no redirect is found
entailment
protected function getAutoSearchElements(\MUtil_Model_ModelAbstract $model, array $data) { if ($model->hasTextSearchFilter()) { // Search text $element = $this->form->createElement('text', \MUtil_Model::TEXT_FILTER, array('label' => $this->_('Free search text'), 'size' => 20, 'maxlength' => 30)); return array($element); } }
Returns a text element for autosearch. Can be overruled. The form / html elements to search on. Elements can be grouped by inserting null's between them. That creates a distinct group of elements @param \MUtil_Model_ModelAbstract $model @param array $data The $form field values (can be usefull, but no need to set them) @return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks.
entailment
protected function getAutoSearchForm($targetId) { if ($this->autoFilter) { $model = $this->getModel(); $data = $this->getCachedRequestData(); $this->form = $form = $this->createForm(array('name' => 'autosubmit', 'class' => 'form-inline', 'role' => 'form')); // Assign a name so autosubmit will only work on this form (when there are others) $elements = $this->getAutoSearchElements($model, $data); if ($elements) { //$form = $this->createForm(array('name' => 'autosubmit')); // Assign a name so autosubmit will only work on this form (when there are others) $form->setHtml('div'); $div = $form->getHtml(); $div->class = 'search'; $span = $div->div(array('class' => 'panel panel-default'))->div(array('class' => 'inputgroup panel-body')); $elements[] = $this->getAutoSearchSubmit($model, $form); if ($reset = $this->getAutoSearchReset()) { $elements[] = $reset; } foreach ($elements as $element) { if ($element instanceof \Zend_Form_Element) { if ($element->getLabel()) { $span->label($element); } $span->input($element); // TODO: Elementen automatisch toevoegen in \MUtil_Form $form->addElement($element); } elseif (null === $element) { $span = $div->div(array('class' => 'panel panel-default'))->div(array('class' => 'inputgroup panel-body')); } else { $span[] = $element; } } if ($this->_request->isPost()) { if (! $form->isValid($data)) { $this->addMessage($form->getErrorMessages(), 'danger'); $this->addMessage($form->getMessages()); } } else { $form->populate($data); } $href = $this->getAutoSearchHref(); $form->setAutoSubmit($href, $targetId); //$div[] = new \Gems_JQuery_AutoSubmitForm($href, $targetId, $form); return $form; } } }
Creates an autosearch form for indexAction. @param string $targetId @return \Gems_Form|null
entailment
public function getBrowseTable(array $baseUrl = array(), $sort = null, $model = null) { $table = parent::getBrowseTable($baseUrl, $sort, $model); $table->class = 'browser table'; $table->setOnEmpty(sprintf($this->_('No %s found'), $this->getTopic(0))); $table->getOnEmpty()->class = 'centerAlign'; return $table; }
Creates from the model a \MUtil_Html_TableElement that can display multiple items. Overruled to add css classes for Gems @param array $baseUrl @return \MUtil_Html_TableElement
entailment
protected function getExcelData($data, \MUtil_Model_ModelAbstract $model) { $headings = array(); $emptyMsg = sprintf($this->_('No %s found.'), $this->getTopic(0)); foreach ($model->getItemsOrdered() as $name) { if ($label = $model->get($name, 'label')) { $headings[$name] = (string) $label; } } $results = array(); $results[] = $headings; if ($headings) { if ($data) { foreach ($data as $row) { $results[] = array_intersect_key($row, $headings); } return $results; } else { $result = array(); foreach ($headings as $key => $value) { $result[$key] = $emptyMsg; } $results[] = $result; return $results; } } else { return array($emptyMsg); } }
Returns an array with all columns from the model that have a label @param array $data @param \MUtil_Model_ModelAbstract $model @return array
entailment
public function getModelForm(array &$data, $new = false) { $model = $this->getModel(); $baseform = $this->createForm(); if ($this->useMultiRowForm) { $bridge = $model->getBridgeFor('form', new \Gems_Form_SubForm()); $newData = $this->addFormElements($bridge, $model, $data, $new); $formtable = new \MUtil_Form_Element_Table($bridge->getForm(), $model->getName(), array('class' => $this->editTableClass)); $baseform->setMethod('post') ->setDescription($this->getTopicTitle()) ->addElement($formtable); $form = $baseform; } else { $bridge = $model->getBridgeFor('form', $baseform); $newData = $this->addFormElements($bridge, $model, $data, $new); $form = $bridge->getForm(); } if ($newData && is_array($newData)) { $data = $newData + $data; } if ($form instanceof \Gems_TabForm) { $form->resetContext(); } return $form; }
Creates from the model a \Zend_Form using createForm and adds elements using addFormElements(). @param array $data The data that will later be loaded into the form, can be changed @param optional boolean $new Form should be for a new element @return \Zend_Form
entailment
public function getShowTable($columns = 1, $filter = null, $sort = null) { $table = parent::getShowTable($columns, $filter, $sort); $table->class = 'displayer table'; return $table; }
Creates from the model a \MUtil_Html_TableElement for display of a single item. Overruled to add css classes for Gems @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 importAction() { $controller = $this->getRequest()->getControllerName(); $importLoader = $this->loader->getImportLoader(); $model = $this->getModel(); $params = array(); $params['defaultImportTranslator'] = $importLoader->getDefaultTranslator($controller); $params['formatBoxClass'] = 'browser table'; $params['importer'] = $importLoader->getImporter($controller, $model); $params['model'] = $model; $params['tempDirectory'] = $importLoader->getTempDirectory(); $params['importTranslators'] = $importLoader->getTranslators($controller); $this->addSnippets($this->importSnippets, $params); }
Generic model based import action
entailment
public function onFakeSubmit(&$form, &$data) { if ($this->useMultiRowForm) { //Check if the insert button was pressed and act upon that if ($this->hasNew() && isset($data['insert_button']) && $data['insert_button']) { // Add a row $model = $this->getModel(); $mname = $model->getName(); $data[$mname][] = $model->loadNew(); } } }
Performs actions when the form is submitted, but the submit button was not checked When not rerouted, the form will be populated afterwards @param \Zend_Form $form The populated form @param array $data The data-array we are working on
entailment
protected function processForm($saveLabel = null, $data = null) { $model = $this->getModel(); $mname = $model->getName(); $request = $this->getRequest(); $isNew = $request->getActionName() === 'create'; //\MUtil_Echo::r($data); if ($request->isPost()) { $data = $request->getPost() + (array) $data; } else { if (!$this->useMultiRowForm) { if (! $data) { if ($isNew) { $data = $model->loadNew(); } else { $data = $model->loadFirst(); if (! $data) { $this->addMessage(sprintf($this->_('Unknown %s requested'), $this->getTopic())); $this->afterSaveRoute(array()); return false; } } } } else { $data[$mname] = $model->load(); if (! $data[$mname]) { $data[$mname] = $model->loadNew(2); } } } // \MUtil_Echo::r($data, __CLASS__ . '->' . __FUNCTION__ . '(): ' . __LINE__); $form = $this->getModelForm($data, $isNew); //Handle insert button on multirow forms if ($this->useMultiRowForm) { if ($this->hasNew()) { $form->addElement($form->createElement('fakeSubmit', array( 'name' => 'insert_button', 'label' => sprintf($this->_('New %1$s...'), $this->getTopic())))); } } //If not already there, add a save button $saveButton = $form->getElement('save_button'); if (! $saveButton) { if (null === $saveLabel) { $saveLabel = $this->_('Save'); } $saveButton = $form->createElement('submit', 'save_button', array('label' => $saveLabel)); $saveButton->setAttrib('class', 'button btn-success'); $form->addElement($saveButton); } $csrf = $form->getElement($this->csrfId); if ($this->useCsrf && (! $csrf)) { $form->addElement('hash', $this->csrfId, array( 'salt' => 'gems_' . $request->getControllerName() . '_' . $request->getActionName(), 'timeout' => $this->csrfTimeout, )); $csrf = $form->getElement($this->csrfId); } if ($request->isPost()) { //First populate the form, otherwise the saveButton will never be 'checked'! $form->populate($data); if ($saveButton->isChecked()) { // \MUtil_Echo::r($_POST, 'POST'); // \MUtil_Echo::r($data, 'data'); // \MUtil_Echo::r($form->getValues(), 'values'); // \MUtil_Model::$verbose = true; if ($form->isValid($data, false)) { /* * Now that we validated, the form should be populated. I think the step * below is not needed as the values in the form come from the data array * but performing a getValues() cleans the data array so data in post but * not in the form is removed from the data variable */ $data = $form->getValues(); if ($this->beforeSave($data, $isNew, $form)) { //Save the data if (!$this->useMultiRowForm) { $data = $model->save($data); // Do not add filter, all values are in $_POST } else { $data[$mname] = $model->saveAll($data[$mname]); } //Now check if there were changes if (($changed = $model->getChanged())) { if ($this->afterSave($data, $isNew)) { $this->addMessage(sprintf($this->_('%2$u %1$s saved'), $this->getTopic($changed), $changed), 'success'); } } else { $this->addMessage($this->_('No changes to save.')); } //\MUtil_Echo::r($data, 'after process'); if ($this->afterSaveRoute($data)) { return null; } } } else { $this->addMessage($this->_('Input error! No changes saved!'), 'danger'); if ($csrf && $csrf->getMessages()) { $this->addMessage($this->_('The form was open for too long or was opened in multiple windows.')); } } } else { //The default save button was NOT used, so we have a fakesubmit button $this->onFakeSubmit($form, $data); } } if (is_array($data)) { $this->afterFormLoad($data, $isNew); } if ($data) { $form->populate($data); $form = $this->beforeFormDisplay($form, $isNew); if ($csrf) { $csrf->initCsrfToken(); } return $form; } }
Handles a form, including population and saving to the model @param string $saveLabel A label describing the form @param array $data An array of data to use, adding to the data from the post @return \Zend_Form|null Returns a form to display or null when finished
entailment
protected function setPageTitle($title) { $this->pageTitle = $title; $args = array('class' => 'title'); $titleTag = \MUtil_Html::create('h3', $title, $args); $this->html->append($titleTag); }
Set the page title on top of a page, also store it in a public var @param string $title Title
entailment
public function showAction() { $this->setPageTitle(sprintf($this->_('Show %s'), $this->getTopic())); $model = $this->getModel(); // NEAR FUTURE: // $this->addSnippet('ModelVerticalTableSnippet', 'model', $model, 'class', 'displayer'); $repeater = $model->loadRepeatable(); $table = $this->getShowTable(); $table->setOnEmpty(sprintf($this->_('Unknown %s.'), $this->getTopic(1))); $table->setRepeater($repeater); $table->tfrow($this->createMenuLinks($this->menuShowIncludeLevel), array('class' => 'centerAlign')); if ($menuItem = $this->findAllowedMenuItem('edit')) { $table->tbody()->onclick = array('location.href=\'', $menuItem->toHRefAttribute($this->getRequest()), '\';'); } $tableContainer = \MUtil_Html::create('div', array('class' => 'table-container'), $table); $this->html[] = $tableContainer; }
Shows a table displaying a single record from the model Uses: $this->getModel() $this->getShowTable();
entailment
protected function _checkFilterUsed($filter) { $filter = parent::_checkFilterUsed($filter); if (isset($filter['gr2o_id_organization'])) { // Check for option to check for any organization if (true === $filter['gr2o_id_organization']) { unset($filter['gr2o_id_organization']); } } else { // Add the correct filter if ($this->isMultiOrganization() && !isset($filter['gr2o_patient_nr'])) { $allowed = $this->currentUser->getAllowedOrganizations(); // If we are not looking for a specific patient, we can look at all patients $filter['gr2o_id_organization'] = array_keys($allowed); } else { // Otherwise, we can only see in our current organization $filter['gr2o_id_organization'] = $this->getCurrentOrganization(); } } if (self::SSN_HASH === $this->hashSsn) { // Make sure a search for a SSN is hashed when needed. array_walk_recursive($filter, array($this, 'applyHash')); } return $filter; }
Add an organization filter if it wasn't specified in the filter. Checks the filter on sematic correctness and replaces the text seacrh filter with the real filter. @param mixed $filter True for the filter stored in this model or a filter array @return array The filter to use
entailment
public function addLoginCheck() { if (! $this->hasAlias('gems__user_logins')) { $this->addLeftTable( 'gems__user_logins', array('gr2o_patient_nr' => 'gul_login', 'gr2o_id_organization' => 'gul_id_organization'), 'gul', \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_UPDATE | \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_DELETE); } $this->addColumn( "CASE WHEN gul_id_user IS NULL OR gul_user_class = 'NoLogin' OR gul_can_login = 0 THEN 0 ELSE 1 END", 'has_login'); return $this; }
Add the table and field to check for respondent login checks @return \Gems_Model_RespondentModel (continuation pattern)
entailment
public static function addNameToModel(\Gems_Model_JoinModel $model, $label) { $nameExpr[] = "COALESCE(grs_last_name, '-')"; $fieldList[] = 'grs_last_name'; if ($model->has('grs_partner_last_name')) { if ($model->has('grs_partner_surname_prefix')) { $nameExpr[] = "COALESCE(CONCAT(' ', grs_partner_surname_prefix), '')"; $fieldList[] = 'grs_partner_surname_prefix'; } $nameExpr[] = "COALESCE(CONCAT(' ', grs_partner_last_name), '')"; $fieldList[] = 'grs_partner_last_name'; } $nameExpr[] = "', '"; if ($model->has('grs_first_name')) { if ($model->has('grs_initials_name')) { $nameExpr[] = "COALESCE(grs_first_name, grs_initials_name, '')"; $fieldList[] = 'grs_first_name'; $fieldList[] = 'grs_initials_name'; } else { $nameExpr[] = "COALESCE(grs_first_name, '')"; $fieldList[] = 'grs_first_name'; } } elseif ($model->has('grs_initials_name')) { $nameExpr[] = "COALESCE(grs_initials_name, '')"; $fieldList[] = 'grs_initials_name'; } if ($model->has('grs_surname_prefix')) { $nameExpr[] = "COALESCE(CONCAT(' ', grs_surname_prefix), '')"; $fieldList[] = 'grs_surname_prefix'; } $model->set('name', 'label', $label, 'column_expression', new \Zend_Db_Expr("CONCAT(" . implode(', ', $nameExpr) . ")"), 'fieldlist', $fieldList); }
Add the respondent name as a caclulated field to the model @param \Gems_Model_JoinModel $model @param string $label
entailment
public function afterRegistry() { parent::afterRegistry(); $this->setOnSave('gr2o_opened', new \MUtil_Db_Expr_CurrentTimestamp()); $this->setSaveOnChange('gr2o_opened'); $this->setOnSave('gr2o_opened_by', $this->currentUser->getUserId()); $this->setSaveOnChange('gr2o_opened_by'); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment
public function applyBrowseSettings() { $dbLookup = $this->util->getDbLookup(); $translated = $this->util->getTranslated(); $this->resetOrder(); if ($this->has('gr2o_id_organization') && $this->isMultiOrganization()) { // Add for sorting $this->addTable('gems__organizations', array('gr2o_id_organization' => 'gor_id_organization')); $this->setIfExists('gor_name', 'label', $this->translate->_('Organization')); $this->set('gr2o_id_organization', 'label', $this->_('Organization'), 'multiOptions', $dbLookup->getOrganizationsWithRespondents() ); } $this->setIfExists('gr2o_patient_nr', 'label', $this->_('Respondent nr')); self::addNameToModel($this, $this->_('Name')); $this->setIfExists('gr2o_email', 'label', $this->_('E-Mail')); $this->setIfExists('gr2o_mailable', 'label', $this->_('May be mailed'), 'multiOptions', $translated->getYesNo() ); $this->setIfExists('grs_address_1', 'label', $this->_('Street')); $this->setIfExists('grs_zipcode', 'label', $this->_('Zipcode')); $this->setIfExists('grs_city', 'label', $this->_('City')); $this->setIfExists('grs_phone_1', 'label', $this->_('Phone')); $this->setIfExists('grs_birthday', 'label', $this->_('Birthday'), 'dateFormat', \Zend_Date::DATE_MEDIUM); $this->setIfExists('gr2o_opened', 'label', $this->_('Opened'), 'formatFunction', $translated->formatDateTime); $this->setIfExists('gr2o_consent', 'label', $this->_('Consent'), 'multiOptions', $dbLookup->getUserConsents() ); return $this; }
Set those settings needed for the browse display @return \Gems_Model_RespondentModel
entailment
public function applyDetailSettings() { $dbLookup = $this->util->getDbLookup(); $localized = $this->util->getLocalized(); $translated = $this->util->getTranslated(); if ($this->loginCheck) { $this->addLoginCheck(); } $this->resetOrder(); if ($this->has('gr2o_id_organization')) { $this->set('gr2o_id_organization', 'label', $this->_('Organization'), 'tab', $this->_('Identification'), 'multiOptions', $this->currentUser->getRespondentOrganizations() ); $this->set('gr2o_id_organization', 'default', $this->currentUser->getCurrentOrganizationId()); if (count($this->currentUser->getAllowedOrganizations()) == 1) { $this->set('gr2o_id_organization', 'elementClass', 'Exhibitor'); } } // The SSN if ($this->hashSsn !== self::SSN_HIDE) { $this->set('grs_ssn', 'label', $this->_('SSN'), 'tab', $this->_('Identification')); } $this->setIfExists('gr2o_patient_nr', 'label', $this->_('Respondent number'), 'tab', $this->_('Identification')); $this->setIfExists('grs_initials_name', 'label', $this->_('Initials')); $this->setIfExists('grs_first_name', 'label', $this->_('First name')); $this->setIfExists('grs_surname_prefix', 'label', $this->_('Surname prefix'), 'description', $this->_('de, ibn, Le, Mac, von, etc...')); $this->setIfExists('grs_last_name', 'label', $this->_('Last name')); $this->setIfExists('grs_partner_surname_prefix', 'label', $this->_('Partner surname prefix'), 'description', $this->_('de, ibn, Le, Mac, von, etc...')); $this->setIfExists('grs_partner_last_name', 'label', $this->_('Partner last name')); $this->setIfExists('grs_gender', 'label', $this->_('Gender'), 'multiOptions', $translated->getGenderHello() ); $this->setIfExists('grs_birthday', 'label', $this->_('Birthday'), 'dateFormat', \Zend_Date::DATE_MEDIUM ); $this->setIfExists('gr2o_email', 'label', $this->_('E-Mail'), 'tab', $this->_('Contact information')); $this->setIfExists('gr2o_mailable', 'label', $this->_('May be mailed'), 'elementClass', 'radio', 'separator', ' ', 'multiOptions', $translated->getYesNo() ); $this->setIfExists('gr2o_treatment', 'label', $this->_('Treatment')); $this->setIfExists('gr2o_comments', 'label', $this->_('Comments')); $this->setIfExists('grs_address_1', 'label', $this->_('Street')); $this->setIfExists('grs_address_2', 'label', ' '); // \MUtil_Echo::track($this->getItemsOrdered(), $this->getOrder('gr2o_email')); $this->setIfExists('grs_zipcode', 'label', $this->_('Zipcode')); $this->setIfExists('grs_city', 'label', $this->_('City')); $this->setIfExists('grs_iso_country', 'label', $this->_('Country'), 'multiOptions', $localized->getCountries()); $this->setIfExists('grs_phone_1', 'label', $this->_('Phone')); $this->setIfExists('grs_phone_2', 'label', $this->_('Phone 2')); $this->setIfExists('grs_phone_3', 'label', $this->_('Phone 3')); $this->setIfExists('grs_phone_4', 'label', $this->_('Phone 4')); $this->setIfExists('grs_iso_lang', 'label', $this->_('Language'), 'multiOptions', $localized->getLanguages(), 'tab', $this->_('Settings'), 'default', $this->project->getLocaleDefault()); $this->setIfExists('gr2o_consent', 'label', $this->_('Consent'), 'default', $this->util->getDefaultConsent(), 'description', $this->_('Has the respondent signed the informed consent letter?'), 'multiOptions', $dbLookup->getUserConsents() ); $changers = $this->getChangersList(); $this->setIfExists('gr2o_opened', 'label', $this->_('Opened'), 'dateFormat', \Zend_Date::DATE_MEDIUM, 'default', '', 'elementClass', 'None', // Has little use to show: is usually editor 'formatFunction', array($translated, 'formatDateTime') ); $this->setIfExists('gr2o_opened_by', 'label', $this->_('Opened'), 'elementClass', 'None', // Has little use to show: is usually editor 'multiOptions', $changers ); $this->setIfExists('gr2o_changed', 'label', $this->_('Changed on'), 'dateFormat', \Zend_Date::DATE_MEDIUM, 'default', '', 'formatFunction', array($translated, 'formatDateTime') ); $this->setIfExists('gr2o_changed_by', 'label', $this->_('Changed by'), 'multiOptions', $changers ); $this->setIfExists('gr2o_created', 'label', $this->_('Creation date'), 'dateFormat', \Zend_Date::DATE_MEDIUM, 'default', '', 'formatFunction', array($translated, 'formatDateTime') ); $this->setIfExists('gr2o_created_by', 'label', $this->_('Creation by'), 'multiOptions', $changers ); return $this; }
Set those settings needed for the detailed display @return \Gems_Model_RespondentModel
entailment
public function applyEditSettings($create = false) { $this->applyDetailSettings(); $this->copyKeys(); // The user can edit the keys. $translated = $this->util->getTranslated(); $ucfirst = new \Zend_Filter_Callback('ucfirst'); if ($create && ($this->hashSsn !== self::SSN_HIDE)) { $onblur = new \MUtil_Html_JavascriptArrayAttribute('onblur'); $onblur->addSubmitOnChange('this.value'); $this->set('grs_ssn', 'onblur', $onblur->render($this->view), // Render needed as element does not know HtmlInterface 'validator[]', $this->createUniqueValidator('grs_ssn') ); } $this->set('gr2o_id_organization', 'default', $this->currentUser->getCurrentOrganizationId()); $this->setIfExists('gr2o_patient_nr', 'size', 15, 'minlength', 4, 'validators[unique]', $this->createUniqueValidator( array('gr2o_patient_nr', 'gr2o_id_organization'), array('gr2o_id_user' => 'grs_id_user', 'gr2o_id_organization') ), 'validators[regex]', new Zend_Validate_Regex('/^[^\/\\%&]*$/'), // Between start and end no \/%& allowed 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->set('grs_id_user'); $this->set('gr2o_email', 'required', true, 'autoInsertNotEmptyValidator', false, // Make sure it works ok with next 'size', 30, 'validator', 'SimpleEmail'); $this->addColumn('CASE WHEN gr2o_email IS NULL OR LENGTH(TRIM(gr2o_email)) = 0 THEN 1 ELSE 0 END', 'calc_email'); $this->set('calc_email', 'label', $this->_('Respondent has no e-mail'), 'elementClass', 'Checkbox', 'required', true, 'order', $this->getOrder('gr2o_email') + 1, 'validator', new \Gems_Validate_OneOf( $this->_('Respondent has no e-mail'), 'gr2o_email', $this->get('gr2o_email', 'label') ) ); $this->set('gr2o_mailable', 'label', $this->_('May be mailed'), 'elementClass', 'radio', 'multiOptions', $translated->getYesNo(), 'separator', ' ' ); $this->setIfExists('grs_first_name', 'filter', $ucfirst, 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->setIfExists('grs_surname_prefix', 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->setIfExists('grs_last_name', 'filter', $ucfirst, 'required', true, 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->setIfExists('grs_partner_surname_prefix', 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->setIfExists('grs_partner_last_name', 'filter', new \Zend_Filter_Callback('ucfirst'), 'validators[csvinj]', 'NoCsvInjectionChars' ); $this->setIfExists('grs_gender', 'elementClass', 'Radio', 'separator', '', 'multiOptions', $translated->getGenders(), 'tab', $this->_('Medical data') ); $this->setIfExists('grs_birthday', 'jQueryParams', array('defaultDate' => '-30y', 'maxDate' => 0, 'yearRange' => 'c-130:c0'), 'elementClass', 'Date', 'validator', new \MUtil_Validate_Date_DateBefore() ); $this->setIfExists('gr2o_treatment', 'size', 30); $this->setIfExists('gr2o_comments', 'elementClass', 'Textarea', 'rows', 4, 'cols', 60); $this->setIfExists('grs_address_1', 'size', 40, 'description', $this->_('With housenumber'), 'filter', $ucfirst ); $this->setIfExists('grs_address_2', 'size', 40); $this->setIfExists('grs_city', 'filter', $ucfirst); $this->setIfExists('grs_phone_1', 'size', 15); $this->setIfExists('grs_phone_2', 'size', 15); $this->setIfExists('grs_phone_3', 'size', 15); $this->setIfExists('grs_phone_4', 'size', 15); $this->setIfExists('gr2o_consent', 'default', $this->util->getDefaultConsent(), 'elementClass', 'Radio', 'separator', ' ', 'required', true); $this->setMulti(array('name', 'row_class', 'resp_deleted'), 'elementClass', 'None'); $this->setMulti($this->getItemsFor('table', 'gems__reception_codes'), 'elementClass', 'None'); if ($create) { $this->setIfExists('gr2o_changed', 'elementClass', 'None'); $this->setIfExists('gr2o_changed_by', 'elementClass', 'None'); $this->setIfExists('gr2o_created', 'elementClass', 'None'); $this->setIfExists('gr2o_created_by', 'elementClass', 'None'); } else { $this->setIfExists('gr2o_changed', 'elementClass', 'Exhibitor'); $this->setIfExists('gr2o_changed_by', 'elementClass', 'Exhibitor'); $this->setIfExists('gr2o_created', 'elementClass', 'Exhibitor'); $this->setIfExists('gr2o_created_by', 'elementClass', 'Exhibitor'); } return $this; }
Set those values needed for editing @param boolean $create True when creating @return \Gems_Model_RespondentModel
entailment
public function applyHash(&$filterValue, $filterKey) { if ('grs_ssn' === $filterKey) { $filterValue = $this->project->getValueHash($filterValue, $this->hashAlgorithm); } }
Apply hash function for array_walk_recursive in _checkFilterUsed() @see _checkFilterUsed() @param string $filterValue @param string $filterKey
entailment
public function copyToOrg($fromOrgId, $fromPid, $toOrgId, $toPid, $keepConsent = false) { // Maybe we should disable masking, just to be sure $this->currentUser->disableMask(); // Do some sanity checks $fromPatient = $this->loadFirst(['gr2o_id_organization' => $fromOrgId, 'gr2o_patient_nr' => $fromPid]); if (empty($fromPatient)) { throw new \Gems_Exception($this->_('Respondent not found in sending organization.')); } $toPatientByPid = $this->loadFirst(['gr2o_id_organization' => $toOrgId, 'gr2o_patient_nr' => $toPid]); $toPatientByRespondent = $this->loadFirst(['gr2o_id_organization' => $toOrgId, 'gr2o_id_user' => $fromPatient['gr2o_id_user']]); if (!empty($toPatientByPid) && $toPatientByPid['gr2o_id_user'] = $fromPatient['gr2o_id_user']) { // We already have the same respondent, nothing to do throw new \Gems_Exception($this->_('Respondent already exists in destination organization.')); } if (!empty($toPatientByPid) && empty($toPatientByRespondent)) { // Could be the same, or someone else... just return an error for now maybe offer to mark as duplicate and merge records later on throw new \Gems_Exception($this->_('Respondent with requested respondent number already exists in receiving organization.')); } if (!empty($toPatientByRespondent)) { // No action needed, maybe also report the number we found? throw new \Gems_Exception($this->_('Respondent already exists in destination organization, but with different respondent number.')); } // Ready to go, unset consent if needed $toPatient = $fromPatient; if (!$keepConsent) { unset($toPatient['gr2o_consent']); } // And save the record $toPatient['gr2o_patient_nr'] = $toPid; $toPatient['gr2o_id_organization'] = $toOrgId; $toPatient['gr2o_reception_code'] = \GemsEscort::RECEPTION_OK; $loginToSaveTable = false; if (isset($this->_saveTables['gems__user_logins'])) { $loginToSaveTable = $this->_saveTables['gems__user_logins']; unset($this->_saveTables['gems__user_logins']); } $result = $this->save($toPatient); if ($loginToSaveTable) { $this->_saveTables['gems__user_logins'] = $loginToSaveTable; } // Now re-enable the mask feature $this->currentUser->enableMask(); return $result; }
Copy a respondent to a new organization If you want to share a respondent(id) with another organization use this method. @param int $fromOrgId Id of the sending organization @param string $fromPid Respondent number of the sending organization @param int $toOrgId Id of the receiving organization @param string $toPid Respondent number of the sending organization @param bool $keepConsent Should new organization inherit the consent of the old organization or not? @return array The new respondent @throws \Gems_Exception
entailment
public function countTracks($patientId, $organizationId, $respondentId = null, $active = false) { $db = $this->getAdapter(); $select = $db->select(); $select->from('gems__respondent2track', array('COALESCE(COUNT(*), 0)')); if (null === $respondentId) { $respondentId = $this->util->getDbLookup()->getRespondentId($patientId, $organizationId); } $select->where('gr2t_id_user = ?', $respondentId); if (null !== $organizationId) { $select->where('gr2t_id_organization = ?', $organizationId); } if ($active) { $select->joinInner('gems__reception_codes', 'gr2t_reception_code = grc_id_reception_code') ->where('grc_success = 1'); } return $db->fetchOne($select); }
Count the number of tracks the respondent has for this organization @param string $patientId Can be empty if $respondentId is passed @param int $organizationId When null looks at all organizations @param int $respondentId Pass when at hand, is looked up otherwise @param boolean $active When true only tracks with a success code are returned @return boolean
entailment
public function getReceptionCode($patientId, $organizationId, $respondentId = null) { $db = $this->getAdapter(); $select = $db->select(); $select->from('gems__respondent2org', array('gr2o_reception_code')); if ($patientId) { $select->where('gr2o_patient_nr = ?', $patientId); } else { $select->where('gr2o_id_user = ?', $respondentId); } $select->where('gr2o_id_organization = ?', $organizationId); return $db->fetchOne($select); }
Get the current reception code for a respondent @param string $patientId Can be empty if $respondentId is passed @param int $organizationId @param int $respondentId Pass when at hand, is looked up otherwise @return string The current reception code
entailment
public function hasTracks($patientId, $organizationId, $respondentId = null, $active = false) { return (boolean) $this->countTracks($patientId, $organizationId, $respondentId, $active); }
Has the respondent tracks @param string $patientId Can be empty if $respondentId is passed @param int $organizationId When null looks at all organizations @param int $respondentId Pass when at hand, is looked up otherwise @param boolean $active When true we look only for tracks with a success code @return boolean
entailment
public function hideSSN($value, $isNew = false, $name = null, array $context = array(), $isPost = false) { if ($value && (! $isPost)) { return str_repeat('*', 9); } else { return $value; } }
Return a hashed version of the input value. @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 output to display
entailment
public function merge($newPid, $oldPid, $orgId) { // Maybe we should disable masking, just to be sure $this->currentUser->disableMask(); $patients = $this->load([ 'gr2o_id_organization' => $orgId, 'gr2o_patient_nr' => array($oldPid, $newPid) ]); // Now re-enable the mask feature $this->currentUser->enableMask(); $cnt = count($patients); switch ($cnt) { case 1: // We only have one, check if it is the new number $patient = reset($patients); if ($patient['gr2o_patient_nr'] == $newPid) { return \Gems\Model\MergeResult::FIRST; } // Not the new number, we can simply move $this->move($orgId, $oldPid, $orgId, $newPid); return \Gems\Model\MergeResult::SECOND; break; case 2: // We really need to merge all related records for the patients $patient = $patients[0]; if ($patient['gr2o_patient_nr'] == $newPid) { $newPatient = $patient; $oldPatient = $patients[1]; } else { $oldPatient = $patient; $newPatient = $patients[1]; } // Due to key contraints the respondent id's should be different but check anyway if ($oldPatient['grs_id_user'] !== $newPatient['grs_id_user']) { // It could be that the 'old' patient has a ssn, this could lead to problems later // To prevent this we clear the ssn for the old patient if (!empty($oldPatient['grs_ssn'])) { $oldPatient['grs_ssn'] = ''; $changed = $this->db->update( 'gems__respondents', ['grs_ssn' => null], ['grs_id_user = ?' => $oldPatient['grs_id_user']] ); // We seem to be unable to save an empty ssn //$this->save($oldPatient); } } $tables = array( 'gems__respondent2track' => ['gr2t_id_user', 'gr2t_id_organization'], 'gems__tokens' => ['gto_id_respondent', 'gto_id_organization'], 'gems__appointments' => ['gap_id_user', 'gap_id_organization'], 'gems__log_respondent_communications' => ['grco_id_to', 'grco_organization'], 'gems__respondent_relations' => ['grr_id_respondent', null], 'gems__log_activity' => ['gla_respondent_id', 'gla_organization'] ); $changed = 0; $currentTs = new \MUtil_Db_Expr_CurrentTimestamp(); $userId = $this->currentUser->getUserId(); foreach ($tables as $tableName => $settings) { list($respIdField, $orgIdField) = $settings; $start = \MUtil_String::beforeChars($respIdField, '_'); $values = [ $respIdField => $newPatient['grs_id_user'], $start . '_changed' => $currentTs, $start . '_changed_by' => $userId, ]; if ($tableName == 'gems__log_activity') { unset($values[$start . '_changed']); unset($values[$start . '_changed_by']); } $where = []; $where["$respIdField = ?"] = $oldPatient['grs_id_user']; if (!is_null($orgIdField)) { $where["$orgIdField = ?"] = $orgId; }; $changed += $this->db->update($tableName, $values, $where); } return \Gems\Model\MergeResult::BOTH; break; default: // Not found return \Gems\Model\MergeResult::NONE; break; } return false; }
Merge two patients (in the same organization) A respondent can only exist twice in the same organization when the respondent has multiple respondent id's. When ssn is set correctly this can not happen so probably one with and one without or both without ssn. @param string $newPid @param string $oldPid @param int $orgId @return \Gems\Model\MergeResult | false The result or false in case of failure
entailment
public function move($fromOrgId, $fromPid, $toOrgId, $toPid) { // Maybe we should disable masking, just to be sure $this->currentUser->disableMask(); $patientFrom = $this->loadFirst([ 'gr2o_id_organization' => $fromOrgId, 'gr2o_patient_nr' => $fromPid ]); $patientTo = $this->loadFirst([ 'gr2o_id_organization' => $toOrgId, 'gr2o_patient_nr' => $toPid ]); if ($fromPid !== $toPid) { $patientFrom['gr2o_patient_nr'] = $toPid; $copyKey = $this->getKeyCopyName('gr2o_patient_nr'); $patientFrom[$copyKey] = $fromPid; } if ($fromOrgId !== $toOrgId) { $patientFrom['gr2o_id_organization'] = $toOrgId; $copyKey = $this->getKeyCopyName('gr2o_id_organization'); $patientFrom[$copyKey] = $fromOrgId; } if (empty($patientTo)) { $result = $this->save($patientFrom); } else { // already exists, return current patient // we can not delete the other records, maybe mark as inactive or throw an error $result = $patientTo; $this->currentUser->enableMask(); throw new \Gems_Exception($this->_('Respondent already exists in destination, please delete current record manually if needed.')); } // Now re-enable the mask feature $this->currentUser->enableMask(); return $result; }
Move a respondent to a new organization and/or change it's number This not be a copy, it will be renamed. Use copyToOrg if you want to make a copy. @param int $fromOrgId Id of the sending organization @param string $fromPid Respondent number of the sending organization @param int $toOrgId Id of the receiving organization @param string $toPid Respondent number of the sending organization @return array The new respondent
entailment
public function save(array $newValues, array $filter = null, array $saveTables = null) { // If the respondent id is not set, check using the // patient number and then the ssn if (! (isset($newValues['grs_id_user']) && $newValues['grs_id_user'])) { $id = false; if (isset($newValues['gr2o_patient_nr'], $newValues['gr2o_id_organization'])) { $sql = 'SELECT gr2o_id_user FROM gems__respondent2org WHERE gr2o_patient_nr = ? AND gr2o_id_organization = ?'; $id = $this->db->fetchOne($sql, array($newValues['gr2o_patient_nr'], $newValues['gr2o_id_organization'])); } if ((!$id) && isset($newValues['grs_ssn']) && !empty($newValues['grs_ssn']) && ($this->hashSsn !== self::SSN_HIDE)) { if (self::SSN_HASH === $this->hashSsn) { $search = $this->saveSSN($newValues['grs_ssn']); } else { $search = $newValues['grs_ssn']; } $sql = 'SELECT grs_id_user FROM gems__respondents WHERE grs_ssn = ?'; $id = $this->db->fetchOne($sql, $search); // Check for change in patient ID if ($id && isset($newValues['gr2o_id_organization'])) { $sql = 'SELECT gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ? AND gr2o_id_organization = ?'; $patientId = $this->db->fetchOne($sql, array($id, $newValues['gr2o_id_organization'])); if ($patientId) { $copyId = $this->getKeyCopyName('gr2o_patient_nr'); $newValues[$copyId] = $patientId; } } } if ($id) { $newValues['grs_id_user'] = $id; $newValues['gr2o_id_user'] = $id; } // If empty, then set by \Gems_Model->createGemsUserId() } $result = parent::save($newValues, $filter, $saveTables); if (isset($result['gr2o_id_organization']) && isset($result['grs_id_user'])) { // Tell the organization it has at least one user $org = $this->loader->getOrganization($result['gr2o_id_organization']); if ($org) { $org->setHasRespondents($this->currentUser->getUserId()); } $this->handleRespondentChanged($result['gr2o_patient_nr'], $org, $result['grs_id_user']); } return $result; }
Save a single model item. @param array $newValues The values to store for a single model item. @param array $filter If the filter contains old key values these are used to decide on update versus insert. @return array The values as they are after saving (they may change).
entailment
public function saveSSN($value, $isNew = false, $name = null, array $context = array()) { if ($value) { return $this->project->getValueHash($value, $this->hashAlgorithm); } }
Return a hashed version of the input value. @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 salted hash as a 32-character hexadecimal number.
entailment
public function setReceptionCode($patientId, $organizationId, $newCode, $respondentId = null, $oldCode = null) { if (!$newCode instanceof \Gems_Util_ReceptionCode) { $newCode = $this->util->getReceptionCode($newCode); } $userId = $this->currentUser->getUserId(); // Perform actual save, but not for simple stop codes. if ($newCode->isForRespondents()) { if (null === $oldCode) { $oldCode = $this->getReceptionCode($patientId, $organizationId, $respondentId); } if ($oldCode instanceof \Gems_Util_ReceptionCode) { $oldCode = $oldCode->getCode(); } // If the code wasn't set already if ($oldCode !== $newCode->getCode()) { $values['gr2o_reception_code'] = $newCode->getCode(); $values['gr2o_changed'] = new \MUtil_Db_Expr_CurrentTimestamp(); $values['gr2o_changed_by'] = $userId; if ($patientId) { // Update though primamry key is prefered $where = 'gr2o_patient_nr = ? AND gr2o_id_organization = ?'; $where = $this->db->quoteInto($where, $patientId, null, 1); } else { $where = 'gr2o_id_user = ? AND gr2o_id_organization = ?'; $where = $this->db->quoteInto($where, $respondentId, null, 1); } $where = $this->db->quoteInto($where, $organizationId, null, 1); $this->db->update('gems__respondent2org', $values, $where); } } // Is the respondent really removed if (! $newCode->isSuccess()) { // Only check for $respondentId when it is really needed if (null === $respondentId) { $respondentId = $this->util->getDbLookup()->getRespondentId($patientId, $organizationId); } // Cascade to tracks // the responsiblilty to handle it correctly is on the sub objects now. $tracks = $this->loader->getTracker()->getRespondentTracks($respondentId, $organizationId); foreach ($tracks as $track) { if ($track->setReceptionCode($newCode, null, $userId)) { $this->addChanged(); } } } if ($newCode->isForRespondents()) { $this->handleRespondentChanged($patientId, $organizationId, $respondentId); } return $newCode; }
Set the reception code for a respondent and cascade non-success codes to the tracks / surveys. @param string $patientId Can be empty if $respondentId is passed @param int $organizationId @param string $newCode String or \Gems_Util_ReceptionCode @param int $respondentId Pass when at hand, is looked up otherwise @param string $oldCode Pass when at hand as string or \Gems_Util_ReceptionCode, is looked up otherwise @return \Gems_Util_ReceptionCode The new code reception code object for further processing
entailment
public function whenSSN($value, $isNew = false, $name = null, array $context = array()) { return $value && ($value !== $this->hideSSN($value, $isNew, $name, $context)); }
Return a hashed version of the input value. @param mixed $value The value being saved @param boolean $isNew True when a new item is being saved @param string $name The name of the current field @param array $context Optional, the other values being saved @return boolean
entailment
protected function createModel() { if ($this->model instanceof \Gems_Model_RespondentModel) { $model = $this->model; } else { if ($this->respondent instanceof \Gems_Tracker_Respondent) { $model = $this->respondent->getRespondentModel(); } else { $model = $this->loader->getModels()->getRespondentModel(true);; } $model->applyDetailSettings(); } return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function getReceptionCodes() { $rcLib = $this->util->getReceptionCodeLibrary(); if ($this->unDelete) { return $rcLib->getRespondentRestoreCodes(); } return $rcLib->getRespondentDeletionCodes(); }
Called after loadFormData() and isUndeleting() but before the form is created @return array code name => description
entailment
protected function loadFormData() { if (! $this->request->isPost()) { if ($this->respondent instanceof \Gems_Tracker_Respondent) { $this->formData = $this->respondent->getArrayCopy(); } } if (! $this->formData) { parent::loadFormData(); } $model = $this->getModel(); $model->set('restore_tracks', 'label', $this->_('Restore tracks'), 'description', $this->_('Restores tracks with the same code as the respondent.'), 'elementClass', 'Checkbox' ); if (! array_key_exists('restore_tracks', $this->formData)) { $this->formData['restore_tracks'] = 1; } }
Hook that loads the form data from $_POST or the model Or from whatever other source you specify here.
entailment
public function setReceptionCode($newCode, $userId) { $oldCode = $this->respondent->getReceptionCode(); $code = $this->respondent->setReceptionCode($newCode); // Is the respondent really removed if ($code->isSuccess()) { $this->addMessage($this->_('Respondent restored.')); if ($this->formData['restore_tracks']) { $count = $this->respondent->restoreTracks($oldCode, $code); $this->addMessage(sprintf($this->plural('Restored %d track.', 'Restored %d tracks.', $count), $count)); } } else { // Perform actual save, but not simple stop codes. if ($code->isForRespondents()) { $this->addMessage($this->_('Respondent deleted.')); $this->afterSaveRouteKeys = false; $this->resetRoute = true; $this->routeAction = 'index'; } else { // Just a stop code $this->addMessage(sprintf($this->plural('Stopped %d track.', 'Stopped %d tracks.', $count), $count)); } } return 1; }
Hook performing actual save @param string $newCode @param int $userId @return $changed
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { if ($this->tokenId) { $this->addMessage(sprintf($this->_('Token %s not found.'), $this->tokenId)); } else { $this->addMessage($this->_('No token specified.')); } 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 addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $bridge->gr2o_patient_nr; $bridge->gr2o_id_organization; if ($menuItem = $this->menu->find(array('controller' => 'appointment', 'action' => 'show', 'allowed' => true))) { $appButton = $menuItem->toActionLink($this->request, $bridge, $this->_('Show appointment')); } else { $appButton = null; } if ($menuItem = $this->menu->find(array('controller' => 'appointment', 'action' => 'edit', 'allowed' => true))) { $editButton = $menuItem->toActionLink($this->request, $bridge, $this->_('Edit appointment')); } else { $editButton = null; } $episode = $this->currentUser->hasPrivilege('pr.episodes'); $br = \MUtil_Html::create('br'); $table = $bridge->getTable(); $table->appendAttrib('class', 'calendar'); $bridge->tr()->appendAttrib('class', $bridge->row_class); if ($appButton) { $bridge->addItemLink($appButton)->class = 'middleAlign'; } if ($this->sortableLinks) { $bridge->addMultiSort(array($bridge->date_only), $br, 'gap_admission_time')->class = 'date'; if ($episode) { $bridge->addMultiSort('gap_id_episode'); } $bridge->addMultiSort('gap_subject', $br, 'glo_name'); $bridge->addMultiSort('gaa_name', $br, 'gapr_name'); $bridge->addMultiSort('gor_name', $br, 'glo_name'); } else { $bridge->addMultiSort( array($bridge->date_only), $br, array($bridge->gap_admission_time, $model->get('gap_admission_time', 'label')) ); if ($episode) { $bridge->addMultiSort(array($bridge->gap_id_episode, $model->get('gap_id_episode', 'label'))); } $bridge->addMultiSort( array($bridge->gap_subject, $model->get('gap_subject', 'label')), $br, array($bridge->gas_name, $model->get('gas_name', 'label')) ); $bridge->addMultiSort( array($bridge->gaa_name, $model->get('gaa_name', 'label')), $br, array($bridge->gapr_name, $model->get('gapr_name', 'label')) ); $bridge->addMultiSort( array($bridge->gor_name, $model->get('gor_name', 'label')), $br, array($bridge->glo_name, $model->get('glo_name', 'label')) ); } if ($editButton) { $bridge->addItemLink($editButton)->class = 'middleAlign rightAlign'; } }
Adds columns from the model to the bridge that creates the browse table. Overrule this function to add different columns to the browse table, without having to recode the core table building code. @param \MUtil_Model_Bridge_TableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
protected function createModel() { if ($this->model instanceof \Gems_Model_AppointmentModel) { $model = $this->model; } else { $model = $this->loader->getModels()->createAppointmentModel(); $model->applyBrowseSettings(); } $model->addColumn(new \Zend_Db_Expr("CONVERT(gap_admission_time, DATE)"), 'date_only'); $model->set('date_only', 'formatFunction', array($this, 'formatDate')); // 'dateFormat', \Zend_Date::DAY_SHORT . ' ' . \Zend_Date::MONTH_NAME . ' ' . \Zend_Date::YEAR); $model->set('gap_admission_time', 'label', $this->_('Time'), 'formatFunction', array($this, 'formatTime')); // 'dateFormat', 'HH:mm ' . \Zend_Date::WEEKDAY); $this->_dateStorageFormat = $model->get('gap_admission_time', 'storageFormat'); // $this->_timeImg = \MUtil_Html::create('img', array('src' => 'stopwatch.png', 'alt' => '')); $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr')); if ($this->respondent instanceof \Gems_Tracker_Respondent) { $model->addFilter(array( 'gap_id_user' => $this->respondent->getId(), 'gap_id_organization' => $this->respondent->getOrganizationId(), )); } return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function formatDate($value) { return \MUtil_Html::create( 'span', // array('class' => 'date'), \MUtil_Date::format( $value, \Zend_Date::DAY_SHORT . ' ' . \Zend_Date::MONTH_NAME_SHORT . ' ' . \Zend_Date::YEAR, 'yyyy-MM-dd' ) ); }
Display the date field @param \MUtil_Date $value
entailment
public function formatTime($value) { return \MUtil_Html::create( 'span', ' ', // array('class' => 'time'), // $this->_timeImg, \MUtil_Date::format($value, 'HH:mm ' . \Zend_Date::WEEKDAY_SHORT, $this->_dateStorageFormat) ); }
Display the time field @param \MUtil_Date $value
entailment
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model) { parent::processFilterAndSort($model); $eid = $this->request->getParam(\Gems_Model::EPISODE_ID); if ($eid) { $model->addFilter(['gap_id_episode' => $eid]); } }
Overrule to implement snippet specific filtering and sorting. @param \MUtil_Model_ModelAbstract $model
entailment
public function createModel($detailed, $action) { $dbLookup = $this->util->getDbLookup(); $rolesObj = \Gems_Roles::getInstance(); $userLoader = $this->loader->getUserLoader(); $model = new \MUtil_Model_TableModel('gems__groups'); // Add id for excel export if ($action == 'export') { $model->set('ggp_id_group', 'label', 'id'); } $model->set('ggp_name', 'label', $this->_('Name'), 'minlength', 4, 'size', 15, 'validator', $model->createUniqueValidator('ggp_name') ); $model->set('ggp_description', 'label', $this->_('Description'), 'size', 40 ); $model->set('ggp_role', 'label', $this->_('Role'), 'multiOptions', $dbLookup->getRoles() ); $model->setOnLoad('ggp_role', [$rolesObj, 'translateToRoleName']); $model->setOnSave('ggp_role', [$rolesObj, 'translateToRoleId']); $groups = $dbLookup->getGroups(); unset($groups['']); $model->set('ggp_may_set_groups', 'label', $this->_('May set these groups'), 'elementClass', 'MultiCheckbox', 'multiOptions', $groups ); $tpa = new \MUtil_Model_Type_ConcatenatedRow(',', ', '); $tpa->apply($model, 'ggp_may_set_groups'); $model->set('ggp_default_group', 'label', $this->_('Default group'), 'description', $this->_('Default group when creating new staff member'), 'elementClass', 'Select', 'multiOptions', $dbLookup->getGroups() ); $yesNo = $this->util->getTranslated()->getYesNo(); $model->set('ggp_staff_members', 'label', $this->_('Staff'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo ); $model->set('ggp_respondent_members', 'label', $this->_('Respondents'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo ); $model->set('ggp_allowed_ip_ranges', 'label', $this->_('Login allowed from IP Ranges'), 'description', $this->_('Separate with | examples: 10.0.0.0-10.0.0.255, 10.10.*.*, 10.10.151.1 or 10.10.151.1/25'), 'elementClass', 'Textarea', 'itemDisplay', [$this, 'ipWrap'], 'rows', 4, 'validator', new \Gems_Validate_IPRanges() ); $model->setIfExists('ggp_no_2factor_ip_ranges', 'label', $this->_('Two factor Optional IP Ranges'), 'description', $this->_('Separate with | examples: 10.0.0.0-10.0.0.255, 10.10.*.*, 10.10.151.1 or 10.10.151.1/25'), 'default', '127.0.0.1|::1', 'elementClass', 'Textarea', 'itemDisplay', [$this, 'ipWrap'], 'rows', 4, 'validator', new \Gems_Validate_IPRanges() ); $model->setIfExists('ggp_2factor_set', 'label', $this->_('Login with two factor set'), 'elementClass', 'Radio', 'multiOptions', $userLoader->getGroupTwoFactorSetOptions(), 'separator', '<br/>' ); $model->setIfExists('ggp_2factor_not_set', 'label', $this->_('Login without two factor set'), 'elementClass', 'Radio', 'multiOptions', $userLoader->getGroupTwoFactorNotSetOptions(), 'separator', '<br/>' ); $model->set('ggp_group_active', 'label', $this->_('Active'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo ); if ($detailed) { $html = \MUtil_Html::create()->h4($this->_('Screen settings')); $model->set('screensettings', 'label', ' ', 'default', $html, 'elementClass', 'Html', 'value', $html ); $screenLoader = $this->loader->getScreenLoader(); $model->set('ggp_respondent_browse', 'label', $this->_('Respondent browse screen'), 'default', 'Gems\\Screens\\Respondent\\Browse\\ProjectDefaultBrowse', 'elementClass', 'Radio', 'multiOptions', $screenLoader->listRespondentBrowseScreens() ); $screenLoader = $this->loader->getScreenLoader(); $model->set('ggp_respondent_edit', 'label', $this->_('Respondent edit screen'), 'default', 'Gems\\Screens\\Respondent\\Edit\\ProjectDefaultEdit', 'elementClass', 'Radio', 'multiOptions', $screenLoader->listRespondentEditScreens() ); $screenLoader = $this->loader->getScreenLoader(); $model->set('ggp_respondent_show', 'label', $this->_('Respondent show screen'), 'default', 'Gems\\Screens\\Respondent\\Show\\GemsProjectDefaultShow', 'elementClass', 'Radio', 'multiOptions', $screenLoader->listRespondentShowScreens() ); $maskStore = $this->loader->getUserMaskStore(); $maskStore->addMaskSettingsToModel($model, 'ggp_mask_settings'); } \Gems_Model::setChangeFieldsByPrefix($model, 'ggp'); return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
protected function fixSql($where) { if ($where == parent::NO_MATCH_SQL) { return parent::MATCH_ALL_SQL; } elseif ($where == parent::MATCH_ALL_SQL) { return parent::NO_MATCH_SQL; } else { return "NOT ($where)"; } }
Standard where processing @param string $where @return string
entailment
protected function loadFormData() { parent::loadFormData(); if ($this->trackEngine instanceof \Gems_Tracker_Engine_StepEngineAbstract) { if ($this->trackEngine->updateRoundModelToItem($this->getModel(), $this->formData, $this->locale->getLanguage())) { if (isset($this->formData[$this->saveButtonId])) { // Disable validation & save unset($this->formData[$this->saveButtonId]); // Warn user $this->addMessage($this->_('Lists choices changed.')); } } } }
Hook that loads the form data from $_POST or the model Or from whatever other source you specify here.
entailment
public function processTokenInsertion(\Gems_Tracker_Token $token) { if ($token->hasSuccesCode() && (! $token->isCompleted())) { // Preparation for a more general object class $surveyId = $token->getSurveyId(); $prev = $token; while ($prev = $prev->getPreviousToken()) { if ($prev->hasSuccesCode() && $prev->isCompleted()) { // Check first on survey id and when that does not work by name. if ($prev->getSurveyId() == $surveyId) { return $prev->getRawAnswers(); } } } } }
Process the data and return the answers that should be filled in beforehand. Storing the changed values is handled by the calling function. @param \Gems_Tracker_Token $token Gems token object @return array Containing the changed values
entailment
public function authenticate() { $result = call_user_func_array($this->_callback, $this->_params); if ( !($result instanceof Result)) { if ($result === true) { $result = new Result(Result::SUCCESS, $this->_identity); } else { $result = new Result(Result::FAILURE_CREDENTIAL_INVALID, $this->_identity); } } return $result; }
Perform the authenticate attempt @return Result
entailment
protected function getAutoSearchElements(array $data) { $yesNo = $this->util->getTranslated()->getYesNo(); $elements = parent::getAutoSearchElements($data); $elements[] = $this->_createSelectElement('gls_when_no_user', $yesNo, $this->_('(any when no user)')); $elements[] = $this->_createSelectElement('gls_on_action', $yesNo, $this->_('(any on action)')); $elements[] = $this->_createSelectElement('gls_on_post', $yesNo, $this->_('(any on post)')); $elements[] = $this->_createSelectElement('gls_on_change', $yesNo, $this->_('(any on change)')); return $elements; }
Returns a text element for autosearch. Can be overruled. The form / html elements to search on. Elements can be grouped by inserting null's between them. That creates a distinct group of elements @param array $data The $form field values (can be usefull, but no need to set them) @return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks.
entailment
public function createModel($detailed, $action) { $model = new \Gems_Model_JoinModel('resptrack' , 'gems__respondent2track'); $model->addTable('gems__respondent2org', array( 'gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization' )); $model->addTable('gems__respondents', array('gr2o_id_user' => 'grs_id_user')); $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track')); $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code')); $model->addFilter(array('grc_success' => 1)); $model->resetOrder(); $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr')); $model->addColumn( "TRIM(CONCAT(COALESCE(CONCAT(grs_last_name, ', '), '-, '), COALESCE(CONCAT(grs_first_name, ' '), ''), COALESCE(grs_surname_prefix, '')))", 'respondent_name'); if (! $this->currentUser->isFieldMaskedPartial('respondent_name')) { $model->set('respondent_name', 'label', $this->_('Name')); } $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy'); $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy'); $filter = $this->getSearchFilter($action !== 'export'); if (! (isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) { $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter())); } if (! (isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) { $model->setFilter(array('1=0')); $this->autofilterParameters['onEmpty'] = $this->_('No track selected...'); return $model; } // Add the period filter - if any if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) { $model->addFilter(array($where)); } $select = $this->db->select(); $select->from('gems__rounds', array('gro_id_round', 'gro_id_order', 'gro_round_description', 'gro_icon_file')) ->joinInner('gems__surveys', 'gro_id_survey = gsu_id_survey', array('gsu_survey_name')) ->joinLeft('gems__track_fields', 'gro_id_relationfield = gtf_id_field AND gtf_field_type = "relation"', array()) ->joinInner('gems__groups', 'gsu_id_primary_group = ggp_id_group', array()) ->where('gro_id_track = ?', $filter['gr2t_id_track']) ->where('gsu_active = 1') //Only active surveys ->order('gro_id_order'); $fields['filler'] = new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)'); $select->columns($fields); if (array_key_exists('fillerfilter', $filter)) { $select->having('filler = ?', $filter['fillerfilter']); } $data = $this->db->fetchAll($select); if (! $data) { return $model; } $status = $this->util->getTokenData()->getStatusExpression(); $select = $this->db->select(); $select->from('gems__tokens', array( 'gto_id_respondent_track', 'gto_id_round', 'gto_id_token', 'status' => $status, 'gto_result', ))->joinInner('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array()) // ->where('grc_success = 1') ->where('gto_id_track = ?', $filter['gr2t_id_track']) ->order('grc_success') ->order('gto_id_respondent_track') ->order('gto_round_order'); // \MUtil_Echo::track($this->db->fetchAll($select)); $newModel = new \MUtil_Model_SelectModel($select, 'tok'); $newModel->setKeys(array('gto_id_respondent_track')); $transformer = new \MUtil_Model_Transform_CrossTabTransformer(); $transformer->addCrosstabField('gto_id_round', 'status', 'stat_') ->addCrosstabField('gto_id_round', 'gto_id_token', 'tok_') ->addCrosstabField('gto_id_round', 'gto_result', 'res_'); foreach ($data as $row) { $name = 'stat_' . $row['gro_id_round']; $transformer->set($name, 'label', \MUtil_Lazy::call('substr', $row['gsu_survey_name'], 0, 2), 'description', sprintf("%s\n[%s]", $row['gsu_survey_name'], $row['gro_round_description']), 'noSort', true, 'round', $row['gro_round_description'], 'roundIcon', $row['gro_icon_file'] ); $transformer->set('tok_' . $row['gro_id_round']); $transformer->set('res_' . $row['gro_id_round']); } $newModel->addTransformer($transformer); // \MUtil_Echo::track($data); $joinTrans = new \MUtil_Model_Transform_JoinTransformer(); $joinTrans->addModel($newModel, array('gr2t_id_respondent_track' => 'gto_id_respondent_track')); $model->resetOrder(); $model->set('gr2o_patient_nr'); $model->set('respondent_name'); $model->set('gr2t_start_date'); $model->addTransformer($joinTrans); // Add masking if needed $group = $this->currentUser->getGroup(); if ($group instanceof Group) { $group->applyGroupToModel($model, false); } return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
public function getExportModel() { $model = parent::getExportModel(); $statusColumns = $model->getColNames('label'); $everyStatus = $this->util->getTokenData()->getEveryStatus(); foreach ($statusColumns as $colName) { // For the compliance columns, we add the translation for the letter codes and move the decription to the label // This way the column shows the full survey name and round description if (substr($colName, 0, 5) == 'stat_') { $model->set($colName, 'multiOptions', $everyStatus, 'label', $model->get($colName, 'description')); } } return $model; }
Get the model for export and have the option to change it before using for export @return
entailment
public function checkRegistryRequestsAnswers() { // Make sure \Gems_User_User gets userLoader variable. $extras['userLoader'] = $this; // Make sure that this code keeps working when _initSession // is removed from GemsEscort if (! $this->session instanceof \Zend_Session_Namespace) { $this->session = new \Zend_Session_Namespace('gems.' . GEMS_PROJECT_NAME . '.session'); $idleTimeout = $this->project->getSessionTimeout(); $this->session->setExpirationSeconds($idleTimeout); $extras['session'] = $this->session; } $this->addRegistryContainer($extras); }
Should be called after answering the request to allow the Target to check if all required registry values have been set correctly. @return boolean False if required values are missing.
entailment
public function createUser($login_name, $organization, $userClassName, $userId) { $now = new \MUtil_Db_Expr_CurrentTimestamp();; $values['gul_user_class'] = $userClassName; $values['gul_can_login'] = 1; $values['gul_changed'] = $now; $values['gul_changed_by'] = $userId; $select = $this->db->select(); $select->from('gems__user_logins', array('gul_id_user')) ->where('gul_login = ?', $login_name) ->where('gul_id_organization = ?', $organization) ->limit(1); // Update class definition if it already exists if ($login_id = $this->db->fetchOne($select)) { $where = implode(' ', $select->getPart(\Zend_Db_Select::WHERE)); $this->db->update('gems__user_logins', $values, $where); } else { $values['gul_login'] = $login_name; $values['gul_id_organization'] = $organization; $values['gul_created'] = $now; $values['gul_created_by'] = $userId; $this->db->insert('gems__user_logins', $values); } return $this->getUser($login_name, $organization); }
Returns a user object, that may be empty if no user exist. @param string $login_name @param int $organization @param string $userClassName @param int $userId The person creating the user. @return \Gems_User_User Newly created
entailment
public function ensureDefaultUserValues(array $values, \Gems_User_UserDefinitionInterface $definition, $defName = null) { if (! isset($values['user_active'])) { $values['user_active'] = true; } if (! isset($values['user_staff'])) { $values['user_staff'] = $definition->isStaff(); } if (! isset($values['user_resetkey_valid'])) { $values['user_resetkey_valid'] = false; } if (! isset($values['user_two_factor_key'])) { $values['user_two_factor_key'] = null; } if (! isset($values['user_enable_2factor'])) { $values['user_enable_2factor'] = null; } if ($defName) { $values['__user_definition'] = $defName; } return $values; }
Makes sure default values are set for a user @param array $values @param \Gems_User_UserDefinitionInterface $definition @param string $defName Optional @return array
entailment
public function getAvailableStaffDefinitions() { $output = array( self::USER_STAFF => $this->translate->_('Db storage'), self::USER_RADIUS => $this->translate->_('Radius storage'), ); if ($this->project->getLdapSettings()) { $output[self::USER_LDAP] = $this->translate->_('LDAP'); } asort($output); return $output; }
Get userclass / description array of available UserDefinitions for staff @return array
entailment
public function getChangePasswordForm($user, $args_array = null) { $args = \MUtil_Ra::args(func_get_args(), array('user' => 'Gems_User_User')); $form = $this->_loadClass('Form_ChangePasswordForm', true, array($args)); return $form; }
Returns a change password form for this user @param \Gems_user_User $user @param mixed $args_array \MUtil_Ra::args array for LoginForm initiation. @return \Gems_User_Form_ChangePasswordForm
entailment
public final function getCurrentUser() { if (! self::$currentUser) { if ($this->session->__isset('__user_definition')) { $defName = $this->session->__get('__user_definition'); // Check for during upgrade. Remove for version 1.6 if (substr($defName, -10, 10) != 'Definition') { $defName .= 'Definition'; } self::$currentUser = $this->_loadClass('User', true, array($this->session, $this->_getClass($defName))); } else { if (\MUtil_Console::isConsole()) { if (! $this->project->isConsoleAllowed()) { echo "Accessing " . GEMS_PROJECT_NAME . " from the command line is not allowed.\n"; exit; } $request = \Zend_Controller_Front::getInstance()->getRequest(); if (($request instanceof \MUtil_Controller_Request_Cli) && $request->hasUserLogin()) { $user = $this->getUser($request->getUserName(), $request->getUserOrganization()); $authResult = $user->authenticate($request->getUserPassword()); if (! $authResult->isValid()) { echo "Invalid user login data.\n"; echo implode("\n", $authResult->getMessages()); exit; } self::$currentUser = $user; } elseif ($this->project->getConsoleRole()) { // \MUtil_Echo::track($this->request->getUserName(), $this->request->getUserOrganization()); self::$currentUser = $this->loadUser(self::USER_CONSOLE, 0, '(system)'); } } if (! self::$currentUser) { self::$currentUser = $this->getUser(null, self::SYSTEM_NO_ORG); } self::$currentUser->setAsCurrentUser(); } } return self::$currentUser; }
Get the currently loggin in user @return \Gems_User_User
entailment
public function getGroup($groupId) { static $groups = array(); if (! isset($groups[$groupId])) { $groups[$groupId] = $this->_loadClass('Group', true, array($groupId)); } return $groups[$groupId]; }
Returns a group object, initiated from the database or from Group::$_noGroup when the database does not yet exist. @param int $groupId Group id @return \Gems\User\Group
entailment
public function getOrganization($organizationId = null) { static $organizations = array(); if (null === $organizationId) { $user = $this->getCurrentUser(); if (! $user->isActive()) { // Check url only when not logged im $organizationId = $this->getOrganizationIdByUrl(); } if (! $organizationId) { $organizationId = intval($user->getCurrentOrganizationId()); } } if (! isset($organizations[$organizationId])) { $organizations[$organizationId] = $this->_loadClass( 'Organization', true, array($organizationId, $this->getAvailableStaffDefinitions()) ); } return $organizations[$organizationId]; }
Returns an organization object, initiated from the database or from self::$_noOrganization when the database does not yet exist. @param int $organizationId Optional, uses current user or url when empty @return \Gems_User_Organization
entailment
public function getOrganizationIdByUrl() { $urls = $this->getOrganizationUrls(); $current = $this->util->getCurrentURI(); if (isset($urls[$current])) { return $urls[$current]; } }
Returns the current organization according to the current site url. @return int An organization id or null
entailment
public function getOrganizationUrls() { static $urls; if (! is_array($urls)) { if ($this->cache) { $cacheId = GEMS_PROJECT_NAME . '__' . strtr(get_class($this), '\\/', '__') . '__organizations_url'; $urls = $this->cache->load($cacheId); } else { $cacheId = false; } // When we don't use cache or cache reports 'false' for a miss or expiration // then try to reload the data if ($cacheId === false || $urls === false) { $urls = array(); try { $data = $this->db->fetchPairs( "SELECT gor_id_organization, gor_url_base FROM gems__organizations WHERE gor_active=1 AND gor_url_base IS NOT NULL" ); } catch (\Zend_Db_Exception $zde) { // Table might not be filled $data = array(); } foreach ($data as $orgId => $urlsBase) { foreach (explode(' ', $urlsBase) as $url) { if ($url) { $urls[$url] = $orgId; } } } if ($cacheId) { $this->cache->save($urls, $cacheId, array('organization', 'organizations')); } } // \MUtil_Echo::track($urls); } return $urls; }
Returns the current organization according to the current site url. @static array $urls An array of url => orgId values @return array url => orgId
entailment
public function getResetRequestForm($args_array = null) { $args = \MUtil_Ra::args(func_get_args()); return $this->_loadClass('Form_ResetRequestForm', true, array($args)); }
Returns a reset form for handling both the incoming request and the outgoing reset request @param mixed $args_array \MUtil_Ra::args array for LoginForm initiation. @return \Gems_User_Form_ResetRequestForm
entailment
public function getTwoFactorAuthenticator($className) { $object = $this->_loadClass('TwoFactor_' . $className, true); if (! $object instanceof TwoFactorAuthenticatorInterface) { throw new \Gems_Exception_Coding(sprintf( 'The authenticator class %s should be an instance of TwoFactorAuthenticatorInterface.', $className )); } return $object; }
Get TwoFactorAuthenticatorInterface class @return Gems\User\TwoFactor\TwoFactorAuthenticatorInterface
entailment
public function getUser($login_name, $currentOrganization) { $user = $this->getUserClass($login_name, $currentOrganization); if ($this->allowLoginOnWithoutOrganization && (! $currentOrganization)) { $user->setCurrentOrganization($user->getBaseOrganizationId()); } else { // Check: can the user log in as this organization, if not load non-existing user if (! $user->isAllowedOrganization($currentOrganization)) { $user = $this->loadUser(self::USER_NOLOGIN, $currentOrganization, $login_name); } $user->setCurrentOrganization($currentOrganization); } return $user; }
Returns a user object, that may be empty if no user exist. @param string $login_name @param int $currentOrganization @return \Gems_User_User But ! ->isActive when the user does not exist
entailment
public function getUserByResetKey($resetKey) { if ((null == $resetKey) || (0 == strlen(trim($resetKey)))) { return $this->loadUser(self::USER_NOLOGIN, null, null); } $select = $this->db->select(); $select->from('gems__user_passwords', array()) ->joinLeft('gems__user_logins', 'gup_id_user = gul_id_user', array("gul_user_class", 'gul_id_organization', 'gul_login')) ->where('gup_reset_key = ?', $resetKey); if ($row = $this->db->fetchRow($select, null, \Zend_Db::FETCH_NUM)) { // \MUtil_Echo::track($row); return $this->loadUser($row[0], $row[1], $row[2]); } return $this->loadUser(self::USER_NOLOGIN, null, null); }
Get the user having the reset key specified @param string $resetKey @return \Gems_User_User But ! ->isActive when the user does not exist
entailment
public function getUserByStaffId($staff_id) { $data = $this->db->fetchRow("SELECT gsf_login, gsf_id_organization FROM gems__staff WHERE gsf_id_user = ?", $staff_id); // \MUtil_Echo::track($data); if (false == $data) { $data = array('gsf_login' => null, 'gsf_id_organization' => null); } return $this->getUser($data['gsf_login'], $data['gsf_id_organization']); }
Get a staff user using the $staff_id @param int $staff_id @return \Gems_User_User But ! ->isActive when the user does not exist
entailment
protected function getUserClass($login_name, $organization) { //First check for project user, as this one can run without a db if ((null !== $login_name) && $this->isProjectUser($login_name)) { return $this->loadUser(self::USER_PROJECT, $organization, $login_name); } if (null == $login_name) { return $this->loadUser(self::USER_NOLOGIN, $organization, $login_name); } if (!$this->allowLoginOnWithoutOrganization) { if ((null == $organization) || (! intval($organization))) { return $this->loadUser(self::USER_NOLOGIN, $organization, $login_name); } } try { $select = $this->getUserClassSelect($login_name, $organization); if ($row = $this->db->fetchRow($select, null, \Zend_Db::FETCH_NUM)) { if ($row[3] == 1 || $this->allowLoginOnOtherOrganization === true) { // \MUtil_Echo::track($row); return $this->loadUser($row[0], $row[1], $row[2]); } } } catch (\Zend_Db_Exception $e) { // Intentional fall through } return $this->loadUser(self::USER_NOLOGIN, $organization, $login_name); }
Returns the name of the user definition class of this user. @param string $login_name @param int $organization @return \Gems_User_User But ! ->isActive when the user does not exist
entailment