sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function render(\Zend_View_Interface $view = null)
{
if ($this->_getIsRendered()) {
return;
}
$this->fixDecorators();
return parent::render($view);
} | Fix the decorators the first time we try to render the form
@param \Zend_View_Interface $view
@return string | entailment |
protected function createModel() {
if (!$this->model instanceof \Gems_Tracker_Model_StandardTokenModel) {
$model = $this->loader->getTracker()->getTokenModel();
$model->set('gto_id_token', 'label', $this->_('Summary'), 'formatFunction', array($this, 'getData'));
$model->set('gsu_survey_name', 'label', $this->_('Survey'));
$model->set('forgroup', 'label', $this->_('Filler'));
$model->setKeys(array('gr2o_patient_nr', 'gto_id_organization'));
$this->model = $model;
}
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
{
//
$roundDecription = $this->request->getParam('gto_round_description');
if (!is_null($roundDecription)) {
$roundDecription = html_entity_decode(urldecode($roundDecription));
$this->request->setParam('gto_round_description', $roundDecription);
}
parent::processFilterAndSort($model);
} | Fix for forward slash in round description
The round description can contain a / that is interpreted incorrect, so
in TrafficLightTokenSnippet we encode it to the html entity first. This method does the reverse.
@see \Gems_Snippets_Respondent_TrafficLightTokenSnippet
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function applySurveyListValidAfter(\MUtil_Model_ModelAbstract $model, array &$itemData)
{
$this->_ensureRounds();
$rounds = array();
foreach ($this->_rounds as $roundId => $round) {
if (($roundId == $itemData['gro_id_round'])) {
continue; // Skip self
}
$rounds[$roundId] = $this->getRound($roundId)->getFullDescription();
}
return $this->_applyOptions($model, 'gro_valid_after_id', $rounds, $itemData);
} | Set the surveys to be listed as valid after choices for this item and the way they are displayed (if at all)
@param \MUtil_Model_ModelAbstract $model The round model
@param array $itemData The current items data
@param boolean True if the update changed values (usually by changed selection lists). | entailment |
protected function applySurveyListValidFor(\MUtil_Model_ModelAbstract $model, array &$itemData)
{
$this->_ensureRounds();
$rounds = array();
foreach ($this->_rounds as $roundId => $round) {
$rounds[$roundId] = $this->getRound($roundId)->getFullDescription();
}
if (!empty($itemData['gro_id_round'])) {
$rounds[$itemData['gro_id_round']] = $this->_('This round');
} else {
// For new rounds we use 0. The snippet will update this on save
// to the new roundid
$rounds['0'] = $this->_('This round');
}
return $this->_applyOptions($model, 'gro_valid_for_id', $rounds, $itemData);
} | Set the surveys to be listed as valid for choices for this item and the way they are displayed (if at all)
@param \MUtil_Model_ModelAbstract $model The round model
@param array $itemData The current items data
@param boolean True if the update changed values (usually by changed selection lists). | entailment |
public function checkTokensFrom(\Gems_Tracker_RespondentTrack $respTrack, \Gems_Tracker_Token $startToken, $userId, \Gems_Tracker_Token $skipToken = null)
{
$changed = parent::checkTokensFrom($respTrack, $respTrack->getFirstToken(), $userId, $skipToken);
return $changed;
} | The end date of any round can depend on any token so always do a end date check
of the previous tokens
@param \Gems_Tracker_RespondentTrack $respTrack The respondent track to check
@param \Gems_Tracker_Token $startToken The token to start at
@param int $userId Id of the user who takes the action (for logging)
@param \Gems_Tracker_Token $skipToken Optional token to skip in the recalculation
@return int The number of tokens changed by this code | entailment |
public function getRoundDefaults()
{
$defaults = parent::getRoundDefaults();
// Now check if the valid for depends on the same round
if (count($defaults) > 1) {
$lastRound = end($this->_rounds); // We need the ID to compare
if ($defaults['gro_valid_for_source'] == 'tok' &&
$defaults['gro_valid_for_field'] == 'gto_valid_from' &&
$defaults['gro_valid_for_id'] == $lastRound['gro_id_round']) {
$defaults['gro_valid_for_id'] = 0; // Will be updated on save
}
} else {
$defaults['gro_valid_after_source'] = 'rtr';
}
return $defaults;
} | Get the defaults for a new round
@return array Of fieldname => default | entailment |
public function getRoundModel($detailed, $action)
{
$model = parent::getRoundModel($detailed, $action);
$model->set('gro_valid_for_id',
'default', '0');
return $model;
} | Returns a model that can be used to retrieve or save the data.
@param boolean $detailed Create a model for the display of detailed item data or just a browse table
@param string $action The current action
@return \MUtil_Model_ModelAbstract | entailment |
protected function getValidFromDate($fieldSource, $fieldName, $prevRoundId, \Gems_Tracker_Token $token, \Gems_Tracker_RespondentTrack $respTrack)
{
return $this->getValidUntilDate($fieldSource, $fieldName, $prevRoundId, $token, $respTrack, false);
} | Returns the date to use to calculate the ValidFrom if any
@param string $fieldSource Source for field from round
@param string $fieldName Name from round
@param int $prevRoundId Id from round
@param \Gems_Tracker_Token $token
@param \Gems_Tracker_RespondentTrack $respTrack
@return \MUtil_Date date time or null | entailment |
protected function getValidUntilDate($fieldSource, $fieldName, $prevRoundId, \Gems_Tracker_Token $token, \Gems_Tracker_RespondentTrack $respTrack, $validFrom)
{
$date = null;
switch ($fieldSource) {
case parent::ANSWER_TABLE:
if ($prev = $respTrack->getActiveRoundToken($prevRoundId, $token)) {
if ($prev->isCompleted()) {
$date = $prev->getAnswerDateTime($fieldName);
}
}
break;
case parent::TOKEN_TABLE:
if ($prev = $respTrack->getActiveRoundToken($prevRoundId, $token)) {
if ((false !== $validFrom) && ($prev === $token) && ($fieldName == 'gto_valid_from')) {
$date = $validFrom;
} else {
$date = $prev->getDateTime($fieldName);
}
}
break;
case parent::APPOINTMENT_TABLE:
case parent::RESPONDENT_TRACK_TABLE:
$date = $respTrack->getDate($fieldName);
break;
}
return $date;
} | Returns the date to use to calculate the ValidUntil if any
@param string $fieldSource Source for field from round
@param string $fieldName Name from round
@param int $prevRoundId Id from round
@param \Gems_Tracker_Token $token
@param \Gems_Tracker_RespondentTrack $respTrack
@param \MUtil_Date $validFrom The calculated new valid from value
@return \MUtil_Date date time or null | entailment |
public function getAge($date = NULL)
{
if (is_null($date)) {
$date = new \MUtil_Date();
}
if ($date instanceof \MUtil_Date) {
// Now calculate age
$birthDate = $this->getBirthDate();
if ($birthDate instanceof \Zend_Date) {
$age = $date->get('Y') - $birthDate->get('Y');
if ($date->get('MMdd') < $birthDate->get('MMdd')) {
$age--;
}
} else {
return;
}
}
return $age;
} | Returns current age or at a given date when supplied
@param \MUtil_Date|null $date
@return int | entailment |
protected function createModel()
{
if (! $this->model instanceof \Gems_Model_AppointmentModel) {
$this->model = $this->loader->getModels()->createAppointmentModel();
$this->model->applyDetailSettings();
}
$this->model->set('gap_admission_time', 'formatFunction', array($this, 'displayDate'));
$this->model->set('gap_discharge_time', 'formatFunction', array($this, 'displayDate'));
return $this->model;
} | Adds rows 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_VerticalTableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void
/
protected function addShowTableRows(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
parent::addShowTableRows($bridge, $model);
}
Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function _createSelect(array $filter, array $sort)
{
$select = parent::_createSelect($filter, $sort);
$config = $select->getAdapter()->getConfig();
if (isset($config['dbname'])) {
$constraint = $select->getAdapter()->quoteInto(' AND TABLE_SCHEMA=?', $config['dbname']);
} else {
$constraint = '';
}
$select->joinLeft('INFORMATION_SCHEMA.TABLES', "table_name = convert(concat_ws('_','gems__orf_', REPLACE(gof_form_id,'.','_'),gof_form_version) USING utf8)" . $constraint, array('TABLE_ROWS'));
return $select;
} | Get a select statement using a filter and sort
Modified to add the information schema, only possible like this since
the table has no primary key and can not be added using normal joins
@param array $filter
@param array $sort
@return \Zend_Db_Table_Select | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$this->addMessage($this->_('Unsubscribing not possible'));
$html = $this->getHtmlSequence();
$html->h2($this->_('Unsubscribing not possible'));
$p = $html->pInfo($this->_('To unsubscribe please contact the organization that subscribed you to this project.'));
$menu = $this->menu->findAllowedController('contact');
if ($menu) {
$p->append(' ');
$p->append($this->_('The participating organizations are on the contact page.'));
$html->append($menu->toActionLink());
}
return $html;
} | 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($tokenData = null, $userId = null)
{
$batch = $this->getBatch();
$tracker = $this->loader->getTracker();
$batch->addToCounter('checkedTokens');
$token = $tracker->getToken($tokenData);
$wasAnswered = $token->isCompleted();
if ($result = $token->checkTokenCompletion($userId)) {
if ($result & \Gems_Tracker_Token::COMPLETION_DATACHANGE) {
$i = $batch->addToCounter('resultDataChanges');
$batch->setMessage('resultDataChanges', sprintf(
$this->_('Results and timing changed for %d tokens.'),
$i
));
if ($wasAnswered) {
$action = 'token.data-changed';
$message = sprintf($this->_("Token '%s' data has changed."), $token->getTokenId());
} else {
$action = 'token.answered';
$message = sprintf($this->_("Token '%s' was answered."), $token->getTokenId());
}
if (! $this->request instanceof \Zend_Controller_Request_Abstract) {
$this->request = \Zend_Controller_Front::getInstance()->getRequest();
}
$this->accesslog->logEntry(
$this->request,
$action,
true,
$message,
$token->getArrayCopy(),
$token->getRespondentId()
);
}
if ($result & \Gems_Tracker_Token::COMPLETION_EVENTCHANGE) {
$i = $batch->addToCounter('surveyCompletionChanges');
$batch->setMessage('surveyCompletionChanges', sprintf(
$this->_('Answers changed by survey completion event for %d tokens.'),
$i
));
}
}
if ($token->isCompleted()) {
$batch->setTask('Tracker_ProcessTokenCompletion', 'tokproc-' . $token->getTokenId(), $tokenData, $userId);
}
$batch->setMessage('checkedTokens', sprintf(
$this->_('Checked %d tokens.'),
$batch->getCounter('checkedTokens')
));
// Free memory
$tracker->removeToken($token);
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
// $bridge->getTable()->setAlternateRowClass('odd', 'odd', 'even', 'even');
// \MUtil_Model::$verbose = true;
$bridge->add(
'gro_round_description',
$bridge->createSortLink('gro_id_order', $model->get('gro_round_description', 'label'))
);
$bridge->addSortable('gsu_survey_name');
$bridge->th(array($bridge->createSortLink('answered'), 'colspan' => 2))->class = 'centerAlign';
$bridge->td($bridge->answered)->class = 'centerAlign';
$bridge->td($this->percentageLazy($bridge->answered, $bridge->total))->class = 'rightAlign';
$bridge->th(array($bridge->createSortLink('missed'), 'colspan' => 2))->class = 'centerAlign';
$bridge->td($bridge->missed)->class = 'centerAlign';
$bridge->td($this->percentageLazy($bridge->missed, $bridge->total))->class = 'rightAlign';
$bridge->th(array($bridge->createSortLink('open'), 'colspan' => 2))->class = 'centerAlign';
$bridge->td($bridge->open)->class = 'centerAlign';
$bridge->td($this->percentageLazy($bridge->open, $bridge->total))->class = 'rightAlign';
// $bridge->addSortable('answered');
// $bridge->addSortable('missed');
// $bridge->addSortable('open');
// $bridge->add('future');
// $bridge->add('unknown');
$bridge->addColumn(array('=', 'class' => 'centerAlign'));
$bridge->addSortable('total');
$bridge->addSortable('filler');
// $bridge->tr();
// $bridge->add('gsu_survey_name')->colspan = 4;
// $bridge->add('gsu_id_primary_group')->colspan = 2;
// $bridge->addColumn();
/*
$bridge->addColumn(
array(
$bridge->gsu_survey_name,
\MUtil_Html::create('em', ' - ', $bridge->gsu_id_primary_group)
),
array(
$model->get('gsu_survey_name', 'label'),
\MUtil_Html::create('em', ' - ', $model->get('gsu_id_primary_group', 'label'))
)
)->colspan = 7;
$bridge->add('removed');
// */
} | 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 addHeader($filename)
{
$file = fopen($filename, 'w');
//$bom = pack("CCC", 0xef, 0xbb, 0xbf);
//fwrite($file, $bom);
$name = $this->getName();
$labels = $this->getLabeledColumns();
fputcsv($file, $labels, $this->delimiter, '"');
fclose($file);
} | Add headers to a specific file
@param string $filename The temporary filename while the file is being written | entailment |
public function addRow($row, $file)
{
$exportRow = $this->filterRow($row);
$labeledCols = $this->getLabeledColumns();
$exportRow = array_replace(array_flip($labeledCols), $exportRow);
$changed = false;
foreach ($exportRow as $name => $value) {
$type = $this->model->get($name, 'type');
// When numeric, there could be a non numeric answer, just ignore empty values
if ($type == \MUtil_Model::TYPE_NUMERIC && !empty($value) && !is_numeric($value)) {
$this->model->set($name, 'type', \MUtil_Model::TYPE_STRING);
$changed = true;
}
}
fputcsv($file, $exportRow, $this->delimiter, '"');
if ($changed) {
if ($this->batch) {
$this->batch->setVariable('model', $this->model);
} else {
$this->_session->model = $this->model;
}
}
} | Add a separate row to a file
@param array $row a row in the model
@param file $file The already opened file | entailment |
protected function addSyntaxFile($filename)
{
$model = $this->model;
$files = $this->getFiles();
$datFileName = array_search($filename, $files);
$spsFileName = substr($datFileName, 0, -strlen($this->fileExtension)) . '.R';
$tmpFileName = substr($filename, 0, -strlen($this->fileExtension)) . '.R';
$this->files[$spsFileName] = $tmpFileName;
if ($this->batch) {
$this->batch->setSessionVariable('files', $this->files);
} else {
$this->_session->files = $this->files;
}
$file = fopen($tmpFileName, 'a');
//first output our script
fwrite($file,
'data <- read.csv("' . $datFileName . '", quote="\'\\"", stringsAsFactors=FALSE, encoding="UTF-8")' . "\n\n");
$labeledCols = $this->getLabeledColumns();
$labels = array();
$types = array();
$fixedNames = array();
//$questions = $survey->getQuestionList($language);
foreach ($labeledCols as $idx => $colname) {
$fixedNames[$colname] = $this->fixName($colname);
$options = array();
$type = $model->get($colname, 'type');
switch ($type) {
case \MUtil_Model::TYPE_DATE:
$type = 'character';
break;
case \MUtil_Model::TYPE_DATETIME:
$type = 'character';
break;
case \MUtil_Model::TYPE_TIME:
$type = 'character';
break;
case \MUtil_Model::TYPE_NUMERIC:
$type = 'numeric';
break;
//When no type set... assume string
case \MUtil_Model::TYPE_STRING:
default:
$type = 'character';
break;
}
$types[$colname] = $type;
$ref = 'data[,' . ($idx + 1) . ']';
fwrite($file, $ref . ' <- as.' . $type . '(' . $ref . ')' . "\n");
}
fwrite($file, "\n#Define variable labels.\n");
foreach ($labeledCols as $idx => $colname) {
$label = $this->formatString($model->get($colname, 'label'));
fwrite($file, sprintf(
'attributes(data)$variable.labels[%s] <- "%s"' . "\n",
$idx + 1, $label));
}
fwrite($file, "\n#Define value labels.\n");
foreach ($labeledCols as $idx => $colname) {
if ($options = $model->get($colname, 'multiOptions')) {
$ref = 'data[,' . ($idx + 1) . ']';
$type = $types[$colname];
if ($type == 'numeric') {
$values = join(',', array_keys($options));
} else {
$values = '"' . join('","', array_keys($options)) . '"';
}
$labels = '"' . join('","', $options) . '"';
fwrite($file, sprintf(
'%1$s <- factor(%1$s, levels=c(%2$s), labels=c(%3$s))' . "\n",
$ref, $values, $labels));
}
}
fclose($file);
} | Creates a correct syntax file and adds it to the Files array | entailment |
protected function afterLoad()
{
if ($this->_data && ! $this->_organizations) {
foreach (['gaf_filter_text1', 'gaf_filter_text2', 'gaf_filter_text3', 'gaf_filter_text4'] as $field) {
if ($this->_data[$field]) {
$this->_organizations[$this->_data[$field]] = $this->_data[$field];
}
}
}
} | Override this function when you need to perform any actions when the data is loaded.
Test for the availability of variables as these objects can be loaded data first after
deserialization or registry variables first after normal instantiation.
That is why this function called both at the end of afterRegistry() and after exchangeArray(),
but NOT after unserialize().
After this the object should be ready for serialization | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
if ($this->_organizations) {
return isset($this->_organizations[$appointment->getOrganizationId()]);
}
return ! $appointment->getOrganizationId();
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
if (! $this->_data['gaf_filter_text1']) {
return ! $appointment->getSubject();
}
$regex = '/' . str_replace(array('%', '_'), array('.*', '.{1,1}'),$this->_data['gaf_filter_text1']) . '/i';
return (boolean) preg_match($regex, $appointment->getSubject());
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
public function render($content) {
$form = $this->getElement();
if (!$form instanceof \Zend_Form) {
return $content;
}
$this->_recurseForm($form);
return $content;
} | Render the TabErrors
We don't return anything, we just add a class to the tab so it shows the errors
@param <type> $content
@return <type> | entailment |
public function getVerbose() {
if (null !== ($verboseOpt = $this->getOption('verbose'))) {
$this->_verbose = (bool) $verboseOpt;
$this->removeOption('verbose');
}
return $this->_verbose;
} | Should the tab errors be verbose?
Verbose means that apart from marking and selecting the tab that has errors
we also show an error above the form.
@return boolean | entailment |
protected function _recurseForm(\Zend_Form $form)
{
$subFormsWithErrors = array();
$subFormMessages = array();
$tabId = 0;
foreach ($form->getSubForms() as $subForm) {
if ($subForm instanceof \Gems_Form_TabSubForm) {
// See if any of the subformelements has an error message
foreach ($subForm->getElements() as $subFormElement) {
$elementMessages = $subFormElement->getMessages();
if (count($elementMessages)) {
$subFormsWithErrors[$tabId] = $subForm->getAttrib('title'); // Save subform title
$subForm->setAttrib('jQueryParams', array('class' => 'taberror')); // Add css class to the subform
$form->selectTab($tabId); // Select the tab, this way the last tab with error is always selected
break; // don't check other elements
}
}
// Preserve subform level custom messages if we have an error
if (array_key_exists($tabId, $subFormsWithErrors)) {
$subFormMessages[$tabId] = $subForm->getCustomMessages();
}
$tabId++;
}
}
// If we found at least one error, and 'verbose' is true
if ($this->getVerbose() && (!empty($subFormsWithErrors) || $form->isErrors())) {
// First show form level custom error messages (the elements show their own errors)
$formMessage = $form->getCustomMessages();
if (!empty($formMessage)) {
foreach ($formMessage as $message)
{
\Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->addMessage($message);
}
}
// Now browse through the tabs with errors
foreach ($subFormsWithErrors as $tabIdx => $tabName)
{
// If more then one tab, show in which tab we found the errors
if ($tabId > 1) {
$translator = \Zend_Registry::get('Zend_Translate');
\Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->addMessage(sprintf($translator->_('Error in tab "%s"'), $tabName));
}
// If we have them, show the tab custom error messages
foreach ($subFormMessages[$tabIdx] as $subFormMessage)
{
foreach ($subFormMessage as $message)
{
\Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->addMessage("--> " . $message);
}
}
}
}
} | Recurse through a form object, rendering errors
@param \Zend_Form $form
@param \Zend_View_Interface $view
@return string | entailment |
public function isValid($value, $context = array())
{
$this->_valid = $this->_authenticator->verify($this->_key, $value);
return $this->_valid;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@param mixed $content
@return boolean
@throws \Zend_Validate_Exception If validation of $value is impossible | entailment |
public function execute($trackId = null, $surveyId = null)
{
$batch = $this->getBatch();
$select = $this->db->select();
$select->from('gems__surveys', array('gsu_export_code', 'gsu_survey_name', 'gsu_survey_description', 'gsu_surveyor_id'))
->where('gsu_id_survey = ?', $surveyId);
// \MUtil_Echo::track($select->__toString(), $roundId);
$data = $this->db->fetchRow($select);
// \MUtil_Echo::track($data);
if ($data && isset($data['gsu_export_code']) && $data['gsu_export_code']) {
$count = $batch->addToCounter('surveys_exported');
if ($count == 1) {
$this->exportTypeHeader('surveys');
$this->exportFieldHeaders($data);
}
$this->exportFieldData($data);
$this->exportFlush();
$batch->setMessage('survey_export', sprintf(
$this->plural('%d survey code exported', '%d survey codes exported', $count),
$count
));
}
} | Should handle execution of the task, taking as much (optional) parameters as needed
The parameters should be optional and failing to provide them should be handled by
the task | entailment |
public function getPanel()
{
$body = Zend_Controller_Front::getInstance()->getResponse()->getBody();
$liberrors = libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHtml($body);
libxml_use_internal_errors($liberrors);
$panel = '<h4>HTML Information</h4>';
$panel .= $this->_isXhtml();
$linebreak = $this->getLinebreak();
$panel .= $dom->getElementsByTagName('*')->length.' Tags in ' . round(strlen($body)/1024, 2).'K'.$linebreak
. $dom->getElementsByTagName('link')->length.' Link Tags'.$linebreak
. $dom->getElementsByTagName('script')->length.' Script Tags'.$linebreak
. $dom->getElementsByTagName('img')->length.' Images'.$linebreak
. '<form method="post" action="http://validator.w3.org/check"><p><input type="hidden" name="fragment" value="'.htmlentities($body).'"'.$this->getClosingBracket().'<input type="submit" value="Validate With W3C"'.$this->getClosingBracket().'</p></form>';
return $panel;
} | Gets content panel for the Debugbar
@return string | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$orgId = $this->respondent->getOrganizationId();
// These values are set for the generic table snippet and
// should be reset for this snippet
$this->browse = false;
$this->extraFilter = array("gtr_organizations LIKE '%|$orgId|%'");
$this->menuEditActions = 'view';
$this->menuShowActions = 'create';
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
protected function createModel()
{
$translated = $this->util->getTranslated();
$model = new \MUtil_Model_TableModel('gems__tracks');
$model->set('gtr_track_name', 'label', $this->_('Track'));
$model->set('gtr_survey_rounds', 'label', $this->_('Survey #'));
$model->set('gtr_date_start', 'label', $this->_('From'),
'dateFormat', $translated->formatDate,
'tdClass', 'date'
);
$model->set('gtr_date_until', 'label', $this->_('Until'),
'dateFormat', $translated->formatDateForever,
'tdClass', 'date'
);
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function _loadAllTraversable()
{
$data = array();
foreach (array_reverse($this->directories) as $pathData) {
$mainDirectory = $pathData['path'];
$location = $pathData['name'];
$db = $pathData['db'];
$tables = $this->listTablesViews($db);
if (!is_array($tables)) {
$tables = [];
}
if (is_dir($mainDirectory)) {
foreach (new \DirectoryIterator($mainDirectory) as $directory) {
$type = $this->_getType($directory->getFilename());
if ($directory->isFile() || $directory->isDot()) {
continue;
}
$path = $directory->getPathname();
foreach (new \GlobIterator($path . DIRECTORY_SEPARATOR . '*.sql') as $file) {
$fileName = $file->getBasename('.sql');
$forder = $this->_getOrder($fileName); // Changes $fileName
if (array_key_exists($type, $tables) && array_key_exists($fileName, $tables[$type])) {
$fexists = true;
unset($tables[$type][$fileName]);
} elseif (array_key_exists($fileName, $data)) {
// $fexists is also true when the table was already defined
// in a previous directory
$fexists = $data[$fileName]['exists'];
} else {
$fexists = false;
}
$fileContent = file_get_contents($file->getPathname());
if ($this->file_encoding && ($this->file_encoding !== mb_internal_encoding())) {
$fileContent = mb_convert_encoding($fileContent, mb_internal_encoding(), $this->file_encoding);
}
$data[$fileName] = array(
'name' => $fileName,
'group' => $this->_getGroupName($fileName),
'type' => $type,
'order' => $forder,
'defined' => true,
'exists' => $fexists,
'state' => $fexists ? self::STATE_CREATED : self::STATE_DEFINED,
/*'path' => $path,
'fullPath' => $file->getPathname(),
'fileName' => $file->getFilename(),*/
// \MUtil_Lazy does not serialize
// 'script' => \MUtil_Lazy::call('file_get_contents', $file->getPathname()),
'script' => $fileContent,
'lastChanged' => $file->getMTime(),
'location' => $location,
'db' => $db,
);
}
}
}
foreach ($tables as $type => $items) {
foreach($items as $item) {
if (! isset($data[$item])) {
$data[$item] = array(
'name' => $item,
'group' => $this->_getGroupName($item),
'type' => $type,
'order' => self::DEFAULT_ORDER,
'defined' => false,
'exists' => true,
'state' => self::STATE_UNKNOWN,
/*'path' => null,
'fullPath' => $file->getPathname(),
'fileName' => $item . '.' . self::STATE_UNKNOWN . '.sql',*/
'script' => '',
'lastChanged' => null,
'location' => $location,
'db' => $db,
);
}
}
}
}
return $data;
} | An ArrayModel assumes that (usually) all data needs to be loaded before any load
action, this is done using the iterator returned by this function.
@return \Traversable Return an iterator over or an array of all the rows in this object | entailment |
public function runScript(array $data, $includeResultSets = false)
{
$results = array();
if ($data['script']) {
$queries = \MUtil_Parser_Sql_WordsParser::splitStatements($data['script'], false);
$qCount = count($queries);
$results[] = sprintf($this->_('Executed %2$s creation script %1$s:'), $data['name'], $this->_(strtolower($data['type'])));
$stepCount = 1;
$resultSet = 1;
foreach ($queries as $query) {
$sql = (string) $query;
try {
if (isset($data['db'])) {
$db = $data['db'];
} else {
$db = $this->defaultDb;
// Lookup using location
if (isset($data['location'])) {
foreach ($this->directories as $path) {
if ($path['name'] === $data['location']) {
$db = $path['db'];
break;
}
}
}
}
$stmt = $db->query($sql);
if ($rows = $stmt->rowCount()) {
if ($includeResultSets && ($data = $stmt->fetchAll())) {
$results[] = sprintf($this->_('%d record(s) returned as result set %d in step %d of %d.'), $rows, $resultSet, $stepCount, $qCount);
$results[] = $data;
$resultSet++;
} else {
$results[] = sprintf($this->_('%d record(s) updated in step %d of %d.'), $rows, $stepCount, $qCount);
}
} else {
$results[] = sprintf($this->_('Script ran step %d of %d succesfully.'), $stepCount, $qCount);
}
} catch (\Zend_Db_Statement_Exception $e) {
$results[] = $e->getMessage() . $this->_(' in step ') . $stepCount . ': ' . $sql;
}
$stepCount++;
}
} else {
$results[] = sprintf($this->_('No script for %1$s.'), $data['name']);
}
return $results;
} | Run a sql statement from an object loaded through this model
$data is an array with the following keys:
script The sql statement to be executed
name The name of the table, used in messages
type Type of db element (table or view), used in messages
@param array $data
@param boolean $includeResultSets
@return string | entailment |
protected function createModel($detailed, $action)
{
$yesNo = $this->util->getTranslated()->getYesNo();
$model = new \Gems_Model_JoinModel('surveys', 'gems__surveys');
$model->addTable('gems__groups', array('gsu_id_primary_group' => 'ggp_id_group'));
$model->addColumn(
"(SELECT COUNT(DISTINCT gro_id_track)
FROM gems__tracks INNER JOIN gems__rounds ON gtr_id_track = gro_id_track
WHERE gro_id_survey = gsu_id_survey)",
'track_count'
);
$model->resetOrder();
$model->set('gsu_survey_name', 'label', $this->_('Survey'));
if ($detailed) {
$model->set('gsu_survey_description', 'label', $this->_('Description'),
'formatFunction', array(__CLASS__, 'formatDescription')
);
$model->set('gsu_active', 'label', sprintf($this->_('Active in %s'), $this->project->getName()),
'elementClass', 'Checkbox',
'multiOptions', $yesNo
);
}
$model->set('ggp_name', 'label', $this->_('By'));
$model->set('track_count', 'label', $this->_('Usage'),
'description', $this->_('How many track definitions use this survey?'));
$model->set('gsu_insertable', 'label', $this->_('Insertable'),
'description', $this->_('Can this survey be manually inserted into a track?'),
'multiOptions', $yesNo
);
if ($detailed) {
$model->set('gsu_duration', 'label', $this->_('Duration description'),
'description', $this->_('Text to inform the respondent, e.g. "20 seconds" or "1 minute".')
);
}
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 createModel($detailed, $action)
{
$model = $this->loader->getModels()->createAppointmentModel();
$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 getDateFormat()
{
$model = $this->getModel();
$format = $model->get('gap_admission_time', 'dateFormat');
if (! $format) {
$format = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
}
return $format;
} | Get the date format used for the appointment date
@return array | entailment |
public function getSearchDefaults()
{
if (! $this->defaultSearchData) {
$org = $this->currentOrganization;
$this->defaultSearchData = array(
'gap_id_organization' => $org->canHaveRespondents() ? $org->getId() : null,
'dateused' => 'gap_admission_time',
'datefrom' => new \MUtil_Date(),
);
}
return parent::getSearchDefaults();
} | Function to allow the creation of search defaults in code
@see getSearchFilter()
@return array | entailment |
protected function _checkTokenTable(array $tokenTable)
{
$missingFields = parent::_checkTokenTable($tokenTable);
return self::addnewAttributeFields($tokenTable, $missingFields);
} | Check a token table for any changes needed by this version.
@param array $tokenTable
@return array Fieldname => change field commands | entailment |
protected function _fillAttributeMap(\Gems_Tracker_Token $token)
{
$values = parent::_fillAttributeMap($token);
return self::addnewAttributeDefaults($values);
} | Returns a list of field names that should be set in a newly inserted token.
Adds the fields without default new in 2.00
@param \Gems_Tracker_Token $token
@return array Of fieldname => value type | entailment |
public static function addnewAttributeFields(array $tokenTable, array $missingFields)
{
if (! isset($tokenTable['participant_id'])) {
$missingFields['participant_id'] = "ADD participant_id varchar(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL";
}
if (! isset($tokenTable['blacklisted'])) {
$missingFields['blacklisted'] = "ADD blacklisted varchar(17) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL";
}
return $missingFields;
} | Adds the fields without default new in 2.00
@param array $tokenTable
@param array $missingFields
@return array Fieldname => change field commands | entailment |
public function getTokenUrl(\Gems_Tracker_Token $token, $language, $surveyId, $sourceSurveyId)
{
if (null === $sourceSurveyId) {
$sourceSurveyId = $this->_getSid($surveyId);
}
$tokenId = $this->_getToken($token->getTokenId());
if ($this->_isLanguage($sourceSurveyId, $language)) {
$langUrl = '/lang/' . $language;
} else {
$langUrl = '';
}
// <base>/index.php/survey/index/sid/834486/token/234/lang/en
$baseurl = $this->getBaseUrl();
$start = $baseurl . ('/' == substr($baseurl, -1) ? '' : '/');
if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false || (ini_get('security.limit_extensions') && ini_get('security.limit_extensions')!='')) {
// Apache : index.php/
$start .= 'index.php/';
} else {
$start .= 'index.php?r=';
}
return $start . 'survey/index/sid/' . $sourceSurveyId . '/token/' . $tokenId . $langUrl . '/newtest/Y';
} | Returns the url that (should) start the survey for this token
@param \Gems_Tracker_Token $token Gems token object
@param string $language
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return string The url to start the survey | entailment |
public function lsDbQuery($sourceSurveyId, $sql, $bindValues=array())
{
$this->_getFieldMap($sourceSurveyId)->lsDbQuery($sql, $bindValues);
} | Execute a Database query on the limesurvey Database
@param $sourceSurveyId int Limesurvey survey ID
@param $sql mixed SQL query to perform on the limesurvey database
@param array $bindValues optional bind values for the Query | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$this->saveLabel = $this->_('Change organization');
$choices = [
'share' => $this->_('Share between both organizations, keep tracks in old'),
'copy' => $this->_('Move tracks but keep in both organization'),
'move' => $this->_('Move tracks and remove from old organization'),
];
$bridge->addRadio('change_method',
'label', $this->_('Change method'),
'multiOptions', $choices,
'onchange', 'this.form.submit();',
'required', true
);
$sql = "SELECT gr2o_id_organization, gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ?";
$availableOrganizations = $this->util->getDbLookup()->getOrganizationsWithRespondents();
$shareOption = $this->formData['change_method'] == 'share';
$disabled = array();
$existingOrgs = $this->db->fetchPairs($sql, $this->respondent->getId());
foreach ($availableOrganizations as $orgId => &$orgName) {
$orglabel = \MUtil_Html::create('spaced');
$orglabel->strong($orgName);
if ($orgId == $this->formData['orig_org_id']) {
$disabled[] = $orgId;
$orglabel->em($this->_('Is current organization.'));
} elseif (isset($existingOrgs[$orgId])) {
$orglabel->em(sprintf(
$this->_('Exists already with respondent nr %s.'),
$existingOrgs[$orgId]
));
if ($shareOption) {
// Only disable when we just share the patient and he already exists
$disabled[] = $orgId;
}
}
$orgName = $orglabel->render($this->view);
}
$bridge->addRadio('gr2o_id_organization',
'label', $this->_('New organization'),
'disable', $disabled,
'escape', false,
'multiOptions', $availableOrganizations,
'onchange', 'this.form.submit();',
'validator', new \MUtil_Validate_IsNot(
$disabled,
$this->_('You cannot change to this organization')
)
);
if (in_array($this->formData['gr2o_id_organization'], $disabled)) {
// Selected organization is now unavailable, reset selection
$this->formData['gr2o_id_organization'] = null;
}
// Only allow to set a patient number when not exists in selected destination organization
$disablePatientNumber = array_key_exists($this->formData['gr2o_id_organization'], $existingOrgs);
if ($disablePatientNumber) {
$this->formData['gr2o_patient_nr'] = $existingOrgs[$this->formData['gr2o_id_organization']];
}
$bridge->addText('gr2o_patient_nr', 'label', $this->_('New respondent nr'),
'disabled', $disablePatientNumber ? 'disabled' : null
);
} | Adds elements from the model to the bridge that creates the form.
Overrule this function to add different elements to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function afterSave($changed)
{
// Communicate to user
if ($changed) {
switch ($this->formData['change_method']) {
case 'share':
$message = $this->_('Shared %s with %s as %s');
break;
case 'copy':
$message = $this->_('Moved %s with tracks to %s as %s');
break;
case 'move':
$message = $this->_('Moved %s to %s as %s');
break;
default:
}
$this->addMessage(sprintf(
$message,
$this->request->getParam(\MUtil_Model::REQUEST_ID1),
$this->loader->getOrganization($this->formData['gr2o_id_organization'])->getName(),
$this->formData['gr2o_patient_nr']
));
$this->accesslog->logChange($this->request, null, $this->formData);
} else {
parent::afterSave($changed);
}
} | Hook that allows actions when data was saved
When not rerouted, the form will be populated afterwards
@param int $changed The number of changed rows (0 or 1 usually, but can be more) | entailment |
protected function getTitle()
{
if ($this->respondent instanceof \Gems_Tracker_Respondent) {
if ($this->currentUser->areAllFieldsMaskedWhole('grs_first_name', 'grs_surname_prefix', 'grs_last_name')) {
return sprintf(
$this->_('Change organization of respondent nr %s'),
$this->respondent->getPatientNumber()
);
}
return sprintf(
$this->_('Change organization of respondent nr %s: %s'),
$this->respondent->getPatientNumber(),
$this->respondent->getName()
);
}
return $this->_('Change organization of respondent');
} | Retrieve the header title to display
@return string | entailment |
protected function loadFormData()
{
parent::loadFormData();
if (! isset($this->formData['change_method'])) {
$this->formData['change_method'] = null;
}
$this->formData['orig_org_id'] = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function saveData()
{
$this->beforeSave();
$fromOrgId = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
$fromPid = $this->request->getParam(\MUtil_Model::REQUEST_ID1);
$fromRespId = $this->respondent->getId();
$toOrgId = $this->formData['gr2o_id_organization'];
$toPatientId = $this->formData['gr2o_patient_nr'];
switch ($this->formData['change_method']) {
case 'share':
$this->_changed = $this->saveShare($fromOrgId, $fromPid, $toOrgId, $toPatientId);
break;
case 'copy':
$this->_changed = $this->saveShare($fromOrgId, $fromPid, $toOrgId, $toPatientId);
$this->_changed += $this->saveMoveTracks($fromOrgId, $fromRespId, $toOrgId, $toPatientId, false);
break;
case 'move':
$this->_changed = $this->saveTo($fromOrgId, $fromPid, $toOrgId, $toPatientId);
$this->_changed += $this->saveMoveTracks($fromOrgId, $fromRespId, $toOrgId, $toPatientId, true);
break;
default:
$this->_changed = 0;
}
// Message the save
$this->afterSave($this->_changed);
} | Hook containing the actual save code.
Calls afterSave() for user interaction.
@see afterSave() | entailment |
protected function saveShare($fromOrgId, $fromRespId, $toOrgId, $toPatientId)
{
$model = $this->getModel();
try {
$result = $model->copyToOrg($fromOrgId, $fromRespId, $toOrgId, $toPatientId, $this->keepConsent);
} catch (\Exception $exc) {
// Maybe we could do something with the error...
$this->addMessage($exc->getMessage());
return 0;
}
return $model->getChanged();
} | Copy the respondent
@param int $fromOrgId
@param int $fromRespId
@param int $toOrgId
@param string $toPatientId
@return int 1 If saved | entailment |
protected function saveTo($fromOrgId, $fromRespId, $toOrgId, $toPatientId)
{
$model = $this->getModel();
try {
$model->move($fromOrgId, $fromRespId, $toOrgId, $toPatientId);
} catch (\Exception $exc) {
$this->addMessage($exc->getMessage());
return 0;
}
return $model->getChanged();
} | Move the respondent
@param int $fromOrgId
@param int $fromRespId
@param int $toOrgId
@param string $toPatientId
@return int 1 If saved | entailment |
protected function setAfterSaveRoute()
{
$this->routeAction = 'show';
if ($this->request->getActionName() !== $this->routeAction) {
$this->afterSaveRouteUrl = array(
$this->request->getControllerKey() => $this->request->getControllerName(),
$this->request->getActionKey() => $this->routeAction,
);
if ($this->afterSaveRouteKeys) {
$this->afterSaveRouteUrl[\MUtil_Model::REQUEST_ID1] = $this->formData['gr2o_patient_nr'];
$this->afterSaveRouteUrl[\MUtil_Model::REQUEST_ID2] = $this->formData['gr2o_id_organization'];
}
}
return $this;
} | Set what to do when the form is 'finished'.
@return \MUtil_Snippets_ModelFormSnippetAbstract (continuation pattern) | entailment |
public function processTokenInsertion(\Gems_Tracker_Token $token)
{
$this->token = $token;
if ($token->getReceptionCode()->isSuccess() && (!$token->isCompleted())) {
// Read questioncodes
$questions = $token->getSurvey()->getQuestionList(null);
$fields = [];
$results = [];
// Check if they match a prefix schema
foreach ($questions as $code => $text) {
$upperField = strtoupper($code);
$fields[$code] = $upperField;
}
if (count($fields) > 0) {
$results = $results + $this->getTrackFields($fields);
}
return $results;
}
} | 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 |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$br = \MUtil_Html::create('br');
if ($this->showSelected) {
$selectedClass = \MUtil_Lazy::iff(\MUtil_Lazy::comp($bridge->gto_id_token, '==', $this->tokenId), 'selectedColumn', null);
} else {
$selectedClass = null;
}
$bridge->th($this->_('Status'));
$td = $bridge->tdh([
$this->util->getTokenData()->getTokenStatusLinkForBridge($bridge),
' ',
\MUtil_Lazy::first($bridge->grc_description, $this->_('OK')),
]);
$td->appendAttrib('class', $selectedClass);
$bridge->th($this->_('Question'));
if ($model->has('grr_name') && $model->has('gtf_field_name')) {
$td = $bridge->tdh(
\MUtil_Lazy::iif($bridge->grr_name, array($bridge->grr_name, $br)),
\MUtil_Lazy::iif($bridge->gtf_field_name, array($bridge->gtf_field_name, $br)),
$bridge->gto_round_description,
\MUtil_Lazy::iif($bridge->gto_round_description, $br),
\MUtil_Lazy::iif($bridge->gto_completion_time, $bridge->gto_completion_time, $bridge->gto_valid_from)
);
} else {
$td = $bridge->tdh(
$bridge->gto_round_description,
\MUtil_Lazy::iif($bridge->gto_round_description, $br),
\MUtil_Lazy::iif($bridge->gto_completion_time, $bridge->gto_completion_time, $bridge->gto_valid_from)
);
}
$td->appendAttrib('class', $selectedClass);
$td->appendAttrib('class', $bridge->row_class);
// Apply filter on the answers displayed
$answerNames = $model->getItemsOrdered();
if ($this->answerFilter instanceof \Gems_Tracker_Snippets_AnswerNameFilterInterface) {
$answerNames = $this->answerFilter->filterAnswers($bridge, $model, $answerNames);
}
foreach($answerNames as $name) {
$label = $model->get($name, 'label');
if (null !== $label) { // Was strlen($label), but this ruled out empty sub-questions
$bridge->thd($label, array('class' => $model->get($name, 'thClass')));
$td = $bridge->td($bridge->$name);
$td->appendAttrib('class', 'answer');
$td->appendAttrib('class', $selectedClass);
$td->appendAttrib('class', $bridge->row_class);
}
}
$bridge->th($this->_('Token'));
$tokenUpper = $bridge->gto_id_token->strtoupper();
if ($this->showTakeButton && $menuItem = $this->menu->find(array('controller' => 'ask', 'action' => 'take', 'allowed' => true))) {
$source = new \Gems_Menu_ParameterSource();
$source->setTokenId($bridge->gto_id_token);
$source->offsetSet('can_be_taken', $bridge->can_be_taken);
$link = $menuItem->toActionLink($source);
if ($link) {
$link->title = array($this->_('Token'), $tokenUpper);
}
$td = $bridge->tdh($bridge->can_be_taken->if($link, $tokenUpper));
} else {
$td = $bridge->tdh($tokenUpper);
}
$td->appendAttrib('class', $selectedClass);
$td->appendAttrib('class', $bridge->row_class);
} | 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 addButtons(\MUtil_Html_HtmlElement $html)
{
$buttonDiv = $html->buttonDiv();
$buttonDiv->actionLink(array(), $this->_('Close'), array('onclick' => 'window.close();'));
$buttonDiv->actionLink(array(), $this->_('Print'), array('onclick' => 'window.print();'));
} | Add the buttons to the result div
@param \MUtil_Html_HtmlElement $html | entailment |
public function addHeaderInfo(\MUtil_Html_HtmlElement $htmlDiv)
{
$htmlDiv->h3(sprintf($this->_('%s answers for patient number %s'), $this->token->getSurveyName(), $this->token->getPatientNumber()));
if (! $this->currentUser->isFieldMaskedWhole('name')) {
$htmlDiv->pInfo(sprintf(
$this->_('Answers for token %s, patient number %s: %s.'),
strtoupper($this->tokenId),
$this->token->getPatientNumber(),
$this->token->getRespondentName()))
->appendAttrib('class', 'noprint');
}
} | Add elements that form the header
@param \MUtil_Html_HtmlElement $htmlDiv | entailment |
protected function createModel()
{
$model = $this->token->getSurveyAnswerModel($this->locale->getLanguage());
$model->addColumn($this->util->getTokenData()->getStatusExpression(), 'token_status');
$model->set('gto_valid_from', 'dateFormat', $this->dateFormat);
$model->set('gto_completion_time', 'dateFormat', $this->dateFormat);
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$htmlDiv = \MUtil_Html::create()->div(array('class' => 'answer-container'));
if ($this->tokenId) {
if ($this->token->exists) {
if ($this->showHeaders) {
$this->addHeaderInfo($htmlDiv);
}
$table = parent::getHtmlOutput($view);
$table->setPivot(true, 2, 1);
$this->applyHtmlAttributes($table);
$this->class = false;
$htmlDiv[] = $table;
} else {
$htmlDiv->ul(sprintf($this->_('Token %s not found.'), $this->tokenId), array('class' => 'errors'));
}
} else {
$htmlDiv->ul($this->_('No token specified.'), array('class' => 'errors'));
}
if ($this->showButtons) {
$this->addButtons($htmlDiv);
}
return $htmlDiv;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function hasHtmlOutput()
{
if (! $this->tokenId) {
if (isset($this->token)) {
$this->tokenId = $this->token->getTokenId();
}
} elseif (! $this->token) {
$this->token = $this->loader->getTracker()->getToken($this->tokenId);
}
// Output always true, returns an error message as html when anything is wrong
return true;
} | 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 |
public function getFullDescription()
{
if ($this->_description) {
return $this->_description;
}
$descr = $this->getRoundDescription();
$hasDescr = strlen(trim($descr));
$order = $this->getRoundOrder();
$survey = $this->getSurvey();
$surveyExists = $survey ? $survey->exists : false;
if ($order) {
if ($hasDescr) {
if ($surveyExists) {
$this->_description = sprintf($this->_('%d: %s - %s'), $order, $descr, $survey->getName());
} else {
$this->_description = sprintf($this->_('%d: %s'), $order, $descr);
}
} elseif ($surveyExists) {
$this->_description = sprintf($this->_('%d: %s'), $order, $survey->getName());
} else {
$this->_description = $order;
}
} elseif ($hasDescr) {
if ($surveyExists) {
$this->_description = sprintf($this->_('%s - %s'), $descr, $survey->getName());
} else {
$this->_description = $descr;
}
} else {
if ($surveyExists) {
$this->_description = $survey->getName();
} else {
$this->_description = '';
}
}
return $this->_description;
} | Get a round description with order number and survey name
@return string | entailment |
public function getSurvey()
{
if (false !== $this->_survey) {
return $this->_survey;
}
$surveyId = $this->getSurveyId();
if ($surveyId) {
$this->_survey = $this->tracker->getSurvey($surveyId);
} else {
$this->_survey = null;
}
return $this->_survey;
} | Get the survey id for this round
@return \Gems_Tracker_Survey | entailment |
public function getRespondent()
{
static $respondent;
if (! $respondent) {
$patientNumber = $this->_getParam(\MUtil_Model::REQUEST_ID1);
$organizationId = $this->_getParam(\MUtil_Model::REQUEST_ID2);
$respondent = $this->loader->getRespondent($patientNumber, $organizationId);
if ((! $respondent->exists) && $patientNumber && $organizationId) {
throw new \Gems_Exception(sprintf($this->_('Unknown respondent %s.'), $patientNumber));
}
$respondent->applyToMenuSource($this->menu->getParameterSource());
}
return $respondent;
} | Get the respondent object
@return \Gems_Tracker_Respondent | entailment |
public function getSearchData($useRequest = true)
{
$data = parent::getSearchData($useRequest);
// Survey action data
$data['gto_id_respondent'] = $this->getRespondentId();
$orgsFor = $this->util->getOtherOrgsFor($this->_getParam(\MUtil_Model::REQUEST_ID2));
if (is_array($orgsFor)) {
$data['gto_id_organization'] = $orgsFor;
} elseif (true !== $orgsFor) {
$data['gto_id_organization'] = $this->_getParam(\MUtil_Model::REQUEST_ID2);
}
return $data;
} | Get the data to use for searching: the values passed in the request + any defaults
used in the search form (or any other search request mechanism).
It does not return the actual filter used in the query.
@see getSearchFilter()
@param boolean $useRequest Use the request as source (when false, the session is used)
@return array | entailment |
public function applyBrowseSettings($addCount = true)
{
$conditions = $this->loader->getConditions();
$yesNo = $this->util->getTranslated()->getYesNo();
$types = $conditions->getConditionTypes();
reset($types);
$default = key($types);
$this->set('gcon_type', 'label', $this->_('Type'),
'description', $this->_('Determines where the condition can be applied.'),
'multiOptions', $types,
'default', $default
);
$this->set('gcon_class', 'label', $this->_('Condition'),
'multiOptions', []
);
$this->set('gcon_name', 'label', $this->_('Name'));
$this->set('gcon_active', 'label', $this->_('Active'),
'multiOptions', $yesNo
);
$this->addColumn("CASE WHEN gcon_active = 1 THEN '' ELSE 'deleted' END", 'row_class');
if ($addCount) {
$this->addColumn(
"(SELECT COUNT(gro_id_round) FROM gems__rounds WHERE gcon_id = gro_condition)",
'usage'
);
$this->set('usage', 'label', $this->_('Rounds'),
'description', $this->_('The number of rounds using this condition.'),
'elementClass', 'Exhibitor'
);
}
$this->addDependency('Condition\\TypeDependency');
return $this;
} | Set those settings needed for the browse display
@param boolean $addCount Add a count in rounds column
@return \Gems\Model\ConditionModel | entailment |
public function applyDetailSettings()
{
$this->applyBrowseSettings(false);
$yesNo = $this->util->getTranslated()->getYesNo();
$this->resetOrder();
$this->set('gcon_type');
$this->set('gcon_class');
$this->set('gcon_name', 'description', $this->_('A name for this condition, will be used to select it when applying the condition.'));
$this->set('condition_help', 'label', $this->_('Help'), 'elementClass', 'Exhibitor');
// Set the order
$this->set('gcon_condition_text1');
$this->set('gcon_condition_text2');
$this->set('gcon_condition_text3');
$this->set('gcon_condition_text4');
$this->set('gcon_active', 'label', $this->_('Active'),
'multiOptions', $yesNo
);
$this->addDependency('Condition\\ClassDependency');
return $this;
} | Set those settings needed for the detailed display
@return \Gems\Model\ConditionModel | entailment |
public function applyEditSettings($create = false)
{
$this->applyDetailSettings();
// gcon_id is not needed for some validators
$this->set('gcon_id', 'elementClass', 'Hidden');
$this->set('gcon_active', 'elementClass', 'Checkbox');
return $this;
} | Set those values needed for editing
@return \Gems\Model\ConditionModel | entailment |
protected function getTabs()
{
$tabs['default'] = array($this->_('Default'), 'title' => $this->_('To do 2 weeks ahead and done'));
$tabs['todo'] = $this->_('To do');
$tabs['done'] = $this->_('Done');
$tabs['missed'] = $this->_('Missed');
$tabs['all'] = $this->_('All');
return $tabs;
} | Function used to fill the tab bar
@return array tabId => label | entailment |
public function hasHtmlOutput()
{
$reqFilter = $this->request->getParam('filter');
switch ($reqFilter) {
case 'todo':
//Only actions valid now that are not already done
$filter[] = 'gto_completion_time IS NULL';
$filter[] = 'gto_valid_from <= CURRENT_TIMESTAMP';
$filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
break;
case 'done':
//Only completed actions
$filter[] = 'gto_completion_time IS NOT NULL';
break;
case 'missed':
//Only missed actions (not filled in, valid until < today)
$filter[] = 'gto_completion_time IS NULL';
$filter[] = 'gto_valid_until < CURRENT_TIMESTAMP';
break;
case 'all':
$filter[] = 'gto_valid_from IS NOT NULL';
break;
default:
//2 weeks look ahead, valid from date is set
$filter[] = 'gto_valid_from IS NOT NULL';
$filter[] = 'DATEDIFF(gto_valid_from, CURRENT_TIMESTAMP) < 15';
$filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
}
$this->model->setMeta('tab_filter', $filter);
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 |
public function validate($bankAccountNumber)
{
if (is_array($bankAccountNumber)) {
$parts = $bankAccountNumber;
} else {
$parts = $this->parseNumber($bankAccountNumber);
}
if (empty($parts)) {
return false;
}
list($firstPart, $secondPart, $bankCode) = $parts;
if (!$this->validateBankCode($bankCode)) {
return false;
}
if (null !== $firstPart && !$this->validateCheckSum($firstPart)) {
return false;
}
if (!$this->validateCheckSum($secondPart)) {
return false;
}
return true;
} | Use full valid format YYYY-XXXXXX/ZZZZ - prefix part is optional
Or use output from parseNumber method (array)
@param string|array $bankAccountNumber
@return bool | entailment |
public function validateCheckSum($bankAccountPart)
{
$bankAccountPart = $this->trimZeroDigits($bankAccountPart);
if (!empty($bankAccountPart)) {
preg_match_all('/(\d)/', $bankAccountPart, $parts);
if (!empty($parts) && !empty($parts[0])) {
$parts = $parts[0];
$sum = 0;
$parts = array_reverse($parts);
foreach ($parts as $order => $digit) {
if (!isset($this->scale[$order])) {
return false;
}
$sum += $this->scale[$order] * (int)$digit;
}
return 0 === $sum % 11;
}
} else {
return true;
}
return false;
} | Count and verify checkSum based on legislative
@param string $bankAccountPart - numeric part from account number (first or second - before/after separator)
@return bool | entailment |
public function validateBankCode($bankCode)
{
return self::BANK_CODE_LENGTH == strlen($bankCode) && isset($this->validBankCodes[$bankCode]);
} | @param string $bankCode
@return bool | entailment |
public function parseNumber($bankAccountNumber)
{
$pattern = <<<PATTERN
~
^
(?:
((\d{0,%1\$d})-(\d{%2\$d,%3\$d})) # account number with two parts
| # or
((\d{%2\$d,%3\$d})) # single number
)?
\/ # slash for separate bank code
(\d{%4\$d}) # bank code
$
~xim
PATTERN;
$pattern = sprintf(
$pattern,
self::FIRST_PART_MAX_DIGITS,
self::SECOND_PART_MIN_DIGITS,
self::SECOND_PART_MAX_DIGITS,
self::BANK_CODE_LENGTH
);
$firstPart = $secondPart = $bankCode = null;
preg_match($pattern, $bankAccountNumber, $match);
if (!empty($match[6])) {
$bankCode = $match[6];
}
if (isset($match[2])
&& '' !== $match[2]
&& isset($match[3])
&& '' !== $match[3]) {
$firstPart = $match[2];
$secondPart = $match[3];
} elseif (!empty($match[5])) {
$secondPart = $match[5];
}
return [$firstPart, $secondPart, $bankCode];
} | Parse string account number in format XXXX-YYYYYY/ZZZZ or XXXXXXX/ZZZZ
@param string $bankAccountNumber
@return array [$firstPart, $secondPart, $bankCode] - if some part is not matched, return it null | entailment |
private function getBankCodes($codesFile)
{
if (!is_file($codesFile)) {
throw new MissingBankCodesFileException('Czech bank codes CSV file is not valid. ' . $codesFile);
}
$data = str_getcsv(file_get_contents($codesFile), "\n");
array_shift($data);
$validBankCodes = [];
foreach($data as &$row) {
$row = str_getcsv($row, ";");
$validBankCodes[$row[0]] = $row[1];
}
return $validBankCodes;
} | @param $codesFile
@return array
@throws MissingBankCodesFileException | entailment |
protected function getUserSelect($login_name, $organization)
{
if ((0 == ($this->hoursResetKeyIsValid % 24)) || \Zend_Session::$_unitTestEnabled) {
$resetExpr = 'CASE WHEN ADDDATE(gup_reset_requested, ' .
intval($this->hoursResetKeyIsValid / 24) .
') >= CURRENT_TIMESTAMP THEN 1 ELSE 0 END';
} else {
$resetExpr = 'CASE WHEN DATE_ADD(gup_reset_requested, INTERVAL ' .
$this->hoursResetKeyIsValid .
' HOUR) >= CURRENT_TIMESTAMP THEN 1 ELSE 0 END';
}
// 'user_group' => 'gsf_id_primary_group', 'user_logout' => 'gsf_logout_on_survey',
$select = new \Zend_Db_Select($this->db);
$select->from('gems__user_logins', array(
'user_login_id' => 'gul_id_user',
'user_two_factor_key' => 'gul_two_factor_key',
'user_enable_2factor' => 'gul_enable_2factor',
'user_active' => 'gul_can_login',
))
->join('gems__respondent2org', 'gul_login = gr2o_patient_nr AND gul_id_organization = gr2o_id_organization', array(
'user_login' => 'gr2o_patient_nr',
'user_base_org_id' => 'gr2o_id_organization',
'user_email' => 'gr2o_email',
))
->join('gems__respondents', 'gr2o_id_user = grs_id_user', array(
'user_id' => 'grs_id_user',
'user_first_name' => 'grs_first_name',
'user_surname_prefix' => 'grs_surname_prefix',
'user_last_name' => 'grs_last_name',
'user_gender' => 'grs_gender',
'user_locale' => 'grs_iso_lang',
'user_birthday' => 'grs_birthday',
'user_zip' => 'grs_zipcode',
))
->join('gems__organizations', 'gr2o_id_organization = gor_id_organization', array(
'user_group' => 'gor_respondent_group',
))
->join('gems__groups', 'gor_respondent_group = ggp_id_group', array(
'user_role' => 'ggp_role',
'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges',
))
->joinLeft('gems__user_passwords', 'gul_id_user = gup_id_user', array(
'user_password_reset' => 'gup_reset_required',
'user_resetkey_valid' => new \Zend_Db_Expr($resetExpr),
'user_password_last_changed' => 'gup_last_pwd_change',
))
->joinLeft('gems__reception_codes', 'gr2o_reception_code = grc_id_reception_code', array())
->where('ggp_group_active = 1')
->where('grc_success = 1')
->where('gul_can_login = 1')
->where('gul_login = ?')
->where('gul_id_organization = ?')
->limit(1);
return $select;
} | A select used by subclasses to add fields to the select.
@param string $login_name
@param int $organization
@return \Zend_Db_Select | entailment |
public function execute()
{
$role = \Gems_Roles::getInstance();
$parents = $this->db->fetchPairs("SELECT grl_id_role, grl_parents FROM gems__roles");
// \MUtil_Echo::track($parents);
if ($parents) {
foreach ($parents as $id => $priv) {
$values['grl_parents'] = implode(',', $role->translateToRoleIds($priv));
$this->db->update('gems__roles', $values, $this->db->quoteInto('grl_id_role = ?', $id));
}
}
} | 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)
{
$respondent = $this->getRespondent();
$model = $this->loader->getModels()->createEpisodeOfCareModel();
if ($detailed) {
if (('edit' === $action) || ('create' === $action)) {
$model->applyEditSettings($respondent->getOrganizationId(), $respondent->getId());
// When there is something saved, then set manual edit to 1
$model->setSaveOnChange('gec_manual_edit');
$model->setOnSave( 'gec_manual_edit', 1);
} else {
$model->applyDetailSettings();
}
} else {
$model->applyBrowseSettings();
$model->addFilter(array(
'gec_id_user' => $respondent->getId(),
'gec_id_organization' => $respondent->getOrganizationId(),
));
}
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 getContentTitle()
{
$respondent = $this->getRespondent();
$patientId = $respondent->getPatientNumber();
if ($patientId) {
if ($this->currentUser->areAllFieldsMaskedWhole('grs_first_name', 'grs_surname_prefix', 'grs_last_name')) {
return sprintf($this->_('Episodes of care for respondent number %s'), $patientId);
}
return sprintf($this->_('Episodes of care for respondent number %s: %s'), $patientId, $respondent->getName());
}
return $this->getIndexTitle();
} | Helper function to get the informed title for the index action.
@return $string | entailment |
public function getRespondent()
{
if (! $this->_respondent) {
$id = $this->_getParam(\Gems_Model::EPISODE_ID);
if ($id && ! ($this->_getParam(\MUtil_Model::REQUEST_ID1) || $this->_getParam(\MUtil_Model::REQUEST_ID2))) {
$episode = $this->loader->getAgenda()->getEpisodeOfCare($id);
$this->_respondent = $episode->getRespondent();
if (! $this->_respondent->exists) {
throw new \Gems_Exception($this->_('Unknown respondent.'));
}
$this->_respondent->applyToMenuSource($this->menu->getParameterSource());
} else {
$this->_respondent = parent::getRespondent();
}
}
return $this->_respondent;
} | Get the respondent object
@return \Gems_Tracker_Respondent | entailment |
public function getTopic($count = 1)
{
$respondent = $this->getRespondent();
$patientId = $respondent->getPatientNumber();
if ($patientId) {
if ($this->currentUser->areAllFieldsMaskedWhole('grs_first_name', 'grs_surname_prefix', 'grs_last_name')) {
$for = sprintf($this->_('for respondent number %s'), $patientId);
} else {
$for = sprintf($this->_('for respondent number %s'), $patientId);
}
$for = ' ' . $for;
} else {
$for = '';
}
return $this->plural('episode of care', 'episodes of care', $count) . $for;
} | Helper function to allow generalized statements about the items in the model.
@param int $count
@return $string | entailment |
public function format($row, $model) {
foreach ($row as $fieldname=>$value) {
$row[$fieldname] = $this->_format($fieldname, $row[$fieldname], $model);
}
return $row;
} | Formats a row of data using the given model
Static method only available for single rows, for a convenient way of using on a
rowset, use the class and iterate
@param array $row
@param \MUtil_Model_ModelAbstract $model
@return array The formatted array | entailment |
private function _format($name, $result, $model)
{
static $view = null;
if (!isset($this->_options[$name])) {
$this->_options[$name] = $model->get($name, array('default', 'multiOptions', 'formatFunction', 'dateFormat', 'storageFormat', 'itemDisplay'));
}
$options = $this->_options[$name];
foreach($options as $key => $value) {
switch ($key) {
case 'default':
if (is_null($result)) {
$result = $value;
}
break;
case 'multiOptions':
$multiOptions = $value;
if (is_array($multiOptions)) {
/*
* Sometimes a field is an array and will be formatted later on using the
* formatFunction -> handle each element in the array.
*/
if (is_array($result)) {
foreach($result as $key => $value) {
if (array_key_exists($value, $multiOptions)) {
$result[$key] = $multiOptions[$value];
}
}
} else {
if (array_key_exists($result, $multiOptions)) {
$result = $multiOptions[$result];
}
}
}
break;
case 'formatFunction':
$callback = $value;
$result = call_user_func($callback, $result);
break;
case 'dateFormat':
if (array_key_exists('formatFunction', $options)) {
// if there is a formatFunction skip the date formatting
continue;
}
$dateFormat = $value;
$storageFormat = $model->get($name, 'storageFormat');
$result = \MUtil_Date::format($result, $dateFormat, $storageFormat);
break;
case 'itemDisplay':
$function = $value;
if (is_callable($function)) {
$result = call_user_func($function, $result);
} elseif (is_object($function)) {
if (($function instanceof \MUtil_Html_ElementInterface)
|| method_exists($function, 'append')) {
$object = clone $function;
$result = $object->append($result);
}
} elseif (is_string($function)) {
// Assume it is a html tag when a string
$result = \MUtil_Html::create($function, $result);
}
default:
break;
}
}
if (is_object($result)) {
// If it is Lazy, execute it
if ($result instanceof \MUtil_Lazy_LazyInterface) {
$result = \MUtil_Lazy::rise($result);
}
// If it is Html, render it
if ($result instanceof \MUtil_Html_HtmlInterface) {
if (is_null($view)) {
$viewRenderer = \Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (null === $viewRenderer->view) {
$viewRenderer->initView();
}
$view = $viewRenderer->view;
}
$result = $result->render($view);
}
}
return $result;
} | This is the actual format function, copied from the Exhibitor for field
@param type $name
@param type $result
@param \MUtil_Model_ModelAbstract $model
@return type | entailment |
public function write($path, $contents, Config $config)
{
return $this->writeObject($path, $contents, $config);
} | Write a new file.
@param string $path
@param string $contents
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function writeStream($path, $resource, Config $config)
{
return $this->writeObject($path, $resource, $config);
} | Write a new file using a stream.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function update($path, $contents, Config $config)
{
return $this->writeObject($path, $contents, $config);
} | Update a file.
@param string $path
@param string $contents
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function updateStream($path, $resource, Config $config)
{
return $this->writeObject($path, $resource, $config);
} | Update a file using a stream.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function rename($path, $newpath)
{
$statusCopy = $this->copy($path, $newpath);
$statusRemoveOld = $this->delete($path);
return $statusCopy && $statusRemoveOld;
} | Rename a file.
@param string $path
@param string $newpath
@return bool | entailment |
public function copy($path, $newpath)
{
$path = $this->applyPathPrefix($path);
$newpath = $this->applyPathPrefix($newpath);
$this->bucket
->object($path)
->copy($this->bucket, ['name' => $newpath]);
return $this->bucket->object($newpath)->exists();
} | Copy a file.
@param string $path
@param string $newpath
@return bool | entailment |
public function delete($path)
{
$path = $this->applyPathPrefix($path);
$object = $this->bucket->object($path);
if (false === $object->exists()) {
return true;
}
$object->delete();
return !$object->exists();
} | Delete a file.
@param string $path
@return bool | entailment |
public function deleteDir($dirname)
{
$dirname = rtrim($dirname, '/').'/';
if (false === $this->has($dirname)) {
return false;
}
$dirname = $this->applyPathPrefix($dirname);
$this->bucket->object($dirname)->delete();
return !$this->bucket->object($dirname)->exists();
} | Delete a directory.
@param string $dirname
@return bool | entailment |
public function createDir($dirname, Config $config)
{
$path = $this->applyPathPrefix($dirname);
$path = rtrim($path, '/').'/';
$object = $this->bucket->upload('', ['name' => $path]);
return $this->convertObjectInfo($object);
} | Create a directory.
@param string $dirname directory name
@param Config $config
@return array|false | entailment |
public function setVisibility($path, $visibility)
{
$path = $this->applyPathPrefix($path);
$object = $this->bucket->object($path);
switch (true) {
case $visibility === AdapterInterface::VISIBILITY_PUBLIC:
$object->acl()->add('allUsers', Acl::ROLE_READER);
break;
case $visibility === AdapterInterface::VISIBILITY_PRIVATE:
$object->acl()->delete('allUsers');
break;
default:
// invalid value
break;
}
$object->reload();
return $this->convertObjectInfo($object);
} | Set the visibility for a file.
@param string $path
@param string $visibility
@return array|false file meta data | entailment |
public function has($path)
{
$path = $this->applyPathPrefix($path);
$object = $this->bucket->object($path);
return $object->exists();
} | Check whether a file exists.
@param string $path
@return array|bool|null | entailment |
public function read($path)
{
$path = $this->applyPathPrefix($path);
$object = $this->bucket->object($path);
$contents = $object->downloadAsString();
return compact('path', 'contents');
} | Read a file.
@param string $path
@return array|false | entailment |
public function listContents($directory = '', $recursive = false)
{
$directory = $this->applyPathPrefix($directory);
$objects = $this->bucket->objects(
[
'prefix' => $directory,
]
);
$contents = [];
foreach ($objects as $apiObject) {
if (null !== $apiObject) {
$contents[] = $this->convertObjectInfo($apiObject);
}
}
// if directory, skip the directory object
// if directory, truncate prefix + delimiter
if ('' !== $directory) {
foreach ($contents as $idx => $objectInfo) {
if ('dir' === $objectInfo['type'] && $objectInfo['path'] === $directory) {
$contents[$idx] = false;
}
}
}
return array_filter($contents);
} | List contents of a directory.
@param string $directory
@param bool $recursive
@return array | entailment |
public function getMetadata($path)
{
$path = $this->applyPathPrefix($path);
$object = $this->bucket->object($path);
if (!$object->exists()) {
return false;
}
return $this->convertObjectInfo($object);
} | Get all the meta data of a file or directory.
@param string $path
@return array|false | entailment |
public function getVisibility($path)
{
$path = $this->applyPathPrefix($path);
try {
$allUsersAcl = $this->bucket->object($path)->acl()->get(['entity' => 'allUsers']);
if ($allUsersAcl['role'] === Acl::ROLE_READER) {
return ['path' => $path, 'visibility' => AdapterInterface::VISIBILITY_PUBLIC];
}
} catch (NotFoundException $e) {
return ['path' => $path, 'visibility' => AdapterInterface::VISIBILITY_PRIVATE];
}
return ['path' => $path, 'visibility' => AdapterInterface::VISIBILITY_PRIVATE];
} | Get the visibility of a file.
@param string $path
@return array|false | entailment |
public function getUrl($path)
{
$path = $this->applyPathPrefix($path);
return implode('/', [$this->baseUrl, $path]);
} | @param string $path
@return string | entailment |
protected function convertObjectInfo($object)
{
$identity = $object->identity();
$objectInfo = $object->info();
$objectName = $identity['object'];
// determine whether it's a file or a directory
$type = 'file';
$objectNameLength = strlen($objectName);
if (strpos($objectName, '/', $objectNameLength - 1)) {
$type = 'dir';
}
$normalizedObjectInfo = [
'type' => $type,
'path' => $objectName,
];
// timestamp
$datetime = \DateTime::createFromFormat('Y-m-d\TH:i:s+', $objectInfo['updated']);
$normalizedObjectInfo['timestamp'] = $datetime->getTimestamp();
// size when file
if ($type === 'file') {
$normalizedObjectInfo['size'] = $objectInfo['size'];
$normalizedObjectInfo['mimetype'] = isset($objectInfo['contentType']) ? $objectInfo['contentType'] : null;
}
return $normalizedObjectInfo;
} | @param $object StorageObject
@return array | entailment |
protected function getOptionsFromConfig(Config $config)
{
$options = [];
if ($config->has('visibility')) {
switch (true) {
case $config->get('visibility') === AdapterInterface::VISIBILITY_PUBLIC:
$options['predefinedAcl'] = static::GCS_VISIBILITY_PUBLIC_READ;
break;
case $config->get('visibility') === AdapterInterface::VISIBILITY_PRIVATE:
default:
$options['predefinedAcl'] = static::GCS_VISIBILITY_PROJECT_PRIVATE;
break;
}
}
return $options;
} | Converts flysystem specific config to options for the underlying API client
@param $config Config
@return array | entailment |
protected function writeObject($path, $contents, Config $config)
{
$path = $this->applyPathPrefix($path);
$metadata = [
'name' => $path,
];
$metadata += $this->getOptionsFromConfig($config);
$uploadedObject = $this->bucket->upload($contents, $metadata);
$uploadedObject->reload();
return $this->convertObjectInfo($uploadedObject);
} | Writes an object to the current
@param string $path
@param string|resource $contents
@param Config $config
@return array | entailment |
public function createModel($detailed, $action)
{
// \MUtil_Model::$verbose = true;
$model = $this->loader->getTracker()->getTokenModel();
$model->setCreate(false);
$model->set('gr2o_patient_nr', 'label', $this->_('Respondent'));
$model->set('gto_round_description', 'label', $this->_('Round / Details'));
$model->set('gto_valid_from', 'label', $this->_('Valid from'));
$model->set('gto_valid_until', 'label', $this->_('Valid until'));
$model->set('gto_mail_sent_date', 'label', $this->_('Contact date'));
$model->set('respondent_name', 'label', $this->_('Name'));
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 emailAction()
{
$model = $this->getModel();
$model->setFilter($this->getSearchFilter(false));
$sort = array(
'gr2o_email' => SORT_ASC,
'grs_first_name' => SORT_ASC,
'grs_surname_prefix' => SORT_ASC,
'grs_last_name' => SORT_ASC,
'gto_valid_from' => SORT_ASC,
'gto_round_order' => SORT_ASC,
'gsu_survey_name' => SORT_ASC,
);
if ($tokensData = $model->load(true, $sort)) {
$params['mailTarget'] = 'token';
$params['menu'] = $this->menu;
$params['model'] = $model;
$params['identifier'] = $this->_getIdParam();
$params['view'] = $this->view;
$params['routeAction'] = 'index';
$params['formTitle'] = sprintf($this->_('Send mail to: %s'), $this->getTopic());
$params['templateOnly'] = ! $this->currentUser->hasPrivilege('pr.token.mail.freetext');
$params['multipleTokenData'] = $tokensData;
$this->addSnippet('Mail_TokenBulkMailFormSnippet', $params);
} else {
$this->addMessage($this->_('No tokens found.'));
}
} | Bulk email action | entailment |
public function getSearchDefaults()
{
if (! $this->defaultSearchData) {
$inFormat = \MUtil_Model_Bridge_FormBridge::getFixedOption('date', 'dateFormat');
$now = new \MUtil_Date();
$today = $now->toString($inFormat);
$this->defaultSearchData = array(
'datefrom' => $today,
'dateused' => '_gto_valid_from gto_valid_until',
'dateuntil' => $today,
'main_filter' => '',
);
}
return parent::getSearchDefaults();
} | Function to allow the creation of search defaults in code
@see getSearchFilter()
@return array | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.