sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
$this->_addPeriodSelectors($elements, 'gla_created');
$elements[] = null;
$elements[] = $this->_('Specific action');
$sql = "SELECT gls_id_action, gls_name
FROM gems__log_setup
WHERE gls_when_no_user = 1 OR gls_on_action = 1 OR gls_on_change = 1 OR gls_on_post = 1
ORDER BY gls_name";
$elements[] = $this->_createSelectElement('gla_action', $sql, $this->_('(any action)'));
$elements[] = $this->_createSelectElement(
'gla_organization',
$this->loader->getCurrentUser()->getAllowedOrganizations(),
$this->_('(all organizations)')
);
return $elements;
} | Returns a text element for autosearch. Can be overruled.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks. | entailment |
public function getExportModelSource()
{
if (! $this->_exportModelSource) {
$this->_exportModelSource = $this->loader->getExportModelSource($this->exportModelSourceClass);
}
return $this->_exportModelSource;
} | Function to get a model source for this export
@return \Gems_Export_ModelSource_ExportModelSourceAbstract | entailment |
public function getSearchFilter($useRequest = false)
{
if (null !== $this->_searchFilter) {
return $this->_searchFilter;
}
$this->_searchFilter = parent::getSearchFilter($useRequest);
$this->_searchFilter[] = 'gto_start_time IS NOT NULL';
if (!isset($this->_searchFilter['incomplete']) || !$this->_searchFilter['incomplete']) {
$this->_searchFilter[] = 'gto_completion_time IS NOT NULL';
}
if (isset($this->_searchFilter['dateused']) && $this->_searchFilter['dateused']) {
$where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($this->_searchFilter, $this->db);
if ($where) {
$this->_searchFilter[] = $where;
}
}
$this->_searchFilter['gco_code'] = 'consent given';
$this->_searchFilter['grc_success'] = 1;
if (isset($this->_searchFilter['ids'])) {
$idStrings = $this->_searchFilter['ids'];
$idArray = preg_split('/[\s,;]+/', $idStrings, -1, PREG_SPLIT_NO_EMPTY);
if ($idArray) {
$this->_searchFilter['gto_id_respondent'] = $idArray;
}
}
return $this->_searchFilter;
} | Get the filter to use with the model for searching including model sorts, etc..
@param boolean $useRequest Use the request as source (when false, the session is used)
@return array or false | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$seq = $this->getHtmlSequence();
$seq->h2($this->_('Checks'));
$ul = $seq->ul();
$ul->li($this->_('Executes respondent change event for all active respondents.'));
$seq->pInfo($this->_(
'Run this code when the respondent change event was changed or e.g. when a new "default" track was created.'
));
return $seq;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
public function execute($sourceId = null, $sourceSurveyId = null, $surveyId = null)
{
$batch = $this->getBatch();
if ($surveyId) {
$survey = $this->loader->getTracker()->getSurvey($surveyId);
} else {
$survey = $this->loader->getTracker()->getSurveyBySourceId($sourceSurveyId, $sourceId);
}
if (! $survey->isActive()) {
return;
}
// Now save the questions
$answerModel = $survey->getAnswerModel('en');
$hash = $survey->calculateHash();
if ($survey->getHash() === $hash) {
return;
}
$survey->setHash($hash, $this->loader->getCurrentUser()->getUserId());
foreach ($answerModel->getItemsOrdered() as $order => $name) {
if (true === $answerModel->get($name, 'survey_question')) {
$batch->addTask('Tracker_RefreshQuestion', $surveyId, $name, $order);
}
}
// If we have a response database, create a view on the answers
if ($this->project->hasResponseDatabase()) {
$this->replaceCreateView($survey, $answerModel);
}
} | 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 replaceCreateView(\Gems_Tracker_Survey $survey, \MUtil_Model_ModelAbstract $answerModel)
{
$viewName = $this->getViewName($survey);
$responseDb = $this->project->getResponseDatabase();
$fieldSql = '';
foreach ($answerModel->getItemsOrdered() as $name) {
if (true === $answerModel->get($name, 'survey_question') && // It should be a question
!in_array($name, array('submitdate', 'startdate', 'datestamp')) && // Leave out meta info
!$answerModel->is($name, 'type', \MUtil_Model::TYPE_NOVALUE)) { // Only real answers
$fieldSql .= ',MAX(IF(gdr_answer_id = ' . $responseDb->quote($name) . ', gdr_response, NULL)) AS ' . $responseDb->quoteIdentifier($name);
}
}
if ($fieldSql > '') {
$dbConfig = $this->db->getConfig();
$tokenTable = $this->db->quoteIdentifier($dbConfig['dbname'] . '.gems__tokens');
$createViewSql = 'CREATE OR REPLACE VIEW ' . $responseDb->quoteIdentifier($viewName) . ' AS SELECT gdr_id_token';
$createViewSql .= $fieldSql;
$createViewSql .= "FROM gemsdata__responses join " . $tokenTable .
" on (gto_id_token=gdr_id_token and gto_id_survey=" . $survey->getSurveyId() .
") GROUP BY gdr_id_token;";
try {
$responseDb->query($createViewSql)->execute();
} catch (Exception $exc) {
$responseConfig = $responseDb->getConfig();
$dbUser = $this->db->quoteIdentifier($responseConfig['username']) . '@' .
$this->db->quoteIdentifier($responseConfig['host']);
$statement = "GRANT SELECT ON " . $tokenTable . " TO " . $dbUser;
$batch = $this->getBatch();
$batch->addMessage(sprintf(
$this->_("View creation failed for survey %s with message: '%s'"),
$survey->getName(),
$exc->getMessage()
));
$batch->addMessage(sprintf($this->_("View creation statement: %s"), $createViewSql));
$batch->addMessage(sprintf($this->_("Try adding rights using this statement: %s"), $statement));
}
}
} | Handles creating or replacing the view for this survey
@param \Gems_Tracker_Survey $viewName
@param \MUtil_Model_ModelAbstract $answerModel | entailment |
public function addSeparator($token)
{
$cellContent = $this->wikiContentArr[$this->separatorCount];
if ($cellContent === '') {
if ($this->previousGenerator) {
$this->previousGenerator->setColSpan($this->previousGenerator->getColSpan() + 1);
}
} else {
if (preg_match('/^\s\s/', $cellContent) &&
preg_match('/\s\s$/', $cellContent)) {
if (trim($cellContent) != '') {
$this->generator->setAlign('center');
}
} elseif (preg_match('/^\s\s/', $cellContent)) {
$this->generator->setAlign('right');
} elseif (preg_match('/\s\s$/', $cellContent) && preg_match('/^\S/', $cellContent)) {
$this->generator->setAlign('left');
}
$this->row->addGenerator($this->generator);
$this->wikiContent .= $cellContent;
$this->previousGenerator = $this->generator;
$this->generator = $this->documentGenerator->getInlineGenerator($this->generatorName);
if ($token == '^') {
$this->generator->setIsHeader(true);
}
++$this->separatorCount;
$this->contents[$this->separatorCount] = '';
$this->wikiContentArr[$this->separatorCount] = '';
}
$this->currentSeparator = $token;
$this->wikiContent .= $token;
} | called by the inline parser, when it found a separator.
@param string $token | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view) {
//$view->headLink()->prependStylesheet($view->serverUrl() . \GemsEscort::getInstance()->basepath->getBasePath() . '/gems/css/barchart.less', 'screen,print');
$htmlDiv = \MUtil_Html::create()->div(' ', array('class'=>'barchartcontainer'));
if ($this->showHeaders) {
if (isset($this->token)) {
$htmlDiv->h3(sprintf($this->_('Overview for patient number %s'), $this->token->getPatientNumber()));
$htmlDiv->pInfo(sprintf(
$this->_('Overview for patient number %s: %s.'),
$this->token->getPatientNumber(),
$this->token->getRespondentName()))
->appendAttrib('class', 'noprint');
} else {
$htmlDiv->pInfo($this->_('No data present'));
}
}
if (!empty($this->data)) {
$htmlDiv->append($this->getChart()); // Insert the chart here
}
if ($this->showButtons) {
$buttonDiv = $htmlDiv->buttonDiv();
$buttonDiv->actionLink(array(), $this->_('Back'), array('onclick' => 'window.history.go(-1); return false;'));
$buttonDiv->actionLink(array(), $this->_('Print'), array('onclick' => 'window.print();'));
}
// Make vertically resizable
$view = \Zend_Layout::getMvcInstance()->getView();
/*$jquery = $view->jQuery();
$jquery->enable();*/
\MUtil_JQuery::enableView($view);
// We need width 100% otherwise it will look strange in print output
$view->jQuery()->addOnLoad("$('.barchart').resizable({
handles: 's',
resize: function( event, ui ) { ui.element.css({ width: '100%'}); },
minHeight: 150
});");
return $htmlDiv;
} | Copied from parent, but insert chart instead of table after commented out part
@param \Zend_View_Abstract $view
@return type | entailment |
private function getPercentage($value)
{
$percentage = ($value - $this->min) / ($this->max - $this->min) * 100;
return $percentage;
} | Return the percentage in the range between min and max for this chart
@param number $value
@return float | entailment |
public function getTab(): string
{
$mailsCount = count($this->traceableMailer->getMails());
if ($mailsCount === 0) {
return '';
}
ob_start();
require 'templates/tab.phtml';
return (string) ob_get_clean();
} | Renders HTML code for custom tab. | entailment |
protected function _ensureTrackFields()
{
if (! is_array($this->_fields)) {
// Check for cases where the track id is zero, but there is a field for track 0 in the db
if ($this->_trackId) {
$model = $this->getMaintenanceModel();
$fields = $model->load(array('gtf_id_track' => $this->_trackId), array('gtf_id_order' => SORT_ASC));
} else {
$fields = false;
}
$this->_fields = array();
$this->_trackFields = array();
if (is_array($fields)) {
$this->exists = true;
foreach ($fields as $field) {
$key = self::makeKey($field['sub'], $field['gtf_id_field']);
$class = 'Field\\' . ucfirst($field['gtf_field_type']) . 'Field';
$this->_fields[$key] = $this->tracker->createTrackClass($class, $this->_trackId, $key, $field);
$this->_trackFields[$key] = $field;
}
// \MUtil_Echo::track($this->_trackFields);
} else {
$this->exists = false;
}
}
} | Loads the $this->_trackFields array, if not already there | entailment |
public function calculateFieldsInfo(array $data)
{
if (! $this->exists) {
return null;
}
$output = array();
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
if ($field->toTrackInfo()) {
$inVal = isset($data[$key]) ? $data[$key] : null;
$outVal = $field->calculateFieldInfo($inVal, $data);
if ($outVal && $field->isLabelInTrackInfo()) {
$label = $field->getLabel();
if ($label) {
$output[] = $label;
}
}
if (is_array($outVal)) {
$output = array_merge($output, array_filter($outVal));
} elseif ($outVal || ($outVal == 0)) {
$output[] = $outVal;
}
}
}
}
return substr(trim(implode(' ', $output)), 0, $this->maxTrackInfoChars);
} | Calculate the content for the track info field using the other fields
@param array $data The field values
@return string The description to save as track_info | entailment |
public function getDataModelDependency()
{
if (! $this->exists) {
return null;
}
$dependency = new FieldDataDependency();
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
$dependsOn = $field->getDataModelDependsOn();
if ($field->hasDataModelDependencies()) {
$dependency->addField($field);
}
}
}
if ($dependency->getFieldCount()) {
return $dependency;
} else {
return null;
}
} | Get model dependency that changes model settings for each row when loaded
@return \MUtil\Model\Dependency\DependencyInterface or null | entailment |
public function getDataModelSettings()
{
if (! $this->exists) {
return array();
}
$fieldSettings = array();
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
$fieldSettings[$key] = $field->getDataModelSettings();
}
}
return $fieldSettings;
} | Get a big array with model settings for fields in a track
@return array fieldname => array(settings) | entailment |
public function getDataStorageModel()
{
if (! $this->_dataModel instanceof FieldDataModel) {
$this->_dataModel = $this->tracker->createTrackClass('Model\\FieldDataModel');
}
return $this->_dataModel;
} | Get the storage model for field values
@return \Gems\Tracker\Model\FieldDataModel | entailment |
public function getFieldByCode($code)
{
foreach ($this->_fields as $field) {
if ($field instanceof FieldInterface) {
if ($field->getCode() == $code) {
return $field;
}
}
}
return null;
} | Get a specific field by field code
@param string $code
@return \Gems\Tracker\Field\FieldInterface | entailment |
public function getFieldByOrder($order)
{
foreach ($this->_fields as $field) {
if ($field instanceof FieldInterface) {
if ($field->getOrder() == $order) {
return $field;
}
}
}
return null;
} | Get a specific field by field order
@param int $order
@return \Gems\Tracker\Field\FieldInterface | entailment |
public function getFieldCodes()
{
$fields = array();
foreach ($this->_trackFields as $key => $field) {
$fields[$key] = $field['gtf_field_code'];
}
return $fields;
} | Returns an array of the fields in this track
key / value are id / code
@return array fieldid => fieldcode | entailment |
public function getFieldDefaults()
{
$output = array();
foreach ($this->_trackFields as $key => $field) {
$output[$key] = $field['gtf_field_default'];
}
return $output;
} | Returns an array of the fields in this track
key / value are id / code
@return array fieldid => fieldcode | entailment |
public function getFieldNames()
{
$fields = array();
foreach ($this->_trackFields as $key => $field) {
$fields[$key] = $field['gtf_field_name'];
}
return $fields;
} | Returns an array of the fields in this track
key / value are id / field name
@return array fieldid => fieldcode | entailment |
public function getFieldsDataFor($respTrackId)
{
if (! $this->_fields) {
return array();
}
// Set the default values to empty as we currently do not store default values for fields
$output = array_fill_keys(array_keys($this->_fields), null);
if (! $respTrackId) {
return $output;
}
$model = $this->getDataStorageModel();
$rows = $model->load(array('gr2t2f_id_respondent_track' => $respTrackId));
if ($rows) {
foreach ($rows as $row) {
$key = self::makeKey($row['sub'], $row['gr2t2f_id_field']);
if (isset($this->_fields[$key]) && ($this->_fields[$key] instanceof FieldInterface)) {
$value = $this->_fields[$key]->onFieldDataLoad($row['gr2t2f_value'], $output, $respTrackId);
} else {
$value = $row['gr2t2f_value']; // Should not occur
}
$output[$key] = $value;
}
}
// \MUtil_Echo::track($output);
return $output;
} | Returns the field data for the respondent track id.
@param int $respTrackId Gems respondent track id or null when new
@return array of the existing field values for this respondent track | entailment |
protected function getFieldsOfType($fieldType, $element)
{
$output = array();
$fieldArray = (array) $fieldType;
foreach ($this->_trackFields as $key => $field) {
if (in_array($field['gtf_field_type'], $fieldArray)) {
$output[$key] = $field[$element];
}
}
return $output;
} | Returns an array name => $element of all the fields of the type specified
@param string|array $fieldType One or more field types
@return array name => $element | entailment |
public function getMaintenanceModel($detailed = false, $action = 'index')
{
if (isset($this->_maintenanceModels[$action])) {
return $this->_maintenanceModels[$action];
}
$model = $this->tracker->createTrackClass('Model\\FieldMaintenanceModel');
if ($detailed) {
if (('edit' === $action) || ('create' === $action)) {
$model->applyEditSettings();
if ('create' === $action) {
$model->set('gtf_id_track', 'default', $this->_trackId);
// Set the default round order
// Load last row
$row = $model->loadFirst(
array('gtf_id_track' => $this->_trackId),
array('gtf_id_order' => SORT_DESC),
false // Make sure this does not trigger type dependency
);
if ($row && isset($row['gtf_id_order'])) {
$newOrder = $row['gtf_id_order'] + 10;
$model->set('gtf_id_order', 'default', $newOrder);
}
}
} else {
$model->applyDetailSettings();
}
} else {
$model->applyBrowseSettings();
}
$this->_maintenanceModels[$action] = $model;
return $model;
} | Returns a model that can be used to retrieve or save the field definitions for the track editor.
@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 \Gems\Tracker\Model\FieldMaintenanceModel | entailment |
public function hasAppointmentFields()
{
if (null === $this->_hasAppointmentFields) {
$this->_hasAppointmentFields = false;
foreach ($this->_trackFields as $field) {
if (self::TYPE_APPOINTMENT == $field['gtf_field_type']) {
$this->_hasAppointmentFields = true;
break;
}
}
}
return $this->_hasAppointmentFields;
} | True when this track contains appointment fields
@return boolean | entailment |
public function isAppointment($fieldName)
{
return isset($this->_trackFields[$fieldName]) &&
(self::TYPE_APPOINTMENT == $this->_trackFields[$fieldName]['gtf_field_type']);
} | Is the field an appointment type
@param string $fieldName
@return boolean | entailment |
public function processBeforeSave(array $fieldData, array $trackData)
{
$this->changed = false;
if (! $this->exists) {
return null;
}
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
$field->calculationStart($trackData);
}
}
$output = array();
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
$inVal = isset($fieldData[$key]) ? $fieldData[$key] : null;
$outVal = $field->calculateFieldValue($inVal, $fieldData, $trackData);
if (is_array($outVal) || is_array($inVal)) {
if (is_array($outVal) && is_array($inVal)) {
$changedNow = ($outVal != $inVal);
} else {
$changedNow = true;
}
} else {
$changedNow = ((string) $inVal !== (string) $outVal);
}
$this->changed = $this->changed || $changedNow;
$fieldData[$key] = $outVal; // Make sure the new value is available to the next field
$output[$key] = $outVal;
}
}
return $output;
} | Processes the values and and changes them as required
@param array $fieldData The field values
@param array $trackData The currently available track data (track id may be empty)
@return array The processed data | entailment |
public function saveFields($respTrackId, array $fieldData)
{
$saves = array();
foreach ($this->_fields as $key => $field) {
if ($field instanceof FieldInterface) {
if (array_key_exists($key, $fieldData)) {
$inVal = $fieldData[$key];
} else {
// There is no value do not save
continue;
}
$saveVal = $field->onFieldDataSave($inVal, $fieldData);
$saves[] = array(
'sub' => $field->getFieldSub(),
'gr2t2f_id_respondent_track' => $respTrackId,
'gr2t2f_id_field' => $field->getFieldId(),
'gr2t2f_value' => $saveVal,
);
}
}
$model = $this->getDataStorageModel();
$model->saveAll($saves);
return $model->getChanged();
} | Saves the field data for the respondent track id.
@param int $respTrackId Gems respondent track id
@param array $fieldData The values to save, only the key is used, not the code
@return int The number of changed fields | entailment |
public static function splitKey($key)
{
if (strpos($key, self::FIELD_KEY_SEPARATOR) === false) {
return null;
}
list($sub, $fieldId) = explode(self::FIELD_KEY_SEPARATOR, $key, 2);
return array('sub' => $sub, 'gtf_id_field' => $fieldId);
} | Split an external field key in component parts
@param string $sub
@param int $fieldId
@return array 'sub' => suIdb, 'gtf_id_field; => fieldId | entailment |
protected function addFormElements(\Zend_Form $form)
{
if ($this->user->hasEmailAddress()) {
$order = count($form->getElements())-1;
$createElement = new \MUtil_Form_Element_FakeSubmit('create_account');
$createElement->setLabel($this->_('Create account mail'))
->setAttrib('class', 'button')
->setOrder($order++);
$form->addElement($createElement);
$resetElement = new \MUtil_Form_Element_FakeSubmit('reset_password');
$resetElement->setLabel($this->_('Reset password mail'))
->setAttrib('class', 'button')
->setOrder($order++);
$form->addElement($resetElement);
}
parent::addFormElements($form);
} | Add the elements to the form
@param \Zend_Form $form | entailment |
protected function onFakeSubmit()
{
if (isset($this->formData['create_account']) && $this->formData['create_account']) {
$mail = $this->loader->getMailLoader()->getMailer('staffPassword', $this->user->getUserId());
if ($mail->setCreateAccountTemplate()) {
$mail->send();
$this->addMessage($this->_('Create account mail sent'));
$this->setAfterSaveRoute();
} else {
$this->addMessage($this->_('No default Create Account mail template set in organization or project'));
}
return;
}
if (isset($this->formData['reset_password']) && $this->formData['reset_password']) {
$mail = $this->loader->getMailLoader()->getMailer('staffPassword', $this->user->getUserId());
if ($mail->setResetPasswordTemplate()) {
$mail->send();
$this->addMessage($this->_('Reset password mail sent'));
$this->setAfterSaveRoute();
} else {
$this->addMessage($this->_('No default Reset Password mail template set in organization or project'));
}
}
} | Hook that allows actions when the form is submitted, but it was not the submit button that was checked
When not rerouted, the form will be populated afterwards | entailment |
public function getMessages()
{
if ($this->_authResult->isValid()) {
return array();
} else {
$messages = $this->_authResult->getMessages();
switch (count($messages)) {
case 0:
return array($this->_message);
case 1:
switch (reset($messages)) {
case 'Supplied credential is invalid.':
case 'Authentication failed.':
return array($this->_message);
// default:
// Intentional fall through
}
default:
// Intentional fall through
return $messages;
}
}
} | Returns an array of messages that explain why the most recent isValid()
call returned false. The array keys are validation failure message identifiers,
and the array values are the corresponding human-readable message strings.
If isValid() was never called or if the most recent isValid() call
returned true, then this method returns an empty array.
@return array | entailment |
public function render($text)
{
$text = $this->config->onStart($text);
$linesIterator = new \ArrayIterator(preg_split("/\015\012|\015|\012/", $text)); // we split the text at all line feeds
$this->documentGenerator->clear();
$this->errors = array();
while ($linesIterator->valid()) {
$line = $linesIterator->current();
if ($line != '') {
$blockGen = $this->parseBlock($linesIterator, $line, null);
if (is_object($blockGen)) {
$this->documentGenerator->addBlock($blockGen);
continue;
}
}
// no block found, we use a default block
if (trim($line) == '') {
$blockGenerator = new Generator\SingleLineBlock($this->documentGenerator->getConfig());
} else {
$inline = $this->inlineParser->parse($line);
$blockGenerator = $this->documentGenerator->getDefaultBlock($inline);
if (!$blockGenerator) {
$blockGenerator = new Generator\SingleLineBlock($this->documentGenerator->getConfig());
$blockGenerator->setLineAsString($inline);
}
}
$this->documentGenerator->addBlock($blockGenerator);
$this->nextLine($linesIterator);
}
$result = $this->documentGenerator->generate();
if ($this->documentGenerator->getConfig()->generateHeaderFooter) {
$result = $this->documentGenerator->generateHeader()
.$result
.$this->documentGenerator->generateFooter();
}
return $this->config->onParse($result);
} | Main method to call to convert a wiki text into an other format, according to the
rules given to the constructor.
@param string $text The wiki text to convert.
@return string The converted text. | entailment |
public function isValid($value, $context = array())
{
$result = true;
$ranges = explode('|', $value);
foreach ($ranges as $range) {
if (($sep = strpos($range, '-')) !== false) {
$range = IpFactory::rangeFromBoundaries(substr($range, 0, $sep), substr($range, $sep + 1));
} else {
$range = IpFactory::rangeFromString($range);
}
if (! $range instanceof RangeInterface) {
$result = false;
break;
}
}
if (!$result) {
$this->_error(self::ERROR_INVALID_IP);
}
return $result;
} | 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
@return boolean
@todo ip2long is broken on Windows, find a replacement | entailment |
public function getPanel()
{
$linebreak = $this->getLinebreak();
$included = $this->_getIncludedFiles();
$html = '<h4>' . count($included).' files included worth ';
$size = 0;
foreach ($included as $file) {
$size += filesize($file);
}
$html .= round($size/1024, 1).'K</h4>';
// $html .= 'Basepath: ' . $this->_basePath .$linebreak;
$libraryFiles = array();
foreach ($this->_library as $key => $value) {
if ('' != $value) {
$libraryFiles[$key] = '<h4>' . $value . ' Files</h4>';
}
}
$html .= '<h4>Application Files</h4>';
foreach ($included as $file) {
$file = str_replace($this->_basePath, '', $file);
$filePaths = explode(DIRECTORY_SEPARATOR, $file);
$inUserLib = false;
foreach ($this->_library as $key => $library) {
if ('' != $library && in_array($library, $filePaths)) {
$libraryFiles[$key] .= $file . $linebreak;
$inUserLib = TRUE;
}
}
if (!$inUserLib) {
$html .= $file .$linebreak;
}
}
$html .= implode('', $libraryFiles);
return $html;
} | Gets content panel for the Debugbar
@return string | entailment |
protected function _getIncludedFiles()
{
if (null !== $this->_includedFiles) {
return $this->_includedFiles;
}
$this->_includedFiles = get_included_files();
sort($this->_includedFiles);
return $this->_includedFiles;
} | Gets included files
@return array | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$bridge->addHidden('grl_id_role');
$bridge->addText('grl_name');
$bridge->addText('grl_description');
$roles = $this->acl->getRoles();
if ($roles) {
$possibleParents = array_combine($roles, $roles);
} else {
$possibleParents = array();
}
if (isset($this->formData['grl_parents']) && $this->formData['grl_parents']) {
$this->formData['grl_parents'] = array_combine($this->formData['grl_parents'], $this->formData['grl_parents']);
} else {
$this->formData['grl_parents'] = array();
}
// Don't allow master, nologin or itself as parents
unset($possibleParents['master']);
unset($possibleParents['nologin']);
$disabled = array();
if (isset($this->formData['grl_name'])) {
foreach ($possibleParents as $parent) {
if ($this->acl->hasRole($this->formData['grl_name']) && $this->acl->inheritsRole($parent, $this->formData['grl_name'])) {
$disabled[] = $parent;
$possibleParents[$parent] .= ' ' .
\MUtil_Html::create('small', $this->_('child of current role'), $this->view);
unset($this->formData['grl_parents'][$parent]);
} else {
foreach ($this->formData['grl_parents'] as $p2) {
if ($this->acl->hasRole($p2) && $this->acl->inheritsRole($p2, $parent)) {
$disabled[] = $parent;
$possibleParents[$parent] .= ' ' . \MUtil_Html::create(
'small',
\MUtil_Html::raw(sprintf(
$this->_('inherited from %s'),
\MUtil_Html::create('em', $p2, $this->view)
)),
$this->view);
$this->formData['grl_parents'][$parent] = $parent;
}
}
}
}
$disabled[] = $this->formData['grl_name'];
if (isset($possibleParents[$this->formData['grl_name']])) {
$possibleParents[$this->formData['grl_name']] .= ' ' .
\MUtil_Html::create('small', $this->_('this role'), $this->view);
}
}
$bridge->addMultiCheckbox('grl_parents', 'multiOptions', $possibleParents,
'disable', $disabled,
'escape', false,
'onchange', 'this.form.submit();',
'required', false
);
$allPrivileges = $this->usedPrivileges;
$rolePrivileges = $this->acl->getRolePrivileges();
if (isset($this->formData['grl_parents']) && $this->formData['grl_parents']) {
$inherited = $this->getInheritedPrivileges($this->formData['grl_parents']);
$privileges = array_diff_key($allPrivileges, $inherited);
$inheritedPrivileges = array_intersect_key($allPrivileges, $inherited);
} else {
$privileges = $allPrivileges;
$inheritedPrivileges = false;
}
$checkbox = $bridge->addMultiCheckbox('grl_privileges', 'multiOptions', $privileges, 'required', false);
$checkbox->setAttrib('escape', false); //Don't use escaping, so the line breaks work
if ($inheritedPrivileges) {
$checkbox = $bridge->addMultiCheckbox(
'inherited',
'label', $this->_('Inherited'),
'multiOptions', $inheritedPrivileges,
'required', false,
'disabled', 'disabled'
);
$checkbox->setAttrib('escape', false); //Don't use escaping, so the line breaks work
$checkbox->setValue(array_keys($inheritedPrivileges)); //To check the boxes
}
$bridge->getForm()->setDisableTranslator(true);
} | 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 beforeSave()
{
if (isset($this->formData['grl_parents']) && (! is_array($this->formData['grl_parents']))) {
$this->formData['grl_parents'] = explode(',', $this->formData['grl_parents']);
}
if (isset($this->formData['grl_parents']) && is_array($this->formData['grl_parents'])) {
$this->formData['grl_parents'] = implode(
',',
\Gems_Roles::getInstance()->translateToRoleIds($this->formData['grl_parents'])
);
}
//Always add nologin privilege to 'nologin' role
if (isset($this->formData['grl_name']) && $this->formData['grl_name'] == 'nologin') {
$this->formData['grl_privileges'][] = 'pr.nologin';
} elseif (isset($this->formData['grl_name']) && $this->formData['grl_name'] !== 'nologin') {
//Assign islogin to all other roles
$this->formData['grl_privileges'][] = 'pr.islogin';
}
if (isset($this->formData['grl_privileges'])) {
$this->formData['grl_privileges'] = implode(',', $this->formData['grl_privileges']);
}
} | Perform some actions to the data before it is saved to the database | entailment |
protected function loadFormData()
{
// \MUtil_Echo::track(file_get_contents('php://input'));
parent::loadFormData();
// \MUtil_Echo::track($this->formData);
// Sometimes these settings sneek in when changing the parents of a role
foreach(['pr.nologin', 'pr.islogin'] as $val) {
$key = array_search($val, $this->formData['grl_privileges']);
if (false !== $key) {
unset($this->formData['grl_privileges'][$key]);
}
}
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
public function getSqlAppointmentsWhere()
{
$where = $this->getSqlEpisodeWhere();
if (($where == parent::NO_MATCH_SQL) || ($where == parent::MATCH_ALL_SQL)) {
return $where;
}
return sprintf(
"gap_id_episode IN (SELECT gec_episode_of_care_id FROM gems__episodes_of_care WHERE %s)",
$where
);
} | Generate a where statement to filter an appointment model
@return string | entailment |
public function matchAppointment(\Gems_Agenda_Appointment $appointment)
{
$episode = $appointment->getEpisode();
if (! ($episode && $episode->exists)) {
return false;
}
return $this->matchEpisode($episode);
} | Check a filter for a match
@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean | entailment |
protected function getExportModel()
{
$model = parent::getExportModel();
$model->del('parents', 'formatFunction');
$model->del('allowed', 'formatFunction');
$model->del('inherited', 'formatFunction');
return $model;
} | Get the model for export and have the option to change it before using for export
@return | entailment |
protected function getRoles()
{
$roles = [];
foreach ($this->acl->getRolePrivileges() as $role => $privileges) {
$roles[$role]['role'] = $role;
$roles[$role]['parents'] = $privileges[\MUtil_Acl::PARENTS] ? implode(', ', $privileges[\MUtil_Acl::PARENTS]) : null;
$roles[$role]['allowed'] = $privileges[\Zend_Acl::TYPE_ALLOW] ? implode(', ', $privileges[\Zend_Acl::TYPE_ALLOW]) : null;
//$roles[$role]['denied'] = $privileges[\Zend_Acl::TYPE_DENY] ? implode(', ', $privileges[\Zend_Acl::TYPE_DENY]) : null;
$roles[$role]['inherited'] = $privileges[\MUtil_Acl::INHERITED][\Zend_Acl::TYPE_ALLOW] ? implode(', ', $privileges[\MUtil_Acl::INHERITED][\Zend_Acl::TYPE_ALLOW]) : null;
//$roles[$role]['parent-denied'] = $privileges[\MUtil_Acl::INHERITED][\Zend_Acl::TYPE_DENY] ? implode(', ', $privileges[\MUtil_Acl::INHERITED][\Zend_Acl::TYPE_DENY]) : null;
}
ksort($roles);
return $roles;
} | Get list of privileges, their menu options and which role is allowed or denied this specific privilege
@return array list of roles | entailment |
public function execute($sourceId = null, $command = null)
{
$batch = $this->getBatch();
$params = array_slice(func_get_args(), 2);
$source = $this->loader->getTracker()->getSource($sourceId);
if ($messages = call_user_func_array(array($source, $command), $params)) {
foreach ($messages as $message) {
$batch->addMessage($command . ': ' . $message);
}
}
} | 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 afterRegistry()
{
parent::afterRegistry();
$this->maskStore = $this->loader->getUserMaskStore();
$this->maskStore->setMaskSettings($this->_data['ggp_mask_settings']);
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function isTwoFactorRequired($ipAddress, $hasKey)
{
// \MUtil_Echo::track($ipAddress, $hasKey, $this->_get('ggp_2factor_set'), $this->_get('ggp_2factor_not_set'));
if ($hasKey) {
switch ($this->_get('ggp_2factor_set')) {
case self::TWO_FACTOR_SET_REQUIRED:
return true;
case self::TWO_FACTOR_SET_OUTSIDE_ONLY:
// Required when not in range
return ! $this->util->isAllowedIP($ipAddress, $this->_get('ggp_no_2factor_ip_ranges'));
}
} else {
switch ($this->_get('ggp_2factor_not_set')) {
case self::NO_TWO_FACTOR_INSIDE_ONLY:
// Required even when not set when not in range
return ! $this->util->isAllowedIP($ipAddress, $this->_get('ggp_no_2factor_ip_ranges'));
}
}
return false;
} | Should a user be authorized using two factor authentication?
@param string $ipAddress
@param boolean $hasKey
@return boolean | entailment |
protected function loadData($id)
{
try {
$sql = "SELECT * FROM gems__groups WHERE ggp_id_group = ? LIMIT 1";
$data = $this->db->fetchRow($sql, intval($id));
} catch (\Exception $e) {
$data = false;
}
if (! $data) {
$data = $this->_noGroup;
}
// Translate numeric role id
if (is_array($data)) {
if (intval($data['ggp_role'])) {
$data['ggp_role'] = \Gems_Roles::getInstance()->translateToRoleName($data['ggp_role']);
}
if (! isset($data['ggp_mask_settings'])) {
$data['ggp_mask_settings'] = array();
} elseif (! is_array($data['ggp_mask_settings'])) {
$data['ggp_mask_settings'] = (array) json_decode($data['ggp_mask_settings']);
}
// \MUtil_Echo::track($data['ggp_mask_settings']);
}
return $data;
} | Load the data when the cache is empty.
@param mixed $id
@return array The array of data values | entailment |
protected function _getConditionClass($conditionType)
{
if (isset($this->_conditionClasses[$conditionType])) {
return $this->_conditionClasses[$conditionType];
} else {
throw new Gems_Exception_Coding("No condition class exists for condition type '$conditionType'.");
}
} | Lookup condition class for an event type. This class or interface should at the very least
implement the ConditionInterface.
@see ConditionInterface
@param string $conditionType The type (i.e. lookup directory) to find the associated class for
@return string Class/interface name associated with the type | entailment |
protected function _listConditions($conditionType)
{
$classType = $this->_getConditionClass($conditionType);
$paths = $this->_getConditionDirs($conditionType);
return $this->util->getTranslated()->getEmptyDropdownArray() + $this->listClasses($classType, $paths);
} | Returns a list of selectable conditions with an empty element as the first option.
@param string $conditionType The type (i.e. lookup directory with an associated class) of the conditions to list
@return ConditionInterface or more specific a $conditionClass type object | entailment |
protected function _loadCondition($conditionName, $conditionType)
{
$conditionClass = $this->_getConditionClass($conditionType);
if (! class_exists($conditionName, true)) {
throw new Gems_Exception_Coding("The condition '$conditionName' of type '$conditionType' can not be found");
}
$condition = new $conditionName();
if (! $condition instanceof $conditionClass) {
throw new Gems_Exception_Coding("The condition '$conditionName' of type '$conditionType' is not an instance of '$conditionClass'.");
}
if ($condition instanceof MUtil_Registry_TargetInterface) {
$this->applySource($condition);
}
return $condition;
} | Loads and initiates a condition class and returns the class (without triggering the condition itself).
@param string $conditionName The class name of the individual event to load
@param string $conditionType The type (i.e. lookup directory with an associated class) of the event
@return ConditionInterface or more specific a $eventClass type object | entailment |
public function getTokenTableStructure()
{
$tableName = $this->_getTokenTableName();
$table = new \Zend_DB_Table(array('name' => $tableName, 'db' => $this->lsDb));
$info = $table->info();
$metaData = $info['metadata'];
return $metaData;
} | Get the table structure of the token table
@return array List of Zend_DB Table metadata | entailment |
protected function addBrowseTableColumns(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$bridge->gr2o_id_organization;
if ($menuItem = $this->menu->find(array('controller' => 'appointment', 'action' => 'show', 'allowed' => true))) {
$appButton = $menuItem->toActionLink($this->request, $bridge, $this->_('Show appointment'));
} else {
$appButton = null;
}
if ($menuItem = $this->menu->find(array('controller' => 'respondent', 'action' => 'show', 'allowed' => true))) {
$respButton = $menuItem->toActionLink($this->request, $bridge, $this->_('Show respondent'));
} else {
$respButton = null;
}
$br = \MUtil_Html::create('br');
$sp = \MUtil_Html::raw(' ');
$table = $bridge->getTable();
$table->appendAttrib('class', 'calendar');
$table->tbody()->getFirst(true)->appendAttrib('class', $bridge->row_class);
// Row with dates and patient data
$table->tr(array('onlyWhenChanged' => true, 'class' => 'date'));
$bridge->addSortable('date_only', $this->_('Date'), array('class' => 'date'))->colspan = 4;
// Row with dates and patient data
$bridge->tr(array('onlyWhenChanged' => true, 'class' => 'time middleAlign'));
$td = $bridge->addSortable('gap_admission_time');
$td->append(' ');
$td->img()->src = 'stopwatch.png';
$td->title = $bridge->date_only; // Add title, to make sure row displays when time is same as time for previous day
$bridge->addSortable('gor_name');
$bridge->addSortable('glo_name')->colspan = 2;
$bridge->tr()->class = array('odd', $bridge->row_class);
$bridge->addColumn($appButton)->class = 'middleAlign';
$bridge->addMultiSort('gr2o_patient_nr', $sp, 'gap_subject', $br, 'name');
// $bridge->addColumn(array($bridge->gr2o_patient_nr, $br, $bridge->name));
$bridge->addMultiSort(array($this->_('With')), array(' '), 'gas_name', $br, 'gaa_name', array(' '), 'gapr_name');
// $bridge->addColumn(array($bridge->gaa_name, $br, $bridge->gapr_name));
$bridge->addColumn($respButton)->class = 'middleAlign rightAlign';
unset($table[\MUtil_Html_TableElement::THEAD]);
} | Adds columns from the model to the bridge that creates the browse table.
Overrule this function to add different columns to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
protected function createModel()
{
if (! $this->model instanceof \Gems_Model_AppointmentModel) {
$this->model = $this->loader->getModels()->createAppointmentModel();
$this->model->applyBrowseSettings();
}
$this->model->addColumn(new \Zend_Db_Expr("CONVERT(gap_admission_time, DATE)"), 'date_only');
$this->model->set('date_only', 'dateFormat',
\Zend_Date::WEEKDAY . ' ' . \Zend_Date::DAY_SHORT . ' ' .
\Zend_Date::MONTH_NAME . ' ' . \Zend_Date::YEAR,
'storageFormat', 'YYYY-MM-DD'
);
$this->model->set('gap_admission_time', 'label', $this->_('Time'),
'dateFormat', 'HH:mm');
$this->model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'));
\Gems_Model_RespondentModel::addNameToModel($this->model, $this->_('Name'));
// \MUtil_Model::$verbose = true;
return $this->model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
$data = $this->getModel()->loadFirst();
if ($data && isset($data['relpath'])) {
$nameForUser = $data['relpath'];
} else {
$nameForUser = $this->request->getParam(\MUtil_Model::REQUEST_ID, $this->_('unknown'));
}
if (! ($data && file_exists($data['fullpath']))) {
$this->addMessage(sprintf($this->_('The file "%s" does not exist on the server.'), $nameForUser));
return \MUtil_Html::create('pInfo', sprintf($this->_('The file "%s" could not be imported.'), $nameForUser));
}
// \MUtil_Echo::track($data);
return $this->_('Token');
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
protected function getTitle()
{
if ($this->formTitle) {
return $this->formTitle;
} elseif ($this->unDelete) {
return sprintf($this->_('Undelete %s!'), $this->getTopic());
} else {
return sprintf($this->_('Delete %s!'), $this->getTopic());
}
} | Retrieve the header title to display
@return string | entailment |
protected function initItems()
{
if (is_null($this->_items)) {
// Set the element classes
$model = $this->getModel();
$keys = $model->getKeys();
foreach ($model->getItemNames() as $item) {
if (($item == $this->receptionCodeItem) || in_array($item, $this->editItems)) {
continue;
}
if (in_array($item, $this->exhibitItems)) {
$model->set($item, 'elementClass', 'Exhibitor');
} elseif (in_array($item, $this->hiddenItems)) {
$model->set($item, 'elementClass', 'Hidden');
} elseif (in_array($item, $keys)) {
$model->set($item, 'elementClass', 'Hidden');
} else {
$model->set($item, 'elementClass', 'None');
}
}
$this->_items = array_merge(
$this->hiddenItems,
$this->exhibitItems,
array($this->receptionCodeItem),
$this->editItems
);
}
} | Initialize the _items variable to hold all items from the model | entailment |
protected function loadForm()
{
$model = $this->getModel();
$this->unDelete = $this->isUndeleting();
$receptionCodes = $this->getReceptionCodes();
// \MUtil_Echo::track($this->unDelete, $receptionCodes);
if (! $receptionCodes) {
throw new \Gems_Exception($this->_('No reception codes exist.'));
}
if ($this->unDelete) {
$label = $this->_('Restore code');
} else {
if ($this->unDeleteRight && (! $this->loader->getCurrentUser()->hasPrivilege($this->unDeleteRight))) {
$this->addMessage($this->_('Watch out! You yourself cannot undo this change!'));
}
$label = $this->_('Rejection code');
}
$model->set($this->receptionCodeItem, 'label', $label);
if ($this->fixedReceptionCode) {
if (! isset($receptionCodes[$this->fixedReceptionCode])) {
if ($this->fixedReceptionCode == $this->formData[$this->receptionCodeItem]) {
throw new \Gems_Exception($this->_('Already set to this reception code.'));
} else {
throw new \Gems_Exception(sprintf(
$this->_('Reception code %s does not exist.'),
$this->fixedReceptionCode
));
}
}
} elseif (count($receptionCodes) == 1) {
reset($receptionCodes);
$this->fixedReceptionCode = key($receptionCodes);
}
if ($this->fixedReceptionCode) {
$model->set($this->receptionCodeItem,
'elementClass', 'Exhibitor',
'multiOptions', $receptionCodes
);
$this->formData[$this->receptionCodeItem] = $this->fixedReceptionCode;
} else {
$model->set($this->receptionCodeItem,
'elementClass', 'Select',
'multiOptions', array('' => '') + $receptionCodes,
'required', true,
'size', min(7, max(3, count($receptionCodes) + 2))
);
if (! isset($this->formData[$this->receptionCodeItem], $receptionCodes[$this->formData[$this->receptionCodeItem]])) {
$this->formData[$this->receptionCodeItem] = '';
}
}
$this->saveLabel = $this->getTitle();
parent::loadForm();
} | Makes sure there is a form. | entailment |
protected function saveData()
{
$this->beforeSave();
$changed = $this->setReceptionCode(
$this->formData[$this->receptionCodeItem],
$this->loader->getCurrentUser()->getUserId()
);
$this->afterSave($changed);
$this->accesslog->logChange($this->request, null, $this->formData);
} | Hook containing the actual save code.
Call's afterSave() for user interaction.
@see afterSave() | entailment |
protected function createModel()
{
$model = $this->token->getModel();
if ($model instanceof \Gems_Tracker_Model_StandardTokenModel) {
$model->addEditTracking();
if ($this->createData) {
$model->applyInsertionFormatting();
}
}
return $model;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
if ($this->tokenId) {
if ($this->token->exists) {
return parent::getHtmlOutput($view);
} else {
$this->addMessage(sprintf($this->_('Token %s not found.'), $this->tokenId));
}
} else {
$this->addMessage($this->_('No token specified.'));
}
} | 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 ($this->token) {
$this->tokenId = $this->token->getTokenId();
} elseif ($this->request) {
$this->tokenId = $this->request->getParam(\MUtil_Model::REQUEST_ID);
}
}
if ($this->tokenId && (! $this->token)) {
$this->token = $this->loader->getTracker()->getToken($this->tokenId);
}
// Output always true, returns an error message as html when anything is wrong
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 parse($line)
{
$this->error = false;
$this->currentTextLineContainer = $this->textLineContainers[$this->config->defaultTextLineContainer];
$firsttag = clone ($this->currentTextLineContainer->tag);
$this->str = preg_split($this->currentTextLineContainer->pattern, $line, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$this->end = count($this->str);
if ($this->end > 1) {
$pos = -1;
$this->_parse($firsttag, $pos);
return $firsttag->getContent();
} else {
$firsttag->addContentString($line);
return $firsttag->getContent();
}
} | Main function which parses a line of wiki content.
@param string $line a string containing wiki content, but without line feeds
@return \WikiRenderer\Generator\InlineGeneratorInterface the line transformed to the target content | entailment |
protected function _parse(\WikiRenderer\InlineTag $tag, $posstart)
{
$checkNextTag = true;
// we analyse each part of the string,
for ($i = $posstart + 1; $i < $this->end; ++$i) {
$t = &$this->str[$i];
// is it the escape char ?
if ($this->escapeChar != '' && $t === $this->escapeChar) {
if ($checkNextTag) {
$t = ''; // yes -> let's ignore the tag
$checkNextTag = false;
} else {
// if we are here, this is because the previous part was the escape char
$tag->addContentString($this->escapeChar);
if ($this->config->outputDoubleEscapeChar) {
$tag->addContentString($this->escapeChar);
}
$checkNextTag = true;
}
// no escape char, and previous token allowed us to
// take care of the current token, so let's processing it
} elseif ($checkNextTag) {
$result = $tag->isSupportedToken($t);
if ($result === $tag::END_TOKEN) {
return $i;
}
else if ($result !== false) {
// nothing
}
else if (!$tag->isOtherTagAllowed()) {
$tag->addContentString($t);
}
// is there a tag which begin something ?
elseif (isset($this->currentTextLineContainer->allowedTags[$t])) {
$newtag = clone $this->currentTextLineContainer->allowedTags[$t];
$i = $this->_parse($newtag, $i);
if ($i !== false) {
$tag->addContentGenerator($newtag->getWikiContent(), $newtag->getContent());
} else {
$i = $this->end;
$tag->addContentGenerator($newtag->getWikiContent(), $newtag->getBogusContent());
}
}
// is there a simple tag ?
elseif (isset($this->allSimpleTags[$t])) {
$tag->addContentGenerator($t, $this->allSimpleTags[$t]->getContent($this->documentGenerator, $t));
} else {
$tag->addContentString($t);
}
// previous token prevents us to process the current token, and
// indicated to ignore it, so let's ignore it.
} else {
if (isset($this->currentTextLineContainer->allowedTags[$t]) ||
isset($this->allSimpleTags[$t])
) {
if ($this->config->outputEscapeCharForTags) {
$tag->addContentString($this->escapeChar . $t);
} else {
$tag->addContentString($t);
}
} else {
if ($this->config->outputEscapeChar) {
$tag->addContentString($this->escapeChar . $t);
} else {
$tag->addContentString($t);
}
}
$checkNextTag = true;
}
}
if (!$checkNextTag &&
($this->config->outputEscapeChar ||
$this->config->outputEscapeCharAtEOL)
) {
$tag->addContentString($this->escapeChar);
}
if (!$tag->isLineContainer()) {
//we didn't find the ended tag, error
$this->error = true;
return false;
} else {
return $this->end;
}
} | Parser's core function.
@param \WikiRenderer\InlineTag $tag ???
@param int $posstart ???
@return int new position | entailment |
protected function addStepElementsFor(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model, $step)
{
$this->displayHeader($bridge, sprintf(
$this->_('%s track export. Step %d of %d.'),
$this->trackEngine->getTrackName(),
$step,
$this->getStepCount()), 'h2');
switch ($step) {
case 2:
$this->addStepExportCodes($bridge, $model);
break;
case 3:
$this->addStepGenerateExportFile($bridge, $model);
break;
default:
$this->addStepExportSettings($bridge, $model);
break;
}
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model
@param int $step The current step | entailment |
protected function addStepExportCodes(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$this->displayHeader($bridge, $this->_('Set the survey export codes'), 'h3');
$rounds = $this->formData['rounds'];
$surveyCodes = array();
foreach ($rounds as $roundId) {
$round = $this->trackEngine->getRound($roundId);
$sid = $round->getSurveyId();
$name = 'survey__' . $sid;
$surveyCodes[$name] = $name;
$model->set($name, 'validator', array('ValidateSurveyExportCode', true, array($sid, $this->db)));
}
$this->addItems($bridge, $surveyCodes);
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepExportSettings(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$this->displayHeader($bridge, $this->_('Select what to export'), 'h3');
$this->addItems($bridge, 'orgs', 'fields', 'rounds');
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function addStepGenerateExportFile(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
// Things go really wrong (at the session level) if we run this code
// while the finish button was pressed
if ($this->isFinishedClicked()) {
return;
}
$this->displayHeader($bridge, $this->_('Creating the export file'), 'h3');
$this->nextDisabled = true;
$batch = $this->getExportBatch();
$form = $bridge->getForm();
$batch->setFormId($form->getId());
$batch->autoStart = true;
// \MUtil_Registry_Source::$verbose = true;
if ($batch->run($this->request)) {
exit;
}
$element = $form->createElement('html', $batch->getId());
if ($batch->isFinished()) {
$this->nextDisabled = $batch->getCounter('export_errors');
$batch->autoStart = false;
// Keep the filename after $batch->getMessages(true) cleared the previous
$downloadName = \MUtil_File::cleanupName($this->trackEngine->getTrackName()) . '.track.txt';
$localFilename = $batch->getSessionVariable('filename');
$this->addMessage($batch->getMessages(true));
$batch->setSessionVariable('downloadname', $downloadName);
$batch->setSessionVariable('filename', $localFilename);
// Log Export
$data = $this->formData;
// Remove unuseful data
unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId]);
// Add useful data
$data['localfile'] = '...' . substr($localFilename, -30);
$data['downloadname'] = $downloadName;
ksort($data);
$this->accesslog->logChange($this->request, null, array_filter($data));
if ($this->nextDisabled) {
$element->pInfo($this->_('Export errors occurred.'));
} else {
$p = $element->pInfo($this->_('Export file generated.'), ' ');
$p->sprintf(
$this->plural(
'Click here if the download does not start automatically in %d second:',
'Click here if the download does not start automatically in %d seconds:',
$this->downloadWaitSeconds
),
$this->downloadWaitSeconds
);
$p->append(' ');
$href = new \MUtil_Html_HrefArrayAttribute(array('file' => 'go', $this->stepFieldName => 'download'));
$p->a(
$href,
$downloadName,
array('type' => 'application/download')
);
$metaContent = sprintf('%d;url=%s', $this->downloadWaitSeconds, $href->render($this->view));
$this->view->headMeta($metaContent, 'refresh', 'http-equiv');
}
} else {
$element->setValue($batch->getPanel($this->view, $batch->getProgressPercentage() . '%'));
}
$form->activateJQuery();
$form->addElement($element);
} | Add the elements from the model to the bridge for the current step
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function afterFormValidationFor($step)
{
if (2 == $step) {
$model = $this->getModel();
$saves = array();
foreach ($model->getCol('surveyId') as $name => $sid) {
if (isset($this->formData[$name]) && $this->formData[$name]) {
$saves[] = array('gsu_id_survey' => $sid, 'gsu_export_code' => $this->formData[$name]);
}
}
if ($saves) {
$sModel = new \MUtil_Model_TableModel('gems__surveys');
\Gems_Model::setChangeFieldsByPrefix($sModel, 'gus', $this->currentUser->getUserId());
$sModel->saveAll($saves);
$count = $sModel->getChanged();
if ($count == 0) {
$this->addMessage($this->_('No export code changed'));
} else {
$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array('surveys'));
$this->addMessage(sprintf(
$this->plural('%d export code changed', '%d export codes changed', $count),
$count
));
}
}
}
} | Overrule this function for any activities you want to take place
after the form has successfully been validated, but before any
buttons are processed.
@param int $step The current step | entailment |
protected function createForm($options = null)
{
if (\MUtil_Bootstrap::enabled()) {
if (!isset($options['class'])) {
$options['class'] = 'form-horizontal';
}
if (!isset($options['role'])) {
$options['role'] = 'form';
}
}
return new \Gems_Form($options);
} | Creates an empty form. Allows overruling in sub-classes.
@param mixed $options
@return \Zend_Form | entailment |
protected function createModel()
{
if (! $this->exportModel instanceof \MUtil_Model_ModelAbstract) {
$yesNo = $this->util->getTranslated()->getYesNo();
$model = new \MUtil_Model_SessionModel('export_for_' . $this->request->getControllerName());
$model->set('orgs', 'label', $this->_('Organization export'),
'default', 1,
'description', $this->_('Export the organizations for which the track is active'),
'multiOptions', $yesNo,
'required', true,
'elementClass', 'Checkbox');
$model->set('fields', 'label', $this->_('Field export'));
$fields = $this->trackEngine->getFieldNames();
if ($fields) {
$model->set('fields',
'default', array_keys($fields),
'description', $this->_('Check the fields to export'),
'elementClass', 'MultiCheckbox',
'multiOptions', $fields
);
} else {
$model->set('fields',
'elementClass', 'Exhibitor',
'value', $this->_('No fields to export')
);
}
$rounds = $this->trackEngine->getRoundDescriptions();
$model->set('rounds', 'label', $this->_('Round export'));
if ($rounds) {
$defaultRounds = array();
foreach ($rounds as $roundId => &$roundDescription) {
$round = $this->trackEngine->getRound($roundId);
if ($round && $round->isActive()) {
$defaultRounds[] = $roundId;
} else {
$roundDescription = sprintf($this->_('%s (inactive)'), $roundDescription);
}
$survey = $round->getSurvey();
if ($survey) {
$model->set('survey__' . $survey->getSurveyId(),
'label', $survey->getName(),
'default', $survey->getExportCode(),
'description', $this->_('A unique code indentifying this survey during track import'),
'maxlength', 64,
'required', true,
'size', 20,
'surveyId', $survey->getSurveyId()
);
}
}
$model->set('rounds',
'default', $defaultRounds,
'description', $this->_('Check the rounds to export'),
'elementClass', 'MultiCheckbox',
'multiOptions', $rounds
);
} else {
$model->set('rounds',
'elementClass', 'Exhibitor',
'value', $this->_('No rounds to export')
);
}
$this->exportModel = $model;
}
return $this->exportModel;
} | Creates the model
@return \MUtil_Model_ModelAbstract | entailment |
protected function downloadExportFile()
{
$this->view->layout()->disableLayout();
\Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender(true);
$batch = $this->getExportBatch(false);
$downloadName = $batch->getSessionVariable('downloadname');
$localFilename = $batch->getSessionVariable('filename');
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"$downloadName\"");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: cache"); // HTTP/1.0
readfile($localFilename);
exit();
} | Performs actual download
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function loadFormData()
{
$model = $this->getModel();
if ($this->request->isPost()) {
$this->formData = $model->loadPostData($this->request->getPost() + $this->formData, true);
} elseif ('download' == $this->request->getParam($this->stepFieldName)) {
$this->formData = $this->request->getParams();
$this->downloadExportFile();
} else {
// Assume that if formData is set it is the correct formData
if (! $this->formData) {
$this->formData = $model->loadNew();
}
}
// \MUtil_Echo::track($this->formData);
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function setAfterSaveRoute()
{
$filename = $this->getExportBatch(false)->getSessionVariable('filename');
if ($filename) {
// Now is a good moment to remove the temporary file
@unlink($filename);
}
// Default is just go to the index
if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
$this->afterSaveRouteUrl = array(
$this->request->getControllerKey() => $this->request->getControllerName(),
$this->request->getActionKey() => $this->routeAction,
\MUtil_Model::REQUEST_ID => $this->request->getParam(\MUtil_Model::REQUEST_ID),
);
}
return $this;
} | Set what to do when the form is 'finished'.
@return \Gems\Tracker\Snippets\ExportTrackSnippetAbstract | entailment |
public function validationApplies()
{
$return = true;
if ($criteria = $this->owner->validationLogicCriteria) {
$fields = $this->owner->rootFieldList();
if (eval($criteria->phpEvalString()) === false) {
throw new Exception("There is a syntax error in the constaint logic phpEvalString \"{$criteria->phpEvalString()}\"");
}
$return = eval('return ' . $criteria->phpEvalString());
}
return $return;
} | Checks to see if any ValidationLogicCriteria has been set and if so,
should the validation constraints still be applied
@return bool | entailment |
public function addTo($email, $name = '', $bounce = null)
{
if (is_null($bounce)) {
$bounce = $this->bounceCheck();
}
if ($bounce === true) {
$name = str_replace('@', ' at ', $email);
if (is_array($email)) {
$name = array_shift($name);
if (count($email) > 1) {
$name .= ' & ' . (count($email)-1) . ' addresses';
}
}
$email = $this->getFrom();
if (! $email) {
throw new \Gems_Exception_Coding('Adding bounce To address while From is not set.');
}
if (($this->currentUser instanceof \Gems_User_User) && $this->currentUser->hasEmailAddress()) {
$email = $this->currentUser->getEmailAddress();
}
}
return parent::addTo($email, $name);
} | Adds To-header and recipient, $email can be an array, or a single string address
@param string|array $email
@param string $name
@param boolean $bounce When true the e-mail is bounced to the from address, when omitted bounce is read from project settings
@return \Zend_Mail Provides fluent interface | entailment |
public function checkTransport($from)
{
if (! array_key_exists($from, self::$mailServers)) {
$sql = 'SELECT * FROM gems__mail_servers WHERE ? LIKE gms_from ORDER BY LENGTH(gms_from) DESC LIMIT 1';
// Always set cache, se we know when not to check for this row.
$serverData = $this->db->fetchRow($sql, $from);
// \MUtil_Echo::track($serverData);
if (isset($serverData['gms_server'])) {
$options = array();
if (isset($serverData['gms_user'], $serverData['gms_password'])) {
$options['auth'] = 'login';
$options['username'] = $serverData['gms_user'];
$options['password'] = $this->project->decrypt($serverData['gms_password']);
}
if (isset($serverData['gms_port'])) {
$options['port'] = $serverData['gms_port'];
}
if (isset($serverData['gms_ssl'])) {
switch ($serverData['gms_ssl']) {
case self::MAIL_SSL:
$options['ssl'] = 'ssl';
break;
case self::MAIL_TLS:
$options['ssl'] = 'tls';
break;
default:
// intentional fall through
}
}
self::$mailServers[$from] = new \Zend_Mail_Transport_Smtp($serverData['gms_server'], $options);
} else {
self::$mailServers[$from] = $this->getDefaultTransport();
}
}
return self::$mailServers[$from];
} | Returns \Zend_Mail_Transport_Abstract when something else than the default mail protocol should be used.
@staticvar array $mailServers
@param email address $from
@return \Zend_Mail_Transport_Abstract or null | entailment |
public function setTemplateStyle($style = null)
{
if (null == $style) {
$style = GEMS_PROJECT_NAME;
}
$this->setHtmlTemplateFile(APPLICATION_PATH . '/configs/email/' . $style . '.html');
return $this;
} | Set the template using style as basis
@param string $style
@return \MUtil_Mail (continuation pattern) | entailment |
public function delete($filter = true)
{
$this->trackUsage();
$rows = $this->load($filter);
if ($rows) {
foreach ($rows as $row) {
if (isset($row['gro_id_round'])) {
$roundId = $row['gro_id_round'];
if ($this->isDeleteable($roundId)) {
$this->db->delete('gems__rounds', $this->db->quoteInto('gro_id_round = ?', $roundId));
// Delete the round before anyone starts using it
$this->db->delete('gems__tokens', $this->db->quoteInto('gto_id_round = ?', $roundId));
} else {
$values['gro_id_round'] = $roundId;
$values['gro_active'] = 0;
$this->save($values);
}
$this->addChanged();
}
}
}
} | Delete items from the model
@param mixed $filter True to use the stored filter, array to specify a different filter
@return int The number of items deleted | entailment |
public function isDeleteable($roundId)
{
if (! $roundId) {
return true;
}
$sql = "SELECT gto_id_token FROM gems__tokens WHERE gto_id_round = ? AND gto_start_time IS NOT NULL";
return (boolean) ! $this->db->fetchOne($sql, $roundId);
} | Can this round be deleted as is?
@param int $roundId
@return boolean | entailment |
public function processTokenData(\Gems_Tracker_Token $token)
{
$result = var_export($token->getRawAnswers(), true);
\MUtil_Echo::r($result, $token->getTokenId());
return false;
} | Process the data and return the answers that should be changed.
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 addBrowseColumn1(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$br = \MUtil_Html::create('br');
if (isset($this->searchFilter['grc_success']) && (! $this->searchFilter['grc_success'])) {
$model->set('grc_description', 'label', $this->_('Rejection code'));
$column2 = 'grc_description';
} elseif (isset($this->searchFilter[\MUtil_Model::REQUEST_ID2])) {
$model->setIfExists('gr2o_opened', 'tableDisplay', 'small');
$column2 = 'gr2o_opened';
} else {
$column2 = 'gr2o_id_organization';
}
$bridge->addMultiSort('gr2o_patient_nr', $br, $column2);
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 addBrowseColumn2(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
if ($this->currentUser->isFieldMaskedWhole('name') && $this->currentUser->isFieldMaskedWhole('gr2o_email')) {
return;
}
$br = \MUtil_Html::create('br');
$model->setIfExists('gr2o_email', 'formatFunction', array('MUtil_Html_AElement', 'ifmail'));
$bridge->addMultiSort('name', $br, 'gr2o_email');
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 addBrowseColumn3(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$br = \MUtil_Html::create('br');
if ($model->hasAlias('gems__respondent2track')) {
$model->set('gtr_track_name', 'label', $this->_('Track'));
$model->set('gr2t_track_info', 'label', $this->_('Track description'));
$items = $this->findMenuItems('track', 'show-track');
$track = 'gtr_track_name';
if ($items) {
$menuItem = reset($items);
if ($menuItem instanceof \Gems_Menu_MenuAbstract) {
$href = $menuItem->toHRefAttribute(
$this->request,
$bridge,
array('gr2t_id_respondent_track' => $bridge->gr2t_id_respondent_track)
);
$track = array();
$track[0] = \MUtil_Lazy::iif($bridge->gr2t_id_respondent_track,
\MUtil_Html::create()->a(
$href,
$bridge->gtr_track_name,
array('onclick' => "event.cancelBubble = true;")
)
);
$track[1] = $bridge->createSortLink('gtr_track_name');
}
}
$bridge->addMultiSort($track, $br, 'gr2t_track_info');
} else {
$maskAddress = $this->currentUser->isFieldMaskedWhole('grs_address_1');
$maskZip = $this->currentUser->isFieldMaskedWhole('grs_zipcode');
$maskCity = $this->currentUser->isFieldMaskedWhole('grs_city');
if ($maskAddress && $maskZip && $maskCity) {
return;
}
if ($maskAddress && $maskCity) {
$bridge->addMultiSort('grs_zipcode');
return;
}
if ($maskAddress && $maskZip) {
$bridge->addMultiSort('grs_city');
return;
}
if ($maskAddress) {
$bridge->addMultiSort('grs_zipcode', $br, 'grs_city');
return;
}
$citysep = \MUtil_Html::raw(' ');
$bridge->addMultiSort('grs_address_1', $br, 'grs_zipcode', $citysep, 'grs_city');
}
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 addBrowseColumn4(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$maskBirthday = $this->currentUser->isFieldMaskedWhole('grs_birthday');
$maskPhone = $this->currentUser->isFieldMaskedWhole('grs_phone_1');
if ($maskBirthday && $maskPhone) {
return;
}
if ($maskPhone && ! $maskBirthday) {
$bridge->addMultiSort('grs_birthday');
return;
}
if (! $maskPhone) {
// Display separator and phone sign only if phone exist.
$phonesep = \MUtil_Html::raw('☏ '); // $bridge->itemIf($bridge->grs_phone_1, \MUtil_Html::raw('☏ '));
}
if ($maskBirthday) {
$bridge->addMultiSort($phonesep, 'grs_phone_1');
}
$br = \MUtil_Html::create('br');
$bridge->addMultiSort('grs_birthday', $br, $phonesep, 'grs_phone_1');
} | Add first columns (group) from the model to the bridge that creates the browse table.
You can actually add more than one column in this function, but just call all four functions
with the default columns in each
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 getRedirectRoute()
{
if (null !== $this->_redirectUrl) {
return $this->_redirectUrl;
}
$this->_redirectUrl = false;
// Retrieve these before the session is reset
$staticSession = \GemsEscort::getInstance()->getStaticSession();
if ($staticSession && is_array($staticSession->previousRequestParameters)) {
$url = $staticSession->previousRequestParameters;
$this->loginStatusTracker->destroySession();
$this->_redirectUrl = $url;
}
return $this->_redirectUrl;
} | When hasHtmlOutput() is false a snippet code user should check
for a redirectRoute. Otherwise the redirect calling render() will
execute the redirect.
This function should never return a value when the snippet does
not redirect.
Also when hasHtmlOutput() is true this function should not be
called.
@see \Zend_Controller_Action_Helper_Redirector
@return mixed Nothing or either an array or a string that is acceptable for Redector->gotoRoute() | entailment |
private function _($messageId, $locale = null)
{
if ($this->translate) {
return $this->translate->_($messageId, $locale);
}
return $messageId;
} | proxy for easy access to translations
@param string $messageId Translation string
@param string|\Zend_Locale $locale (optional) Locale/Language to use, identical with locale
identifier, @see \Zend_Locale for more information
@return string | entailment |
public function reset($id) {
$template = $this->load(array('name'=>$id));
$result = false;
if (count($template) == 1) {
if (unlink($this->_path . '/template-local.ini')) {
// Now force recompile
$this->_templates = false;
$this->_template = '';
$template = $this->load(array('name'=>$id));
$this->saveTemplate($id, $template[$id]);
$result = true;
}
}
return $result;
} | Reset a template to it's default values by deleteing template-local.ini
@param string $id
@return boolean true on success | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$setOnSave = \MUtil_Model_ModelAbstract::SAVE_TRANSFORMER;
$switches = $this->getTextSettings();
// Make sure the calculated name is saved
if (! isset($switches['gaf_calc_name'], $switches['gaf_calc_name'][$setOnSave])) {
$switches['gaf_calc_name'][$setOnSave] = array($this, 'calcultateAndCheckName');
}
// Make sure the class name is always saved
$className = $this->getFilterClass();
$switches['gaf_class'][$setOnSave] = $className;
// Check all the fields
for ($i = 1; $i <= $this->_fieldCount; $i++) {
$field = 'gaf_filter_text' . $i;
if (! isset($switches[$field])) {
$switches[$field] = array('label' => null, 'elementClass' => 'Hidden');
}
}
$this->addSwitches(array($className => $switches));
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function calcultateAndCheckName($value, $isNew = false, $name = null, array $context = array())
{
return substr($this->calcultateName($value, $isNew, $name, $context), 0, $this->_maxNameCalcLength);
} | A ModelAbstract->setOnSave() function that returns the input
date as a valid date.
@see \MUtil_Model_ModelAbstract
@param mixed $value The value being saved
@param boolean $isNew True when a new item is being saved
@param string $name The name of the current field
@param array $context Optional, the other values being saved
@return \Zend_Date | entailment |
protected function addFillerSelect(array &$elements, $data, $elementId = 'filler')
{
if (isset($data['gto_id_track']) && !empty($data['gto_id_track'])) {
$trackId = (int) $data['gto_id_track'];
} else {
$trackId = -1;
}
$sqlGroups = "SELECT DISTINCT ggp_name
FROM gems__groups INNER JOIN gems__surveys ON ggp_id_group = gsu_id_primary_group
INNER JOIN gems__rounds ON gsu_id_survey = gro_id_survey
INNER JOIN gems__tracks ON gro_id_track = gtr_id_track
WHERE ggp_group_active = 1 AND
gro_active=1 AND
gtr_active=1";
if ($trackId > -1) {
$sqlGroups .= $this->db->quoteInto(" AND gtr_id_track = ?", $trackId);
}
$sqlRelations = "SELECT DISTINCT gtf_field_name as ggp_name
FROM gems__track_fields
WHERE gtf_field_type = 'relation'";
if ($trackId > -1) {
$sqlRelations .= $this->db->quoteInto(" AND gtf_id_track = ?", $trackId);
}
$sql = "SELECT ggp_name, ggp_name as label FROM ("
. $sqlGroups .
" UNION ALL " .
$sqlRelations . "
) AS tmpTable
ORDER BY ggp_name";
$elements[$elementId] = $this->_createSelectElement($elementId, $sql, $this->_('(all fillers)'));
} | Add filler select to the elements array
@param array $elements
@param array $data
@param string $elementId | entailment |
protected function getAutoSearchElements(array $data)
{
$elements = parent::getAutoSearchElements($data);
if ($elements) {
$elements[] = null; // break into separate spans
}
if ($this->periodSelector) {
$dates = array(
'_gto_valid_from gto_valid_until'
=> $this->_('Is valid during'),
'-gto_valid_from gto_valid_until'
=> $this->_('Is valid within'),
'gto_valid_from' => $this->_('Valid from'),
'gto_valid_until' => $this->_('Valid until'),
'gto_mail_sent_date' => $this->_('E-Mailed on'),
'gto_completion_time' => $this->_('Completion date'),
);
$this->_addPeriodSelectors($elements, $dates);
$elements[] = null; // break into separate spans
}
$allowedOrgs = $this->getOrganizationList($data);
$elements['select_title'] = $this->_('Select:');
$elements['break1'] = \MUtil_Html::create('br');
// Select organization
if (count($allowedOrgs) > 1) {
$elements['gto_id_organization'] = $this->_createSelectElement(
'gto_id_organization',
$allowedOrgs,
$this->_('(all organizations)')
);
}
// Add track selection
if ($this->multiTracks) {
$elements['gto_id_track'] = $this->_createSelectElement(
'gto_id_track',
$this->getAllTrackTypes($allowedOrgs, $data),
$this->_('(all tracks)')
);
}
$elements['gto_round_description'] = $this->_createSelectElement(
'gto_round_description',
$this->getAllTrackRounds($allowedOrgs, $data),
$this->_('(all rounds)')
);
$elements['gto_id_survey'] = $this->_createSelectElement(
'gto_id_survey',
$this->getAllSurveys($allowedOrgs, $data),
$this->_('(all surveys)')
);
$elements['break2'] = \MUtil_Html::create('br');
// Add status selection
$elements['token_status'] = $this->_createSelectElement(
'token_status',
$this->getEveryStatus(),
$this->_('(every status)')
);
$elements['main_filter'] = $this->_createSelectElement(
'main_filter',
$this->getEveryOption(),
$this->_('(all actions)')
);
/*$elements['gsu_id_primary_group'] = $this->_createSelectElement(
'gsu_id_primary_group',
$this->getAllGroups($allowedOrgs, $data),
$this->_('(all fillers)')
);*/
$this->addFillerSelect($elements, $data, 'forgroup');
$elements['gr2t_created_by'] = $this->_createSelectElement(
'gr2t_created_by',
$this->getAllCreators($allowedOrgs, $data),
$this->_('(all staff)')
);
return $elements;
} | Returns a text element for autosearch. Can be overruled.
The form / html elements to search on. Elements can be grouped by inserting null's between them.
That creates a distinct group of elements
@param array $data The $form field values (can be usefull, but no need to set them)
@return array Of \Zend_Form_Element's or static tekst to add to the html or null for group breaks. | entailment |
protected function getEveryOption()
{
return [
'notmailed' => $this->_('Not emailed'),
'tomail' => $this->_('To email'),
'toremind' => $this->_('Needs reminder'),
'hasnomail' => $this->_('Missing email'),
'notmailable' => $this->_('Not allowed to email'),
];
} | The sued options
@return array | entailment |
public function errorAction()
{
$errors = $this->_getParam('error_handler');
$exception = $errors->exception;
$info = null;
$message = 'Application error';
$responseCode = 200;
switch ($errors->type) {
case \Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case \Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$responseCode = 404;
$message = 'Page not found';
break;
case \Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER:
if ($exception instanceof \Gems_Exception) {
$responseCode = $exception->getCode();
$message = $exception->getMessage();
$info = $exception->getInfo();
break;
}
// Intentional fall through
default:
$message = $exception->getMessage();
break;
}
\Gems_Log::getLogger()->logError($errors->exception, $errors->request);
if (\MUtil_Console::isConsole()) {
$this->_helper->viewRenderer->setNoRender(true);
echo $message . "\n\n";
if ($info) {
echo $info . "\n\n";
}
$next = $exception->getPrevious();
while ($next) {
echo ' ' . $next->getMessage() . "\n";
$next = $next->getPrevious();
}
echo $exception->getTraceAsString();
} else {
if ($responseCode) {
$this->getResponse()->setHttpResponseCode($responseCode);
}
$this->view->exception = $exception;
$this->view->message = $message;
$this->view->request = $errors->request;
if ($info) {
$this->view->info = $info;
}
}
} | Action for displaying an error, CLI as well as HTTP | entailment |
public function getChanges(array $context, $new)
{
$multi = explode(FieldAbstract::FIELD_SEP, $context['gtf_field_values']);
if (empty($context['gtf_field_values']) || empty($multi)) {
$multi = $this->util->getTranslated()->getYesNo();
}
$empty = [];
if ($context['gtf_required'] !== 1) {
$empty = $this->util->getTranslated()->getEmptyDropdownArray();
}
return array(
'gtf_field_values' => array(
'label' => $this->_('Values'),
'description' => $this->_('Separate multiple values with a vertical bar (|)'),
'description' => $this->_('Leave empty for Yes|No. Add two values as replacement. Separate multiple values with a vertical bar (|)'),
'elementClass' => 'Text',
'formatFunction' => array($this, 'formatValues'),
'minlength' => 3,// At least two single chars and a separator
),
'gtf_field_default' => array(
'label' => $this->_('Default'),
'description' => $this->_('Choose the default value'),
'elementClass' => 'Select',
'multiOptions' => $empty + array_combine(BooleanField::$keyValues, array_slice($multi,0,2)),
),
);
} | Returns the changes that must be made in an array consisting of
<code>
array(
field1 => array(setting1 => $value1, setting2 => $value2, ...),
field2 => array(setting3 => $value3, setting4 => $value4, ...),
</code>
By using [] array notation in the setting name you can append to existing
values.
Use the setting 'value' to change a value in the original data.
When a 'model' setting is set, the workings cascade.
@param array $context The current data this object is dependent on
@param boolean $new True when the item is a new record not yet saved
@return array name => array(setting => value) | entailment |
public function afterRegistry()
{
parent::afterRegistry();
$this->addColumn($this->util->getTokenData()->getStatusExpression(), 'status');
if (! $this->request instanceof \Zend_Controller_Request_Abstract) {
$this->request = \Zend_Controller_Front::getInstance()->getRequest();
}
} | Called after the check that all required registry values
have been set correctly has run.
@return void | entailment |
public function processChangedRespondent(\Gems_Tracker_Respondent $respondent)
{
$changes = 0;
$tracker = $this->loader->getTracker();
$respTracks = $tracker->getRespondentTracks($respondent->getId(), $respondent->getOrganizationId());
$userId = $this->currentUser->getUserId();
$tracksData = $this->db->fetchAll("SELECT * FROM gems__tracks
WHERE gtr_active = 1 AND
CONCAT(' ', gtr_code, ' ') LIKE '% " . $this->trackCode . " %' AND
gtr_organizations LIKE '%|" . $respondent->getOrganizationId() . "|%'
ORDER BY gtr_track_name");
// \MUtil_Echo::track($tracksData);
$changes = false;
foreach ($tracksData as $trackData) {
$trackEngine = $tracker->getTrackEngine($trackData);
if ($trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {
// \MUtil_Echo::track($trackEngine->getTrackCode(), count($respTracks));
$create = true;
foreach($respTracks as $respondentTrack) {
if (($respondentTrack instanceof \Gems_Tracker_RespondentTrack) &&
($respondentTrack->getTrackId() == $trackEngine->getTrackId())) {
$create = false;
break;
}
}
// \MUtil_Echo::track($create);
if ($create) {
$changes = true;
$tracker->createRespondentTrack(
$respondent->getId(),
$respondent->getOrganizationId(),
$trackEngine->getTrackId(),
$userId
);
}
}
}
return $changes;
} | Process the respondent and return true when data has changed.
The event has to handle the actual storage of the changes.
@param \Gems_Tracker_Respondent $respondent
@param int $userId The current user
@return boolean True when something changed | entailment |
public function getEveryStatus()
{
static $status;
if ($status) {
return $status;
}
$status = array(
'U' => $this->_('Valid from date unknown'),
'W' => $this->_('Valid from date in the future'),
'O' => $this->_('Open - can be answered now'),
'P' => $this->_('Open - partially answered'),
'A' => $this->_('Answered'),
'I' => $this->_('Incomplete - missed deadline'),
'M' => $this->_('Missed deadline'),
'D' => $this->_('Token does not exist'),
);
return $status;
} | Returns a status code => decription array
@static $status array
@return array | entailment |
public function getStatusDescription($value)
{
$status = $this->getEveryStatus();
if (isset($status[$value])) {
return $status[$value];
}
return $status['D'];
} | Returns the description to add to the answer
@param string $value Character
@return string | entailment |
public function getStatusIcon($value)
{
$status = $this->getStatusIcons();
if (isset($status[$value])) {
return $status[$value];
}
return $status['D'];
} | Returns the decription to add to the answer
@param string $value Character
@return string | entailment |
public function getStatusIcons()
{
static $status;
if (is_null($status)) {
$spanU = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanU->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanU->i(array('class' => 'fa fa-question fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanW = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanW->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanW->i(array('class' => 'fa fa-ellipsis-h fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanO = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanO->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanO->i(array('class' => 'fa fa-play fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanA = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanA->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanA->i(array('class' => 'fa fa-check fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanP = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanP->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanP->i(array('class' => 'fa fa-pause fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanI = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanI->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanI->i(array('class' => 'fa fa-stop fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanM = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanM->i(array('class' => 'fa fa-circle fa-stack-2x', 'renderClosingTag' => true));
$spanM->i(array('class' => 'fa fa-lock fa-stack-1x fa-inverse', 'renderClosingTag' => true));
$spanD = \MUtil_Html::create('span', array('class' => 'fa-stack', 'renderClosingTag' => true));
$spanD->i(array('class' => 'fa fa-times fa-stack-2x', 'renderClosingTag' => true));
$status = array(
'U' => $spanU,
'W' => $spanW,
'O' => $spanO,
'A' => $spanA,
'P' => $spanP,
'I' => $spanI,
'M' => $spanM,
'D' => $spanD,
);
foreach ($status as $val => $stat) {
$stat->appendAttrib('class', $this->getStatusClass($val));
}
}
return $status;
} | Returns the status icons in an array
@return array | entailment |
public function getTokenAnswerLink($tokenId, $tokenStatus, $keepCaps)
{
if ('A' == $tokenStatus || 'P' == $tokenStatus || 'I' == $tokenStatus) {
$menuItem = $this->_getAnswerMenuItem();
$label = $menuItem->get('label');
$link = $menuItem->toActionLink(
($keepCaps ? $label : strtolower($label)),
[
'gto_id_token' => $tokenId,
'gto_in_source' => 1,
\Gems_Model::ID_TYPE => 'token',
]);
if ($link) {
$link->title = sprintf($this->_('See answers for token %s'), strtoupper($tokenId));
return $link;
}
}
} | Generate a menu link for answers pop-up
@param string $tokenId
@param string $tokenStatus
@param boolean $keepCaps Keep the capital letters in the label
@return \MUtil_Html_AElement | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.