sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getTokenAnswerLinkForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge, $keepCaps = false) { if (! $this->currentUser->hasPrivilege($this->_getAnswerMenuItem()->getPrivilege())) { return null; } return \MUtil_Lazy::method($this, 'getTokenAnswerLink', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status'), $keepCaps ); }
De a lazy answer link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @param boolean $keepCaps Keep the capital letters in the label @return \MUtil_Lazy_Call
entailment
public function getTokenAskButton($tokenId, $tokenStatus, $staffToken, $keepCaps) { if ('O' == $tokenStatus || 'P' == $tokenStatus) { if ($staffToken) { $menuItem = $this->_getAskMenuItem(); $label = $menuItem->get('label'); if ('P' == $tokenStatus) { $label = $this->_('Continue'); } $link = $menuItem->toActionLink( ($keepCaps ? $label : strtolower($label)), [ 'gto_id_token' => $tokenId, 'can_be_taken' => 1, \Gems_Model::ID_TYPE => 'token', ]); if ($link) { $link->title = sprintf($this->_('Answer token %s'), strtoupper($tokenId)); return $link; } } return $this->getTokenCopyLink($tokenId, $tokenStatus); } }
Generate a menu link for answers pop-up @param string $tokenId @param string $tokenStatus @param boolean $staffToken Is token answerable by staff @param boolean $keepCaps Keep the capital letters in the label @return \MUtil_Html_AElement
entailment
public function getTokenAskButtonForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge, $forceButton = false, $keepCaps = false) { if (! $this->currentUser->hasPrivilege($this->_getAskMenuItem()->getPrivilege())) { return null; } if ($forceButton) { return \MUtil_Lazy::method($this, 'getTokenAskButton', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status'), true, $keepCaps ); } return \MUtil_Lazy::method($this, 'getTokenAskButton', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status'), $bridge->getLazy('ggp_staff_members'), $keepCaps ); }
De a lazy answer link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @param boolean $forceButton Always show a button @param boolean $keepCaps Keep the capital letters in the label @return \MUtil_Lazy_Call
entailment
public function getTokenAskLinkForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge, $forceButton = false, $keepCaps = false) { $method = $this->getTokenAskButtonForBridge($bridge, $forceButton, $keepCaps); if (! $method) { $method = \MUtil_Lazy::method($this, 'getTokenCopyLink', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status') ); } return [ $method, 'class' => \MUtil_Lazy::method($this, 'getTokenCopyLinkClass', $bridge->getLazy('token_status'), $bridge->getLazy('ggp_staff_members') ), ]; }
De a lazy answer link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @param boolean $forceButton Always show a button @param boolean $keepCaps Keep the capital letters in the label @return \MUtil_Lazy_Call
entailment
public function getTokenEmailLink($tokenId, $tokenStatus, $canMail) { if ($canMail && ('O' == $tokenStatus || 'P' == $tokenStatus)) { $menuItem = $this->_getEmailMenuItem(); $link = $menuItem->toActionLinkLower([ 'gto_id_token' => $tokenId, 'can_be_taken' => 1, 'can_email' => 1, \Gems_Model::ID_TYPE => 'token', ]); if ($link) { $link->title = sprintf($this->_('Send email for token %s'), strtoupper($tokenId)); return $link; } } }
Generate a menu link for email screen @param string $tokenId @param string $tokenStatus @param boolean $canMail @return \MUtil_Html_AElement
entailment
public function getTokenEmailLinkForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge) { if (! $this->currentUser->hasPrivilege($this->_getEmailMenuItem()->getPrivilege())) { return null; } return \MUtil_Lazy::method($this, 'getTokenEmailLink', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status'), $bridge->getLazy('can_email') ); }
De a lazy answer link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @return \MUtil_Lazy_Call
entailment
public function getTokenShowLink($tokenId, $plusLabel) { $menuItem = $this->_getShowMenuItem(); if ($plusLabel) { $link = $menuItem->toActionLink( \MUtil_Html::create()->strong($this->_('+')), [ 'gto_id_token' => $tokenId, \Gems_Model::ID_TYPE => 'token', ] ); } else { $link = $menuItem->toActionLinkLower([ 'gto_id_token' => $tokenId, \Gems_Model::ID_TYPE => 'token', ]); } if ($link) { $link->title = sprintf($this->_('Inspect token %s'), strtoupper($tokenId)); } return $link; }
Generate a menu link for answers pop-up @param string $tokenId @param boolean $plusLabel Show plus instead of label @return \MUtil_Html_AElement
entailment
public function getTokenShowLinkForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge, $plusLabel = true) { if (! $this->currentUser->hasPrivilege($this->_getShowMenuItem()->getPrivilege())) { return null; } return \MUtil_Lazy::method($this, 'getTokenShowLink', $bridge->getLazy('gto_id_token'), $plusLabel); }
De a lazy show link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @param boolean $plusLabel Show plus instead of label @return \MUtil_Lazy_Call
entailment
public function getTokenStatusDescriptionForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge, $addDescription = false) { return \MUtil_Lazy::method($this, 'getStatusDescription', $bridge->getLazy('token_status')); }
De a lazy status description text for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @param boolean $addDescription Add the description after the icon @return \MUtil_Lazy_Call
entailment
public function getTokenStatusLink($tokenId, $tokenStatus, $patientNr, $roundDescr, $surveyName, $result) { $menuItem = $this->_getShowMenuItem(); if ($tokenId && $menuItem) { $href = $menuItem->toHRefAttribute([ 'gto_id_token' => $tokenId, \Gems_Model::ID_TYPE => 'token', ]); $link = \MUtil_Html::create('a', $href, [ 'onclick' => 'event.cancelBubble = true;', ]); // $link->title = sprintf($this->_('Inspect token %s'), strtoupper($tokenId)); } else { $link = \MUtil_Html::create('span', [ 'onclick' => 'event.cancelBubble = true;', ]); } if ($link) { $link->append($this->getStatusIcon($tokenStatus)); $link->title = $this->getTokenStatusTitle($tokenId, $tokenStatus, $patientNr, $roundDescr, $surveyName, $result); return $link; } }
Generate a menu link for answers pop-up @param string $tokenId @param string $tokenStatus @param string $patientNr @param string $roundDescr @param string $surveyName @param string $result @return \MUtil_Html_AElement
entailment
public function getTokenStatusLinkForBridge(\MUtil_Model_Bridge_TableBridgeAbstract $bridge) { if (! $this->currentUser->hasPrivilege($this->_getShowMenuItem()->getPrivilege())) { return $this->getTokenStatusShowForBridge($bridge); } return \MUtil_Lazy::method($this, 'getTokenStatusLink', $bridge->getLazy('gto_id_token'), $bridge->getLazy('token_status'), $bridge->getLazy('gr2o_patient_nr'), $bridge->getLazy('gto_round_description'), $bridge->getLazy('gsu_survey_name'), $bridge->getLazy('gto_result') ); }
De a lazy status show link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @return \MUtil_Lazy_Call
entailment
public function getTokenStatusLinkForTokenId($tokenId) { $token = $tokenId ? $this->loader->getTracker()->getToken($tokenId) : null; if (! ($tokenId && $token->exists)) { return $this->getStatusIcon('D'); } return $this->getTokenStatusLink( $tokenId, $token->getStatusCode(), $token->getPatientNumber(), $token->getRoundDescription(), $token->getSurveyName(), $token->getResult() ); }
De a lazy status show link for bridges @param \MUtil_Model_Bridge_TableBridgeAbstract $bridge @return \MUtil_Lazy_Call
entailment
public function getBrowseColumns() { // Newline placeholder $br = \MUtil_Html::create('br'); $sp = \MUtil_Html::raw(' '); $columns[10] = array('glo_name', $br, 'glo_organizations'); $columns[20] = array('glo_url', $br, 'glo_url_route'); $columns[30] = array('glo_address_1', $br, 'glo_zipcode', \MUtil_Html::raw('  '), 'glo_city'); $columns[40] = array(\MUtil_Html::raw('☏ '), 'glo_phone_1', $br, 'glo_filter', $sp, 'glo_match_to'); return $columns; }
Set column usage to use for the browser. Must be an array of arrays containing the input for TableBridge->setMultisort() @return array or false
entailment
protected function createModel($detailed, $action) { $model = new \MUtil_Model_TableModel('gems__locations'); $yesNo = $this->util->getTranslated()->getYesNo(); \Gems_Model::setChangeFieldsByPrefix($model, 'glo'); $model->setDeleteValues('glo_active', 0); $model->set('glo_name', 'label', $this->_('Location'), 'required', true ); $model->set('glo_organizations', 'label', $this->_('Organizations'), 'description', $this->_('Checked organizations see this organizations respondents.'), 'elementClass', 'MultiCheckbox', 'multiOptions', $this->util->getDbLookup()->getOrganizations(), 'noSort', true ); $tp = new \MUtil_Model_Type_ConcatenatedRow(':', ', '); $tp->apply($model, 'glo_organizations'); $model->setIfExists('glo_match_to', 'label', $this->_('Import matches'), 'description', $this->_("Split multiple import matches using '|'.") ); $model->setIfExists('glo_code', 'label', $this->_('Location code'), 'size', 10, 'description', $this->_('Optional code name to link the location to program code.')); $model->setIfExists('glo_url', 'label', $this->_('Location url'), 'description', $this->_('Complete url for location: http://www.domain.etc'), 'validator', 'Url'); $model->setIfExists('glo_url_route', 'label', $this->_('Location route url'), 'description', $this->_('Complete url for route to location: http://www.domain.etc'), 'validator', 'Url'); $model->setIfExists('glo_address_1', 'label', $this->_('Street')); $model->setIfExists('glo_address_2', 'label', ' '); $model->setIfExists('glo_zipcode', 'label', $this->_('Zipcode'), 'size', 7, 'description', $this->_('E.g.: 0000 AA'), 'filter', new \Gems_Filter_DutchZipcode() ); $model->setIfExists('glo_city', 'label', $this->_('City')); $model->setIfExists('glo_region', 'label', $this->_('Region')); $model->setIfExists('glo_iso_country', 'label', $this->_('Country'), 'multiOptions', $this->util->getLocalized()->getCountries()); $model->setIfExists('glo_phone_1', 'label', $this->_('Phone')); $model->setIfExists('glo_phone_2', 'label', $this->_('Phone 2')); $model->setIfExists('glo_phone_3', 'label', $this->_('Phone 3')); $model->setIfExists('glo_phone_4', 'label', $this->_('Phone 4')); $model->setIfExists('glo_active', 'label', $this->_('Active'), 'description', $this->_('Inactive means assignable only through automatich processes.'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo ); $model->setIfExists('glo_filter', 'label', $this->_('Filter'), 'description', $this->_('When checked appointments with these locations are not imported.'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo ); $model->addColumn("CASE WHEN glo_active = 1 THEN '' ELSE 'deleted' END", 'row_class'); 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 addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { // Add link to patient to overview $menuItems = $this->findMenuItems('respondent', 'show'); if ($menuItems) { $menuItem = reset($menuItems); if ($menuItem instanceof \Gems_Menu_SubMenuItem) { $href = $menuItem->toHRefAttribute($bridge); if ($href) { $aElem = new \MUtil_Html_AElement($href); $aElem->setOnEmpty(''); // Make sure org is known $model->get('gr2o_id_organization'); $model->set('gr2o_patient_nr', 'itemDisplay', $aElem); $model->set('respondent_name', 'itemDisplay', $aElem); } } } $tUtil = $this->util->getTokenData(); $table = $bridge->getTable(); $table->appendAttrib('class', 'compliance'); $thead = $table->thead(); $th_row = $thead->tr(array('class' => 'rounds')); $th = $th_row->td(); $span = 1; $cRound = null; $cDesc = null; $thead->tr(); if ($showMenuItem = $this->getShowMenuItem()) { $bridge->addItemLink($showMenuItem->toActionLinkLower($this->request, $bridge)); } // Initialize alter $alternateClass = new \MUtil_Lazy_Alternate(array('odd', 'even')); foreach($model->getItemsOrdered() as $name) { if ($label = $model->get($name, 'label')) { $round = $model->get($name, 'round'); if ($round == $cRound) { $span++; $class = null; } else { // If the round has an icon, show the icon else just 'R' since // complete round description messes up the display $th->append($cDesc); $th->title = $cRound; $th->colspan = $span; $span = 1; $cRound = $round; if ($cIcon = $model->get($name, 'roundIcon')) { $cDesc = \MUtil_Html_ImgElement::imgFile($cIcon, array( 'alt' => $cRound, 'title' => $cRound )); } else { if (substr($name, 0, 5) == 'stat_') { $cDesc = 'R'; } else { $cDesc = null; } } $class = 'newRound'; $thClass = $class .' ' . $alternateClass; // Add alternate class only for th $th = $th_row->td(array('class' => $thClass)); } if ($model->get($name, 'noSort')) { $result = 'res_' . substr($name, 5); $token = 'tok_' . substr($name, 5); $tds = $bridge->addColumn( \MUtil_Lazy::method($tUtil, 'getTokenStatusLinkForTokenId', $bridge->$token), array($label, 'title' => $model->get($name, 'description'), 'class' => 'round') ); } else { $tds = $bridge->addSortable($name, $label); } if ($class) { $tds->appendAttrib('class', $class); } } } $th->append($cRound); $th->colspan = $span; }
Adds columns from the model to the bridge that creates the browse table. Overrule this function to add different columns to the browse table, without having to recode the core table building code. @param \MUtil_Model_Bridge_TableBridge $bridge @param \MUtil_Model_ModelAbstract $model @return void
entailment
public function andIf($master = null) { if ($this->logicalOperator == "or") { throw new Exception("ValidationLogicCriteria: Cannot declare a logical operator more than once. (Specified andIf() after calling orIf()). Use a nested ValidationLogicCriteriaSet to combine conjunctive and disjuctive logic."); } if ($master) { $this->master = $master; } $this->logicalOperator = "and"; return $this; }
Adds a new criterion, and makes this set use conjuctive logic @param string $master The master form field @return ValidationLogicCriteria
entailment
public function orIf($master = null) { if ($this->logicalOperator == "and") { throw new Exception("ValidationLogicCriteria: Cannot declare a logical operator more than once. (Specified orIf() after calling andIf()). Use a nested ValidationLogicCriteriaSet to combine conjunctive and disjuctive logic."); } if ($master) { $this->master = $master; } $this->logicalOperator = "or"; return $this; }
Adds a new criterion, and makes this set use disjunctive logic @param string $master The master form field @return ValidationLogicCriteria
entailment
public function getMasterList() { $list = array(); foreach ($this->getCriteria() as $c) { if ($c instanceof ValidationLogicCriteria) { $list += $c->getMasterList(); } else { $list[] = $c->getMaster(); } } return $list; }
Gets a list of all the master fields in this criteria set @return string
entailment
private function _ensureGroupData($reload = false) { if ($reload || (! isset($this->_gemsSurvey['ggp_id_group']))) { $sql = "SELECT * FROM gems__groups WHERE ggp_id_group = ?"; $code = $this->_gemsSurvey['gsu_id_primary_group']; if ($code) { $row = $this->db->fetchRow($sql, $code); } else { $row = false; } if ($row) { $this->_gemsSurvey = $row + $this->_gemsSurvey; } else { // Add default empty row $this->_gemsSurvey = array( 'ggp_id_group' => false, 'ggp_name' => '', 'ggp_description' => '', 'ggp_role' => 'respondent', 'ggp_group_active' => 0, 'ggp_respondent_members' => 1, 'ggp_staff_members' => 0) + $this->_gemsSurvey; } } }
Makes sure the group data is part of the $this->_gemsSurvey @param boolean $reload Optional parameter to force reload.
entailment
private function _updateSurvey(array $values, $userId) { if ($this->tracker->filterChangesOnly($this->_gemsSurvey, $values)) { if (\Gems_Tracker::$verbose) { $echo = ''; foreach ($values as $key => $val) { $old = isset($this->_gemsSurvey[$key]) ? $this->_gemsSurvey[$key] : null; $echo .= $key . ': ' . $old . ' => ' . $val . "\n"; } \MUtil_Echo::r($echo, 'Updated values for ' . $this->_surveyId); } if (! isset($values['gsu_changed'])) { $values['gsu_changed'] = new \MUtil_Db_Expr_CurrentTimestamp(); } if (! isset($values['gsu_changed_by'])) { $values['gsu_changed_by'] = $userId; } if ($this->exists) { // Update values in this object $this->_gemsSurvey = $values + $this->_gemsSurvey; // return 1; return $this->db->update('gems__surveys', $values, array('gsu_id_survey = ?' => $this->_surveyId)); } else { if (! isset($values['gsu_created'])) { $values['gsu_created'] = new \MUtil_Db_Expr_CurrentTimestamp(); } if (! isset($values['gsu_created_by'])) { $values['gsu_created_by'] = $userId; } // Update values in this object $this->_gemsSurvey = $values + $this->_gemsSurvey; // Remove the Gems survey id unset($this->_gemsSurvey['gsu_id_survey']); $this->_surveyId = $this->db->insert('gems__surveys', $this->_gemsSurvey); $this->_gemsSurvey['gsu_id_survey'] = $this->_surveyId; $this->exists = true; return 1; } } else { return 0; } }
Update the survey, both in the database and in memory. @param array $values The values that this token should be set to @param int $userId The current user @return int 1 if data changed, 0 otherwise
entailment
public function calculateHash() { $answerModel = $this->getAnswerModel('en'); foreach($answerModel->getItemsOrdered() as $item) { $result = $answerModel->get($item, ['label', 'type', 'multiOptions', 'parent_question', 'thClass', 'group', 'description']); if (array_key_exists('label', $result)) { $items[$item] = $result; } } $hash = md5(serialize($items)); return $hash; }
Calculate a hash for this survey, taking into account the questions and answers @return string
entailment
public function checkRegistryRequestsAnswers() { if ($this->db && (! $this->_gemsSurvey)) { $result = $this->db->fetchRow("SELECT * FROM gems__surveys WHERE gsu_id_survey = ?", $this->_surveyId); if ($result) { $this->_gemsSurvey = $result; $this->exists = true; } else { //Row not present, try with empty array? or should we throw an error? $this->_gemsSurvey = array( 'gsu_code' => null, 'gsu_valid_for_length' => 6, 'gsu_valid_for_unit' => 'M', ); $this->exists = false; } } return (boolean) $this->_gemsSurvey; }
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 are missing.
entailment
public function copyTokenToSource(\Gems_Tracker_Token $token, $language) { $source = $this->getSource(); return $source->copyTokenToSource($token, $language, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Inserts the token in the source (if needed) and sets those attributes the source wants to set. @param \Gems_Tracker_Token $token @param string $language @return int 1 of the token was inserted or changed, 0 otherwise @throws \Gems_Tracker_Source_SurveyNotFoundException
entailment
public function getAnswerDateTime($fieldName, \Gems_Tracker_Token $token) { $source = $this->getSource(); return $source->getAnswerDateTime($fieldName, $token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns a field from the raw answers as a date object. @param string $fieldName Name of answer field @param \Gems_Tracker_Token $token Gems token object @return \MUtil_Date date time or null
entailment
public function getAnswerSnippetNames(\Gems_Tracker_Token $token) { if (isset($this->_gemsSurvey['gsu_display_event'])) { $event = $this->events->loadSurveyDisplayEvent($this->_gemsSurvey['gsu_display_event']); return $event->getAnswerDisplaySnippets($token); } }
Returns a snippet name that can be used to display the answers to the token or nothing. @param \Gems_Tracker_Token $token @return array Of snippet names
entailment
public function getAnswerModel($language) { $source = $this->getSource(); return $source->getSurveyAnswerModel($this, $language, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns a model for displaying the answers to this survey in the requested language. @param string $language (ISO) language string @return \MUtil_Model_ModelAbstract
entailment
public function getCompletionTime(\Gems_Tracker_Token $token) { $source = $this->getSource(); return $source->getCompletionTime($token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
The time the survey was completed according to the source @param \Gems_Tracker_Token $token Gems token object @return \MUtil_Date date time or null
entailment
public function getDatesList($language) { $source = $this->getSource(); return $source->getDatesList($language, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns an array containing fieldname => label for each date field in the survey. Used in dropdown list etc.. @param string $language (ISO) language string @return array Returns an array of the strings datename => label
entailment
public function getInsertDateUntil(\MUtil_Date $from) { return Period::applyPeriod( $from, $this->_gemsSurvey['gsu_valid_for_unit'], $this->_gemsSurvey['gsu_valid_for_length'] ); }
Calculate the until date for single survey insertion @param \MUtil_Date $from @return \MUtil_Date
entailment
public function getQuestionInformation($language) { return $this->getSource()->getQuestionInformation($language, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns an array of array with the structure: question => string, class => question|question_sub group => is for grouping type => (optional) source specific type answers => string for single types, array for selection of, nothing for no answer @param string $language (ISO) language string @return array Nested array
entailment
public function getQuestionList($language) { return $this->getSource()->getQuestionList($language, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns a fieldlist with the field names as key and labels as array. @param string $language (ISO) language string @return array of fieldname => label type
entailment
public function getRawTokenAnswerRow($tokenId) { $source = $this->getSource(); return $source->getRawTokenAnswerRow($tokenId, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns the answers in simple raw array format, without value processing etc. Function may return more fields than just the answers. @param string $tokenId Gems Token Id @return array Field => Value array
entailment
public function getRawTokenAnswerRows($filter = array()) { $source = $this->getSource(); return $source->getRawTokenAnswerRows((array) $filter, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns the answers of multiple tokens in simple raw nested array format, without value processing etc. Function may return more fields than just the answers. @param array $filter XXX @return array Of nested Field => Value arrays indexed by tokenId
entailment
public function getRawTokenAnswerRowsCount($filter = array()) { $source = $this->getSource(); return $source->getRawTokenAnswerRowsCount((array) $filter, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns the number of answers of multiple tokens @param array $filter XXX @return array Of nested Field => Value arrays indexed by tokenId
entailment
public function getStartTime(\Gems_Tracker_Token $token) { $source = $this->getSource(); return $source->getStartTime($token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
The time the survey was started according to the source @param \Gems_Tracker_Token $token Gems token object @return \MUtil_Date date time or null
entailment
public function inSource(\Gems_Tracker_Token $token) { $source = $this->getSource(); return $source->inSource($token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Checks whether the token is in the source. @param \Gems_Tracker_Token $token Gems token object @return boolean
entailment
public function isCompleted(\Gems_Tracker_Token $token) { $source = $this->getSource(); return $source->isCompleted($token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id']); }
Returns true if the survey was completed according to the source @param \Gems_Tracker_Token $token Gems token object @return boolean True if the token has completed
entailment
public function updateConsent(\Gems_Tracker_Token $token, $consentCode = null) { $source = $this->getSource(); return $source->updateConsent($token, $this->_surveyId, $this->_gemsSurvey['gsu_surveyor_id'], $consentCode); }
Updates the consent code of the the token in the source (if needed) @param \Gems_Tracker_Token $token @param string $consentCode Optional consent code, otherwise code from token is used. @return int 1 of the token was inserted or changed, 0 otherwise
entailment
public function checkRegistryRequestsAnswers() { if ($this->token instanceof \Gems_Tracker_Token) { $this->wasAnswered = $this->token->isCompleted(); return ($this->request instanceof \Zend_Controller_Request_Abstract) && ($this->view instanceof \Zend_View) && parent::checkRegistryRequestsAnswers(); } else { return false; } }
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 are missing.
entailment
public function formatCompletion(\MUtil_Date $dateTime) { $days = abs($dateTime->diffDays()); switch ($days) { case 0: return $this->_('We have received your answers today. Thank you!'); case 1: return $this->_('We have received your answers yesterday. Thank you!'); case 2: return $this->_('We have received your answers 2 days ago. Thank you.'); default: if ($days <= 14) { return sprintf($this->_('We have received your answers %d days ago. Thank you.'), $days); } return sprintf($this->_('We have received your answers on %s. '), $dateTime->toString($this->dateFormat)); } }
Formats an completion date for this display @param \MUtil_Date $dateTime @return string
entailment
public function formatUntil(\MUtil_Date $dateTime = null) { if (false === $this->showUntil) { return; } if (null === $dateTime) { return $this->_('Survey has no time limit.'); } $days = $dateTime->diffDays(); switch ($days) { case 0: return array( \MUtil_Html::create('strong', $this->_('Warning!!!')), ' ', $this->_('This survey must be answered today!') ); case 1: return array( \MUtil_Html::create('strong', $this->_('Warning!!')), ' ', $this->_('This survey can only be answered until tomorrow!') ); case 2: return $this->_('Warning! This survey can only be answered for another 2 days!'); default: if ($days <= 14) { return sprintf($this->_('Please answer this survey within %d days.'), $days); } if ($days <= 0) { return $this->_('This survey can no longer be answered.'); } return sprintf($this->_('Please answer this survey before %s.'), $dateTime->toString($this->dateFormat)); } }
Formats an until date for this display @param \MUtil_Date $dateTime @return string
entailment
protected function getTokenHref(\Gems_Tracker_Token $token) { /*************** * Get the url * ***************/ $params = array( $this->request->getActionKey() => 'to-survey', \MUtil_Model::REQUEST_ID => $token->getTokenId(), 'RouteReset' => false, ); return new \MUtil_Html_HrefArrayAttribute($params); }
Get the href for a token @param \Gems_Tracker_Token $token @return \MUtil_Html_HrefArrayAttribute
entailment
protected function _getOrgTo($monitorName) { switch ($monitorName) { case 'maintenancemode': $where = "1 = 0"; break; case 'cronmail': default: $where = 'gor_mail_watcher = 1'; break; } $orgTo = $this->db->fetchCol( "SELECT DISTINCT gor_contact_email FROM gems__organizations WHERE LENGTH(gor_contact_email) > 5 AND gor_active = 1 AND $where" ); return $orgTo; }
Return an array of organization recipients for the given monitorName @param string $monitorName @return array
entailment
protected function _getMailTo($monitorName) { $projTo = explode(',',$this->project->getMonitorTo($monitorName)); $userTo = $this->_getUserTo($monitorName); $orgTo = $this->_getOrgTo($monitorName); $mailtos = array_merge($projTo, $userTo, $orgTo); return array_values(array_unique(array_filter(array_map('trim',$mailtos)))); }
Get the mail addresses for a monitor @param string $monitorName ProjectSettings name @param string $where Optional, a gems__staff SQL WHERE statement @return array
entailment
protected function _getUserTo($monitorName) { switch ($monitorName) { case 'maintenancemode': $roles = $this->util->getDbLookup()->getRolesByPrivilege('pr.maintenance.maintenance-mode'); if ($roles) { $joins = "JOIN gems__groups ON gsf_id_primary_group = ggp_id_group JOIN gems__roles ON ggp_role = grl_id_role"; $where = 'grl_name IN (' . implode(', ', array_map(array($this->db, 'quote'), array_keys($roles))) . ')'; } else { return []; } break; case 'cronmail': default: $joins = ''; $where = 'gsf_mail_watcher = 1'; break; } $userTo = $this->db->fetchCol( "SELECT DISTINCT gsf_email FROM gems__staff $joins WHERE LENGTH(gsf_email) > 5 AND gsf_active = 1 AND $where" ); return $userTo; }
Return an array of user recipients for the given monitorName @param string $monitorName @return array
entailment
public function getReverseMaintenanceMonitorTemplate($locale) { switch ($locale) { case 'nl': $initSubject = "{name} is aangezet"; $initBbText = "L.S., De [b]{name}[/b] is op {setTime} aangezet. Zolang dit aan blijft staan kan u regelmatig waarschuwingen krijgen. Dit is een automatisch bericht."; $subject = "{name} staat al meer dan {periodHours} uur aan"; $messageBbText = "L.S., De [b]{name}[/b] is op {setTime} aangezet en staat nog steeds aan. Dit is waarschuwing nummer [b]{mailCount}[/b]. Controleer s.v.p. of de onderhouds modus nog steeds nodig is. Dit is een automatische waarschuwing."; break; default: $initSubject = "{name} has been turned on"; $initBbText = "L.S., The [b]{name}[/b] was activated at {setTime}. As long as maintenance mode is active the system may send you warning messages. This messages was send automatically."; $subject = "{name} has been active for over {periodHours} hours"; $messageBbText = "L.S., The [b]{name}[/b] was activated at {setTime} and is still active. This is notice number {mailCount}. Please check whether the maintenance mode is still required. This messages was send automatically."; break; } return array($initSubject, $initBbText, $subject, $messageBbText); }
Return the mail template to use for sending ReverseMaintenanceMonitor messages There are two messages, the message when the maintenance mode is first turned on and the one that is sent after the set amount of time when the maintenance mode is still turned on. @param string $locale The locale to use for the message @return array with elements $initSubject, $initBbText, $subject and $messageBbText
entailment
public function reverseMaintenanceMonitor() { $job = $this->getReverseMaintenanceMonitor(); $lock = $this->util->getMaintenanceLock(); if ($lock->isLocked()) { $job->stop(); $lock->unlock(); return false; } $lock->lock(); $to = $this->_getMailTo('maintenancemode'); if (!$to) { return true; } $locale = $this->project->getLocaleDefault(); list($initSubject, $initBbText, $subject, $messageBbText) = $this->getReverseMaintenanceMonitorTemplate($locale); $job->setFrom($this->project->getMonitorFrom('maintenancemode')) ->setMessage($messageBbText) ->setPeriod($this->project->getMonitorPeriod('maintenancemode')) ->setSubject($subject) ->setTo($to); if ($job->start()) { $job->sendOtherMail($initSubject, $initBbText); } return true; }
Start the cron mail monitor @return boolean True when the job was started
entailment
public function startCronMailMonitor() { $to = $this->_getMailTo('cronmail'); $job = $this->getCronMailMonitor(); if (! $to) { $job->stop(); return false; } $locale = $this->project->getLocaleDefault(); list($subject, $messageBbText) = $this->getCronMailTemplate($locale); $job->setFrom($this->project->getMonitorFrom('cronmail')) ->setMessage($messageBbText) ->setPeriod($this->project->getMonitorPeriod('cronmail')) ->setSubject($subject) ->setTo($to) ->start(); return true; }
Start the cron mail monitor @return boolean True when the job was started
entailment
public static function solve(array $sudoku, $checkInput = false) { if($checkInput && !self::checkInput($sudoku)) { throw new \InvalidArgumentException('The input is no valid Sudoku array.'); } return self::recursive_solve($sudoku, count($sudoku)); }
Solves the Sudoku. @param array $sudoku @param bool $checkInput If true, the input gets checked for a valid Sudoku array, i.e. if it's a two dimensional square array containing only int and null values @return array|false Returns the solution or false if the sudoku is not solvable. @throws \InvalidArgumentException
entailment
public static function generate($size, $difficulty, $seed = null) { list($task,) = self::generateWithSolution($size, $difficulty, $seed); return $task; }
Wrapper that calls Sudoku::generateWithSolution, but returns only the task. @param $size @param $difficulty @param null $seed @return mixed
entailment
public static function checkSolution(array $solution, array $task = null) { if(!self::checkInput($solution)) { throw new \InvalidArgumentException('Input is no Sudoku array.'); } $dim = count($solution); if($task !== null) { if(count($task) !== $dim) return false; for($i = 0; $i < $dim; $i++) { for($j = 0; $j < $dim; $j++) { if($task[$i][$j] !== null && $solution[$i][$j] !== $task[$i][$j]) return false; } } } // check rows for($row = 0; $row < $dim; $row++) { $valueFound = array_fill(1,$dim,false); for($col = 0; $col < $dim; $col++) { // null check is only needed here if($solution[$row][$col] === null || $valueFound[$solution[$row][$col]] === true) return false; else $valueFound[$solution[$row][$col]] = true; } } // check columns for($col = 0; $col < $dim; $col++) { $valueFound = array_fill(1,$dim,false); for($row = 0; $row < $dim; $row++) { if($valueFound[$solution[$row][$col]] === true) return false; else $valueFound[$solution[$row][$col]] = true; } } // check blocks $blockSize = self::$blockSizes[$dim]; for($row = 0; $row < $dim; $row += $blockSize) { for($col = 0; $col < $dim; $col += $blockSize) { $valueFound = array_fill(1,$dim,false); for($blockRow = 0; $blockRow < $blockSize;$blockRow++) { for($blockCol = 0; $blockCol < $blockSize;$blockCol++) { if($valueFound[$solution[$row+$blockRow][$col+$blockCol]] === true) return false; else $valueFound[$solution[$row+$blockRow][$col+$blockCol]] = true; } } } } return true; }
Checks if the input is a valid sudoku solution. @param array $solution The solution to be checked @param array $task The task that should be result in the solution. If provided, it is checked if the solution relates to the task @return bool @throws \InvalidArgumentException
entailment
private static function array_shuffle(array &$array) { for($i = count($array) - 1; $i > 0; $i--) { $j = mt_rand(0,$i); $temp = $array[$i]; $array[$i] = $array[$j]; $array[$j] = $temp; } }
Shuffles an array using the Fisher-Yates-Algorithm and mt_rand(). So it is affected by the seed set by mt_srand(). This means the result is reproducible. @param array $array
entailment
public static function checkInput(array &$inputSudoku) { $rowCount = count($inputSudoku); if(!in_array($rowCount,self::$dimensions,true)) { return false; } foreach($inputSudoku as &$row) { // check dimensions if(!is_array($row) || count($row) !== $rowCount) { return false; } // check types foreach($row as &$item) { if($item === null) { continue; } if(!is_int($item)) { $item = (int) $item; } if($item < 1 || $item > $rowCount) { return false; } } } return true; }
Checks if the input is an actual sudoku. i.e. The input array has two dimensions, is quadratic and contains only integers between 1 and the number of rows/columns. This function also casts all non null values to int, such that a valid input containing stings works fine. @param array $inputSudoku @return bool
entailment
protected function getConditions() { $conditionLoader = $this->loader->getConditions(); $conditions = []; for ($number = 1; $number <= 4; $number++) { $element = 'gcon_condition_text' . $number; $conditionId = (int) $this->_data[$element]; if ($conditionId >0) { $conditions[] = $conditionLoader->loadCondition($conditionId); } } return $conditions; }
Load the conditions @return \Gems\Condition\RoundConditionInterface[]
entailment
public function isValid($conditionId, $context) { $conditions = $this->getConditions(); $valid = true; foreach($conditions as $condition) { $valid = $valid && $condition->isValid($conditionId, $context); } return $valid; }
Does this track have the fieldcode the condition depends on? @param type $conditionId @param type $context @return boolean
entailment
public function find() { foreach ($this->getSupportedMailers() as $mailer) { $class = Helper::getMailerClassName($mailer); if (class_exists($class)) { $this->register($mailer); } } ksort($this->mailers); return $this->all(); }
Automatically find and register all officially supported mailers @return array An array of mailer names
entailment
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model) { // Signal the bridge that we need these values $bridge->gr2t_id_respondent_track; $bridge->gr2t_id_respondent_track; $bridge->gr2o_patient_nr; $bridge->can_edit; $controller = $this->request->getControllerName(); $menuList = $this->menu->getMenuList(); $menuList->addByController($controller, 'show-track') ->addByController($controller, 'edit-track') ->addParameterSources($bridge) ->setLowerCase()->showDisabled(); $bridge->setOnEmpty($this->_('No other assignments of this track.')); // If we have a track Id and is not excluded: mark it! if ($this->respondentTrackId && (! $this->excludeCurrent)) { $bridge->tr()->appendAttrib('class', \MUtil_Lazy::iff(\MUtil_Lazy::comp($bridge->gr2t_id_respondent_track, '==', $this->respondentTrackId), 'currentRow', null)); } // Add show-track button if allowed, otherwise show, again if allowed $bridge->addItemLink($menuList->getActionLink($controller, 'show-track')); parent::addBrowseTableColumns($bridge, $model); // Add edit-track button if allowed (and not current $bridge->addItemLink($menuList->getActionLink($controller, 'edit-track')); }
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(); $model->addColumn('CONCAT(gr2t_completed, \'' . $this->_(' of ') . '\', gr2t_count)', 'progress'); $model->set('progress', 'label', $this->_('Progress'), 'tdClass', 'rightAlign', 'thClass', 'rightAlign'); return $model; }
Creates the model @return \MUtil_Model_ModelAbstract
entailment
public function send(Message $mail): void { // Set original To, Cc, Bcc $counter = 0; foreach ((array) $mail->getHeader('To') as $email => $name) { $mail->setHeader('X-Original-To-' . $counter++, sprintf('<%s> %s', $email, $name)); } $counter = 0; foreach ((array) $mail->getHeader('Cc') as $email => $name) { $mail->setHeader('X-Original-Cc-' . $counter++, sprintf('<%s> %s', $email, $name)); } $counter = 0; foreach ((array) $mail->getHeader('Bcc') as $email => $name) { $mail->setHeader('X-Original-Bcc-' . $counter++, sprintf('<%s> %s', $email, $name)); } // Override for DevOps $mail->setHeader('To', [$this->mail => 'DevOps']); $mail->setHeader('Cc', null); $mail->setHeader('Bcc', null); // Delegate to original mailer $this->mailer->send($mail); }
Sends email
entailment
public function getSearchDefaults() { if (! $this->defaultSearchData) { $this->defaultSearchData = $this->getDateSelector()->getDefaultSearchData(); } return $this->defaultSearchData; }
Function to allow the creation of search defaults in code @see getSearchFilter() @return array
entailment
public function getSearchFilter($useRequest = true) { $filter = parent::getSearchFilter($useRequest); $selector = $this->getDateSelector(); $output = $selector->getFilter($this->request, $filter); // \MUtil_Echo::track($filter, $output); return $output; }
Get the filter to use with the model for searching @param boolean $useRequest Use the request as source (when false, the session is used) @return array or false
entailment
public function translateRowValues($row, $key) { $row = parent::translateRowValues($row, $key); if (! $row) { return false; } // Get the real organization from the provider_id or code if it exists if (isset($row[$this->orgIdField], $this->orgTranslations[$row[$this->orgIdField]])) { $row[$this->orgIdField] = $this->orgTranslations[$row[$this->orgIdField]]; } return $row; }
Perform any translations necessary for the code to work @param mixed $row array or \Traversable row @param scalar $key @return mixed Row array or false when errors occurred
entailment
public function getContent(\WikiRenderer\Markup\Trac\Config $config, \WikiRenderer\Generator\DocumentGeneratorInterface $documentGenerator, $wikiContent) { preg_match('/^Image\(([^\)]+)\)$/', $wikiContent, $attributes); $image = $documentGenerator->getInlineGenerator('image'); $params = preg_split('/\s*,\s*/', $attributes[1]); $file = $config->getLinkProcessor()->processLink(trim(array_shift($params)), 'image'); $image->setAttribute('src', $file[0]); $width = null; $nolink = false; foreach ($params as $p) { $p = trim($p); if (in_array($p, array('right', 'left', 'top', 'bottom'))) { $image->setAttribute('align', $p); } elseif ($p == 'nolink') { $nolink = true; } elseif (preg_match('/^(\d+)(px|em|\%)?$/', $p)) { if ($width === null) { $width = $p; $image->setAttribute('width', $p); } else { $image->setAttribute('height', $p); } } elseif (preg_match('/^(align|width|height|alt|title|longdesc|class|id)=(.*)$/', $p, $m)) { $image->setAttribute($m[1], $m[2]); } } if ($nolink) { return $image; } else { $link = $documentGenerator->getInlineGenerator('link'); $link->addContent($image); $link->setAttribute('href', $file[0]); return $link; } }
returns the generator corresponding to the macro. @param Config $config @param \WikiRenderer\Generator\DocumentGeneratorInterface $documentGenerator @param string $wikiContent @return \WikiRenderer\Generator\InlineGeneratorInterface
entailment
public function execute($respTrackData = null, $userId = null) { $batch = $this->getBatch(); $tracker = $this->loader->getTracker(); $respTrack = $tracker->getRespondentTrack($respTrackData); $engine = $respTrack->getTrackEngine(); $engine->checkRoundsFor($respTrack, $userId, $batch); }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
public function applyParameters(array $parameters, $includeNumericFilters = false) { if ($parameters) { // Allow use when passed only an ID value if (isset($parameters[\MUtil_Model::REQUEST_ID]) && (! isset($parameters[\MUtil_Model::REQUEST_ID1], $parameters[\MUtil_Model::REQUEST_ID2]))) { $id = $parameters[\MUtil_Model::REQUEST_ID]; $keys = $this->getKeys(); $field = array_shift($keys); $parameters[$field] = $id; if ($field2 = array_shift($keys)) { $parameters[$field2] = $this->getCurrentOrganization(); \MUtil_Echo::r('Still using old HiddenModel parameters.', 'DEPRECIATION WARNING'); \MUtil_Echo::r($parameters); } unset($parameters[\MUtil_Model::REQUEST_ID]); } if (isset($parameters[\MUtil_Model::REQUEST_ID2]) && (! array_key_exists($parameters[\MUtil_Model::REQUEST_ID2], $this->currentUser->getAllowedOrganizations()))) { $this->initTranslateable(); throw new \Gems_Exception( $this->_('Inaccessible or unknown organization'), 403, null, sprintf($this->_('Access to this page is not allowed for current role: %s.'), $this->currentUser->getRole())); } return parent::applyParameters($parameters, $includeNumericFilters); } return array(); }
Stores the fields that can be used for sorting or filtering in the sort / filter objects attached to this model. @param array $parameters @param boolean $includeNumericFilters When true numeric filter keys (0, 1, 2...) are added to the filter as well @return array The $parameters minus the sort & textsearch keys
entailment
public function getKeyRef($forData, $href = array(), $organizationInKey = null) { $keys = $this->getKeys(); if (! $organizationInKey) { if ($forData instanceof \MUtil_Lazy_RepeatableInterface) { // Here I kind of assume that the data always contains the organization key. $organizationInKey = true; } else { $ordId = $this->getCurrentOrganization(); $organizationInKey = self::_getValueFrom('gr2o_id_organization', $forData) == $ordId; } } if ($organizationInKey) { $href[\MUtil_Model::REQUEST_ID] = self::_getValueFrom(reset($keys), $forData); } else { $href[\MUtil_Model::REQUEST_ID1] = self::_getValueFrom(reset($keys), $forData); next($keys); $href[\MUtil_Model::REQUEST_ID2] = self::_getValueFrom(key($keys), $forData); } return $href; }
Return an identifier the item specified by $forData basically transforms the fieldnames ointo oan IDn => value array @param mixed $forData Array value to vilter on @param array $href Or \ArrayObject @return array That can by used as href
entailment
protected function getTranslateAdapter() { if ($this->translate instanceof \Zend_Translate) { return $this->translate->getAdapter(); } if (! $this->translate instanceof \Zend_Translate_Adapter) { $this->translate = new \MUtil_Translate_Adapter_Potemkin(); } return $this->translate; }
Returns a translate adaptor @return \Zend_Translate_Adapter
entailment
public function processAfterLoad($data, $new = false, $isPostData = false) { // Repeat settings here, because the might be overloaded in the meantime $this->refreshGroupSettings(); return parent::processAfterLoad($data, $new, $isPostData); }
Helper function that procesess the raw data after a load. @see \MUtil_Model_SelectModelPaginator @param mxied $data Nested array or Traversable containing rows or iterator @param boolean $new True when it is a new item @param boolean $isPostData With post data, unselected multiOptions values are not set so should be added @return array or Traversable Nested
entailment
public function refreshGroupSettings() { $group = $this->currentUser->getGroup(); if ($group instanceof Group) { $group->applyGroupToModel($this, $this->hideWhollyMasked); } }
Function to re-apply all the masks and settings for the current group @return void
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $tUtil = $this->util->getTokenData(); $repeater = new \MUtil_Lazy_RepeatableByKeyValue($tUtil->getEveryStatus()); $table = new \MUtil_Html_TableElement(); $table->class = 'compliance timeTable rightFloat table table-condensed'; $table->setRepeater($repeater); $table->throw($this->_('Legend')); $cell = $table->td(); $cell->class = array( 'round', \MUtil_Lazy::method($tUtil, 'getStatusClass', $repeater->key) ); $cell->append(\MUtil_Lazy::method($tUtil, 'getStatusIcon', $repeater->key)); $table->td($repeater->value); return $table; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
public function execute($lineNr = null, $fieldId = null, $fieldSub = null, $fieldCalc = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (! (isset($import['trackId']) && $import['trackId'] && $fieldId)) { // Do nothing return; } $tracker = $this->loader->getTracker(); $trackEngine = $tracker->getTrackEngine($import['trackId']); $fieldCodes = $import['fieldCodes']; $fieldModel = $trackEngine->getFieldsMaintenanceModel(true, 'edit'); $roundOrders = $import['roundOrders']; $saveData['gtf_id_field'] = $fieldId; $saveData['sub'] = $fieldSub; $saveData['gtf_id_track'] = $import['trackId']; $calcFields = is_array($fieldCalc) ? $fieldCalc : explode('|', trim($fieldCalc, '|')); if (! $calcFields) { return; } foreach ($calcFields as $field) { if (isset($fieldCodes[$field]) && $fieldCodes[$field]) { $saveData['gtf_calculate_using'][] = $fieldCodes[$field]; } else { // Actually this code currently is PULSE specific if (\MUtil_String::startsWith($field, '{r')) { $roundOrder = substr($field, 2, -1); if (isset($roundOrders[$roundOrder]) && $roundOrders[$roundOrder]) { $saveData['gtf_calculate_using'][] = $roundOrders[$roundOrder]; } else { $saveData['gtf_calculate_using'][] = $field; } } } } \MUtil_Echo::track($saveData, $fieldId); $fieldModel->save($saveData); }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
public function execute($lineNr = null, $forRoundOrder = null, $usesRoundRound = null, $roundField = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (! (isset($import['trackId']) && $import['trackId'])) { // Do nothing return; } if (isset($import['roundOrders'][$usesRoundRound]) && $import['roundOrders'][$usesRoundRound]) { $this->db->update( 'gems__rounds', array($roundField => $import['roundOrders'][$usesRoundRound]), $this->db->quoteInto("gro_id_order = ? AND ", $forRoundOrder) . $this->db->quoteInto("gro_id_track = ?", $import['trackId']) ); } }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
public function execute($tracksData = null) { $batch = $this->getBatch(); switch (count((array) $tracksData)) { case 0: $batch->addToCounter('import_errors'); $batch->addMessage($this->_('No "track" data found in import file.')); break; case 1; $trackData = reset($tracksData); $lineNr = key($tracksData); $defaults = array('gtr_track_name', 'gtr_track_info', 'gtr_code', 'gtr_date_start', 'gtr_date_until'); $events = $this->loader->getEvents(); $import = $batch->getVariable('import'); $tracker = $this->loader->getTracker(); $import['trackData'] = $trackData; foreach ($defaults as $name) { if (isset($trackData[$name])) { $import['formDefaults'][$name] = $trackData[$name]; $import['modelSettings'][$name]['respondentData'] = true; } } if ($batch->hasVariable('trackEngine') && isset($trackData['gtr_track_name'])) { $trackEngine = $batch->getVariable('trackEngine'); if ($trackEngine->getTrackName() == $trackData['gtr_track_name']) { $import['modelSettings']['gtr_track_name']['elementClass'] = 'Exhibitor'; } else { $import['modelSettings']['gtr_track_name']['description'] = sprintf( $this->_('Current track name is "%s".'), $trackEngine->getTrackName() ); } } if (isset($trackData['gtr_track_class']) && $trackData['gtr_track_class']) { $trackEngines = $tracker->getTrackEngineClasses(); if (! isset($trackEngines[$trackData['gtr_track_class']])) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown track engine "%s" specified on line %d.'), $trackData['gtr_track_class'], $lineNr )); } } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No track engine specified on line %d.'), $lineNr )); } if (isset($trackData['gtr_beforefieldupdate_event']) && $trackData['gtr_beforefieldupdate_event']) { try { $events->loadBeforeTrackFieldUpdateEvent($trackData['gtr_beforefieldupdate_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid track field before update event "%s" specified on line %d.'), $trackData['gtr_beforefieldupdate_event'], $lineNr )); } } if (isset($trackData['gtr_calculation_event']) && $trackData['gtr_calculation_event']) { try { $events->loadTrackCalculationEvent($trackData['gtr_calculation_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid track calculation event "%s" specified on line %d.'), $trackData['gtr_calculation_event'], $lineNr )); } } if (isset($trackData['gtr_completed_event']) && $trackData['gtr_completed_event']) { try { $events->loadTrackCompletionEvent($trackData['gtr_completed_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid track completion event "%s" specified on line %d.'), $trackData['gtr_completed_event'], $lineNr )); } } if (isset($trackData['gtr_fieldupdate_event']) && $trackData['gtr_fieldupdate_event']) { try { $events->loadTrackFieldUpdateEvent($trackData['gtr_fieldupdate_event']); } catch (\Gems_Exception_Coding $ex) { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('Unknown or invalid track field update event "%s" specified on line %d.'), $trackData['gtr_fieldupdate_event'], $lineNr )); } } break; default: $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('%d sets of "track" data found in import file.'), count($tracksData) )); foreach ($tracksData as $lineNr => $trackData) { $batch->addMessage(sprintf( $this->_('"track" data found on line %d.'), $lineNr )); } } }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task @param array $trackData Nested array of trackdata
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { $table = \MUtil_Html_TableElement::createArray($this->tableData, $this->tableTitle, $this->tableNested); $table->class = 'browser table'; $div = \MUtil_Html::create()->div(array('class' => 'table-container')); $div[] = $table; return $div; }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment
public function applyParsley() { $this->parsleyEnabled = true; $useCurrent = self::config()->use_current; // Include your own version of jQuery (>= 1.8) and entwine // You can also simply call globalRequirements() Requirements::javascript('zenvalidator/javascript/parsley-2.8.1/parsley.min.js', ['defer' => true]); $lang = strtolower(substr(i18n::get_locale(), 0, 2)); if ($lang != 'en') { Requirements::javascript('zenvalidator/javascript/parsley-2.8.1/i18n/' . $lang . '.js', ['defer' => true]); } if ($this->form) { if ($this->defaultJS) { $this->form->addExtraClass('parsley'); Requirements::javascript('zenvalidator/javascript/zenvalidator.js', ['defer' => true]); } else { $this->form->addExtraClass('custom-parsley'); } foreach ($this->constraints as $fieldName => $constraints) { foreach ($constraints as $constraint) { try { $constraint->applyParsley(); } catch (Exception $ex) { throw new Exception("An exception occured while applying constraint on $fieldName : " . $ex->getMessage()); } } } } return $this; }
applyParsley @return $this
entailment
public function disableParsley() { $this->parsleyEnabled = false; if ($this->form) { $this->form->removeExtraClass('parsley'); $this->form->removeExtraClass('custom-parsley'); } return $this; }
disableParsley @return this
entailment
public function setConstraint($fieldName, $constraint) { $class = get_class($constraint); // remove existing constraint if it already exists if ($this->getConstraint($fieldName, $class)) { $this->removeConstraint($fieldName, $class); } $this->constraints[$fieldName][$class] = $constraint; if ($this->form) { $dataField = $this->form->Fields()->dataFieldByName($fieldName); $constraint->setField($dataField); if ($this->parsleyEnabled) { // If there is no field, output a clear error message before trying to apply parsley if (!$dataField) { throw new Exception("You have set a constraint on '$fieldName' but it does not exist in the FieldList."); } $constraint->applyParsley(); } } return $this; }
setConstraint - sets a ZenValidatorContraint on this validator @param string $field - name of the field to be validated @param ZenFieldValidator $constraint @return $this
entailment
public function setConstraints($constraints) { foreach ($constraints as $fieldName => $v) { if (is_array($v)) { foreach ($v as $constraintFromArray) { $this->setConstraint($fieldName, $constraintFromArray); } } else { $this->setConstraint($fieldName, $v); } } return $this; }
setConstraints - sets multiple constraints on this validator @param array $constraints - $fieldName => ZenValidatorConstraint @return $this
entailment
public function getConstraint($fieldName, $constraintName) { if (isset($this->constraints[$fieldName][$constraintName])) { return $this->constraints[$fieldName][$constraintName]; } }
get a constraint by fieldName, constraintName @param string $fieldName @param string $constraintName @return ZenValidatorConstraint
entailment
public function removeConstraint($fieldName, $constraintName) { if ($constraint = $this->getConstraint($fieldName, $constraintName)) { if ($this->form) { $constraint->removeParsley(); } $class = get_class($constraint); unset($this->constraints[$fieldName][$class]); unset($constraint); } return $this; }
remove a constraint from a field @param string $field - name of the field to have a constraint removed from @param string $constraintName - class name of constraint @return $this
entailment
public function removeConstraints($fieldName) { if ($constraints = $this->getConstraints($fieldName)) { foreach ($constraints as $k => $v) { $this->removeConstraint($fieldName, $k); } unset($this->constraints[$fieldName]); } return $this; }
remove all constraints from a field @param string $field - name of the field to have constraints removed from @return $this
entailment
public function addRequiredFields($fields, ...$otherFields) { if(!is_array($fields)) { $fields = [$fields]; } if(!empty($otherFields)) { $fields = array_merge($fields, $otherFields); } if (ArrayLib::is_associative($fields)) { foreach ($fields as $k => $v) { $constraint = Constraint_required::create(); if ($v) { $constraint->setMessage($v); } $this->setConstraint($k, $constraint); } } else { foreach ($fields as $field) { $this->setConstraint($field, Constraint_required::create()); } } return $this; }
A quick way of adding required constraints to a number of fields @param array $fieldNames - can be either indexed array of fieldnames, or associative array of fieldname => message @param array $otherFields @return this
entailment
public function php($data) { $valid = true; // If we want to ignore validation if (get_class($this->form->getRequestHandler()->buttonClicked()) === 'FormActionNoValidation') { return $valid; } // validate against form field validators $fields = $this->form->Fields(); foreach ($fields as $field) { $valid = ($field->validate($this) && $valid); } // validate against ZenValidator constraints foreach ($this->constraints as $fieldName => $constraints) { $field = $this->form->Fields()->dataFieldByName($fieldName); if (!$field) { continue; } if ($field->validationApplies()) { foreach ($constraints as $constraint) { if (!$constraint->validate($data[$fieldName])) { $this->validationError($fieldName, $constraint->getMessage(), 'required'); $valid = false; $this->debug("Validation (".get_class($constraint).") failed for $fieldName with message: " . $constraint->getMessage()); } } } } return $valid; }
Performs the php validation on all ZenValidatorConstraints attached to this validator @return boolean
entailment
public function removeAllValidation() { if ($this->form) { foreach ($this->constraints as $fieldName => $constraints) { foreach ($constraints as $constraint) { $constraint->removeParsley(); unset($constraint); } } } $this->constraints = array(); }
Removes all constraints from this validator.
entailment
public function fieldIsRequired($fieldName) { $required = false; $constraints = $this->getConstraints($fieldName); if ($constraints) { foreach ($constraints as $constraint) { if ($constraint instanceof Constraint_required) { $required = true; break; } } } return $required || parent::fieldIsRequired($fieldName); }
Returns whether the field in question is required. This will usually display '*' next to the field. @param string $fieldName @return bool
entailment
public function getFieldName($field, $modelName) { if (isset($this->_unionMapsTo[$modelName][$field])) { return $this->_unionMapsTo[$modelName][$field]; } return $field; }
Get the SQL table name of the union sub model that should be used for this row. @param array $row @return string
entailment
public function getTableName($modelName) { if (! isset($this->_unionModels[$modelName])) { return null; } $model = $this->_unionModels[$modelName]; if ($model instanceof \MUtil_Model_TableModel) { return $model->getTableName(); } }
Get the SQL table name of the union sub model that should be used for this row. @param string $modelName Name of the submodel @return string
entailment
protected function checkRequired($exportCode, array $roundsData) { // First find rounds using this export code $rounds = array(); foreach ($roundsData as $roundData) { if ($roundData['survey_export_code'] == $exportCode) { $rounds[$roundData['gro_id_order']] = $roundData['gro_id_order']; } } if (! $rounds) { return false; } // The check for any round using such a round foreach ($roundsData as $roundData) { if (isset($roundData['gro_valid_after_source'], $roundData['valid_after'])) { if ($this->checkSourceRequired( $roundData['gro_valid_after_source'], $roundData['valid_after'], $rounds )) { return true; } } if (isset($roundData['gro_valid_after_source'], $roundData['valid_for'])) { if ($this->checkSourceRequired( $roundData['gro_valid_for_source'], $roundData['valid_for'], $rounds )) { return true; } } } return false; }
Returns tru if another round depends on a round using this export code @param string $exportCode @param array $roundsData @return boolean
entailment
protected function checkSourceRequired($source, $field, array $rounds) { if (($source == \Gems_Tracker_Engine_StepEngineAbstract::ANSWER_TABLE) || ($source == \Gems_Tracker_Engine_StepEngineAbstract::TOKEN_TABLE)) { return isset($rounds[$field]) && $rounds[$field]; } }
Returns true when thw valid_for_source and valid_for combo uses any round. @param string $source @param string $field @param array $rounds @return boolean
entailment
public function execute($lineNr = null, $surveyData = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); $trackData = $this->util->getTrackData(); if (isset($surveyData['gsu_export_code']) && $surveyData['gsu_export_code']) { $name = 'survey__' . $surveyData['gsu_export_code']; $required = $this->checkRequired($surveyData['gsu_export_code'], $import['rounds']); if (isset($surveyData['gsu_survey_name']) && $surveyData['gsu_survey_name']) { $import['modelSettings'][$name]['label'] = $surveyData['gsu_survey_name']; } else { $import['modelSettings'][$name]['label'] = $surveyData['gsu_export_code']; } $import['modelSettings'][$name]['description'] = sprintf($this->_('[%s]'), $surveyData['gsu_export_code']); $import['modelSettings'][$name]['isSurvey'] = true; $import['modelSettings'][$name]['required'] = $required; $surveyId = $this->db->fetchOne( "SELECT gsu_id_survey FROM gems__surveys WHERE gsu_export_code = ?", $surveyData['gsu_export_code'] ); // The first search determines whether the user can select a survey // or the survey is displayed as fixed if ($surveyId) { $import['modelSettings'][$name]['elementClass'] = 'Exhibitor'; $import['modelSettings'][$name]['multiOptions'] = $trackData->getAllSurveys(); $import['surveyCodes'][$surveyData['gsu_export_code']] = $surveyId; } else { $import['modelSettings'][$name]['elementClass'] = 'Select'; // Store the exportCode for rows that should be saved $import['modelSettings'][$name]['exportCode'] = $surveyData['gsu_export_code']; if ($required) { $empty = $this->_('(survey required)'); } else { $empty = $this->_('(skip rounds)'); } $import['modelSettings'][$name]['multiOptions'] = array('' => $empty) + $trackData->getSurveysWithoutExportCode(); $import['surveyCodes'][$surveyData['gsu_export_code']] = false; } // Then try match on gsu_surveyor_id if ((! $surveyId) && isset($surveyData['gsu_surveyor_id']) && $surveyData['gsu_surveyor_id']) { $surveyId = $this->db->fetchOne( "SELECT gsu_id_survey FROM gems__surveys WHERE gsu_surveyor_id = ?", $surveyData['gsu_surveyor_id'] ); } // Last try ny name if ((! $surveyId) && isset($surveyData['gsu_survey_name']) && $surveyData['gsu_survey_name']) { $surveyId = $this->db->fetchOne( "SELECT gsu_id_survey FROM gems__surveys WHERE gsu_survey_name = ?", $surveyData['gsu_survey_name'] ); } // When we have a survey id that is in the options, add it as default if ($surveyId) { if (isset($import['modelSettings'][$name]['multiOptions'][$surveyId])) { $import['formDefaults'][$name] = $surveyId; } } } else { $batch->addToCounter('import_errors'); $batch->addMessage(sprintf( $this->_('No gsu_export_code specified for survey at line %d.'), $lineNr )); } }
Should handle execution of the task, taking as much (optional) parameters as needed The parameters should be optional and failing to provide them should be handled by the task
entailment
protected function createModel($detailed, $action) { $model = $this->loader->getAgenda()->newFilterModel(); if ($detailed) { if (('edit' == $action) || ('create' == $action)) { $model->applyEditSettings(('create' == $action)); } else { $model->applyDetailSettings(); } } else { $model->applyBrowseSettings(); } return $model; }
Creates a model for getModel(). Called only for each new $action. The parameters allow you to easily adapt the model to the current action. The $detailed parameter was added, because the most common use of action is a split between detailed and summarized actions. @param boolean $detailed True when the current action is not in $summarizedActions. @param string $action The current action. @return \MUtil_Model_ModelAbstract
entailment
public function getShowFilter() { $filter = $this->loader->getAgenda()->getFilter($this->_getIdParam()); if ($filter) { return $filter; } }
Get an agenda filter for the current shown item @return AppointmentFilterInterface or null
entailment
public function getTextSettings() { $description = $this->_( "Use the %%-sign to search for zero or more random characters and an _ for a single random character." ) . "\n" . $this->_("Leave empty to filter for missing content."); return array( 'gaf_filter_text1' => array( 'label' => $this->_('Episode diagnosis'), 'description' => $description, 'required' => false, ), ); }
Get the settings for the gaf_filter_textN fields Fields not in this array are not shown in any way @return array gaf_filter_textN => array(modelFieldName => fieldValue)
entailment
protected function saveData() { if ($this->trackEngine) { // concatenate user input (gtf_field fields) // before the data is saved (the fields them $this->formData['gr2t_track_info'] = $this->trackEngine->calculateFieldsInfo($this->formData); } // Perform the save $model = $this->getModel(); $this->formData = $model->save($this->formData); $changed = $model->getChanged(); $refresh = false; // Retrieve the key if just created if ($this->createData) { $this->respondentTrackId = $this->formData['gr2t_id_respondent_track']; $this->respondentTrack = $this->loader->getTracker()->getRespondentTrack($this->formData); // Explicitly save the fields as the transformer in the model only handles // before save event (like default values) for existing respondenttracks $this->respondentTrack->setFieldData($this->formData); // Create the actual tokens!!!! $this->trackEngine->checkRoundsFor($this->respondentTrack, $this->userId); $refresh = true; } else { // Check if the input has changed, i.e. one of the dates may have changed $refresh = (boolean) $changed; } if ($refresh) { // Perform a refresh from the database, to avoid date trouble $this->respondentTrack->refresh(); $this->respondentTrack->checkTrackTokens($this->userId); } // Communicate with the user $this->afterSave($changed); }
Hook containing the actual save code. Call's afterSave() for user interaction. @see afterSave()
entailment
protected function getRequestKey() { if (! $this->_requestKey) { $request = $this->getRequest(); $this->_requestKey[$request->getModuleKey()] = $request->getModuleName(); $this->_requestKey[$request->getControllerKey()] = $request->getControllerName(); $this->_requestKey[$request->getActionKey()] = $this->sourceAction ? $this->sourceAction : $request->getActionName(); } return $this->_requestKey; }
The module / controller /action of the request in an array. @return array
entailment
public function setProgramParams(array $programParams) { // Store result $this->_programParams = $programParams; if (! $this->_readonly) { $this->session->requestCache[$this->getStorageKey()] = $programParams; } return $this; }
Set the keys stored fot this cache @param array $programParams @return \Gems_Util_RequestCache (continuation pattern)
entailment
public static function set($name, $value, $days = 30, $basepath = '/') { // Gems uses the empty string when the base path is '/' if (! $basepath) { $basepath = '/'; } if (\Zend_Session::$_unitTestEnabled) { return true; } // Set the cookie for 30 days return setcookie($name, $value, time() + ($days * 86400), $basepath, '', (APPLICATION_ENV == 'production'), true); }
Store this cookie in a generic save method that works for both sub-directory installations and own url installations. @param string $name Name of the cookie @param mixed $value Value to set @param int $days Number of days to keep this cookie @param string $basepath The folder of the domain, if any. @return boolean True if the cookie was stored.
entailment
public static function setOrganization($organization, $basepath = '/') { if ($organization) { // Set the cookie for 30 days return self::set(self::ORGANIZATION_COOKIE, $organization, 30, $basepath); } }
Store the organization in a cookie. @param int $organization Organization to store @param string $basepath The folder of the domain, if any. @return boolean True if the cookie was stored.
entailment
protected function createModel($detailed, $action) { // Export all if ('export' === $action) { $detailed = true; } if ($detailed) { $year = $this->_('Year'); $month = $this->_('Month'); $fields[$year] = new \Zend_Db_Expr("YEAR(gr2o_created)"); $fields[$month] = new \Zend_Db_Expr("MONTH(gr2o_created)"); } $consents = $this->util->getDbLookup()->getUserConsents(); $deleteds = array('' => '') + $this->util->getReceptionCodeLibrary()->getRespondentDeletionCodes(); $sql = "SUM(CASE WHEN grc_success = 1 AND gr2o_consent = '%s' THEN 1 ELSE 0 END)"; foreach ($consents as $consent => $translated) { $fields[$translated] = new \Zend_Db_Expr(sprintf($sql, $consent)); } $fields[$this->_('Total OK')] = new \Zend_Db_Expr("SUM(CASE WHEN grc_success = 1 THEN 1 ELSE 0 END)"); $sql = "SUM(CASE WHEN gr2o_reception_code = '%s' THEN 1 ELSE 0 END)"; foreach ($deleteds as $code => $translated) { $fields[$translated] = new \Zend_Db_Expr(sprintf($sql, $code)); } $fields[$this->_('Dropped')] = new \Zend_Db_Expr("SUM(CASE WHEN grc_success = 0 THEN 1 ELSE 0 END)"); $fields[$this->_('Total')] = new \Zend_Db_Expr("COUNT(*)"); $select = $this->db->select(); $select->from('gems__respondent2org', $fields) ->joinInner('gems__reception_codes', 'gr2o_reception_code = grc_id_reception_code', array()) ->joinInner( 'gems__organizations', 'gr2o_id_organization = gor_id_organization', array('gor_name', 'gor_id_organization') ); $select->group(array('gor_name', 'gor_id_organization')); if ($detailed) { $select->group(array($fields[$year], $fields[$month])); } $model = new \MUtil_Model_SelectModel($select, 'consent-plan'); $model->setKeys(array('gor_id_organization')); $model->resetOrder(); $model->set('gor_name', 'label', $this->_('Organization')); foreach ($fields as $field => $expr) { $model->set($field, 'label', $field, 'tdClass', 'rightAlign', 'thClass', 'rightAlign'); } foreach ($deleteds as $code => $translated) { $model->set($translated, 'tdClass', 'rightAlign smallTime', 'thClass', 'rightAlign smallTime'); } foreach (array($this->_('Total OK'), $this->_('Dropped'), $this->_('Total')) as $name) { $model->set($name, 'itemDisplay', \MUtil_Html::create('strong'), 'tableHeaderDisplay', \MUtil_Html::create('em'), 'tdClass', 'rightAlign selectedColumn', 'thClass', 'rightAlign selectedColumn' ); } if ($detailed) { $model->set($month, 'formatFunction', $this->util->getLocalized()->getMonthName); } // Only show organizations the user is allowed to see $allowed = $this->currentUser->getAllowedOrganizations(); $model->setFilter(array('gr2o_id_organization'=>array_keys($allowed))); // \MUtil_Model::$verbose = true; 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 afterRegistry() { $this->_select = $this->db->select(); $this->_select->from('gems__appointments', $this->fields); }
Called after the check that all required registry values have been set correctly has run. @return void
entailment